context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using Abp.Dependency; using Abp.Domain.Uow; using Abp.EntityFramework; using Abp.MultiTenancy; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; namespace Abp.EntityFrameworkCore.Uow { /// <summary> /// Implements Unit of work for Entity Framework. /// </summary> public class EfCoreUnitOfWork : UnitOfWorkBase, ITransientDependency { protected IDictionary<string, DbContext> ActiveDbContexts { get; } protected IIocResolver IocResolver { get; } private readonly IDbContextResolver _dbContextResolver; private readonly IDbContextTypeMatcher _dbContextTypeMatcher; private readonly IEfCoreTransactionStrategy _transactionStrategy; /// <summary> /// Creates a new <see cref="EfCoreUnitOfWork"/>. /// </summary> public EfCoreUnitOfWork( IIocResolver iocResolver, IConnectionStringResolver connectionStringResolver, IUnitOfWorkFilterExecuter filterExecuter, IDbContextResolver dbContextResolver, IUnitOfWorkDefaultOptions defaultOptions, IDbContextTypeMatcher dbContextTypeMatcher, IEfCoreTransactionStrategy transactionStrategy) : base( connectionStringResolver, defaultOptions, filterExecuter) { IocResolver = iocResolver; _dbContextResolver = dbContextResolver; _dbContextTypeMatcher = dbContextTypeMatcher; _transactionStrategy = transactionStrategy; ActiveDbContexts = new Dictionary<string, DbContext>(StringComparer.OrdinalIgnoreCase); } protected override void BeginUow() { if (Options.IsTransactional == true) { _transactionStrategy.InitOptions(Options); } } public override void SaveChanges() { foreach (var dbContext in GetAllActiveDbContexts()) { SaveChangesInDbContext(dbContext); } } public override async Task SaveChangesAsync() { foreach (var dbContext in GetAllActiveDbContexts()) { await SaveChangesInDbContextAsync(dbContext); } } protected override void CompleteUow() { SaveChanges(); CommitTransaction(); } protected override async Task CompleteUowAsync() { await SaveChangesAsync(); CommitTransaction(); } private void CommitTransaction() { if (Options.IsTransactional == true) { _transactionStrategy.Commit(); } } public IReadOnlyList<DbContext> GetAllActiveDbContexts() { return ActiveDbContexts.Values.ToImmutableList(); } public virtual async Task<TDbContext> GetOrCreateDbContextAsync<TDbContext>( MultiTenancySides? multiTenancySide = null, string name = null) where TDbContext : DbContext { var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext)); var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide) { ["DbContextType"] = typeof(TDbContext), ["DbContextConcreteType"] = concreteDbContextType }; var connectionString = await ResolveConnectionStringAsync(connectionStringResolveArgs); var dbContextKey = concreteDbContextType.FullName + "#" + connectionString; if (name != null) { dbContextKey += "#" + name; } if (ActiveDbContexts.TryGetValue(dbContextKey, out var dbContext)) { return (TDbContext) dbContext; } if (Options.IsTransactional == true) { dbContext = await _transactionStrategy .CreateDbContextAsync<TDbContext>(connectionString, _dbContextResolver); } else { dbContext = _dbContextResolver.Resolve<TDbContext>(connectionString, null); } if (dbContext is IShouldInitializeDcontext abpDbContext) { abpDbContext.Initialize(new AbpEfDbContextInitializationContext(this)); } ActiveDbContexts[dbContextKey] = dbContext; return (TDbContext) dbContext; } public virtual TDbContext GetOrCreateDbContext<TDbContext>( MultiTenancySides? multiTenancySide = null, string name = null) where TDbContext : DbContext { var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext)); var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide) { ["DbContextType"] = typeof(TDbContext), ["DbContextConcreteType"] = concreteDbContextType }; var connectionString = ResolveConnectionString(connectionStringResolveArgs); var dbContextKey = concreteDbContextType.FullName + "#" + connectionString; if (name != null) { dbContextKey += "#" + name; } if (ActiveDbContexts.TryGetValue(dbContextKey, out var dbContext)) { return (TDbContext) dbContext; } if (Options.IsTransactional == true) { dbContext = _transactionStrategy .CreateDbContext<TDbContext>(connectionString, _dbContextResolver); } else { dbContext = _dbContextResolver.Resolve<TDbContext>(connectionString, null); } if (dbContext is IShouldInitializeDcontext abpDbContext) { abpDbContext.Initialize(new AbpEfDbContextInitializationContext(this)); } ActiveDbContexts[dbContextKey] = dbContext; return (TDbContext) dbContext; } protected override void DisposeUow() { if (Options.IsTransactional == true) { _transactionStrategy.Dispose(IocResolver); } else { foreach (var context in GetAllActiveDbContexts()) { Release(context); } } ActiveDbContexts.Clear(); } protected virtual void SaveChangesInDbContext(DbContext dbContext) { dbContext.SaveChanges(); } protected virtual Task SaveChangesInDbContextAsync(DbContext dbContext) { return dbContext.SaveChangesAsync(); } protected virtual void Release(DbContext dbContext) { dbContext.Dispose(); IocResolver.Release(dbContext); } //private static void ObjectContext_ObjectMaterialized(DbContext dbContext, ObjectMaterializedEventArgs e) //{ // var entityType = ObjectContext.GetObjectType(e.Entity.GetType()); // dbContext.Configuration.AutoDetectChangesEnabled = false; // var previousState = dbContext.Entry(e.Entity).State; // DateTimePropertyInfoHelper.NormalizeDatePropertyKinds(e.Entity, entityType); // dbContext.Entry(e.Entity).State = previousState; // dbContext.Configuration.AutoDetectChangesEnabled = 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractSByte() { var test = new SimpleBinaryOpTest__SubtractSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractSByte { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(SByte); private static SByte[] _data1 = new SByte[ElementCount]; private static SByte[] _data2 = new SByte[ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private SimpleBinaryOpTest__DataTable<SByte> _dataTable; static SimpleBinaryOpTest__SubtractSByte() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__SubtractSByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<SByte>(_data1, _data2, new SByte[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Subtract( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Subtract( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Subtract( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractSByte(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[ElementCount]; SByte[] inArray2 = new SByte[ElementCount]; SByte[] outArray = new SByte[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[ElementCount]; SByte[] inArray2 = new SByte[ElementCount]; SByte[] outArray = new SByte[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { if ((sbyte)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((sbyte)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<SByte>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
namespace Dispatcher { using System; using System.Collections.Generic; using Contracts; public class EventDispatcher : IEventDispatcher, IDisposable { private readonly Dictionary<Type, List<IEventHandler>> _eventHandlers = new Dictionary<Type, List<IEventHandler>>(); private bool _disposed; private readonly object _syncObject = new object(); public void Subscribe<T, TArg>(Action<TArg> action) where T : class where TArg : class, IEventArgument<T> { lock (this._syncObject) { var type = typeof (TArg); this.UpdateHandlers(type); this._eventHandlers[type].Add(new ActionEventHandler<TArg>(action)); } } private void UpdateHandlers(Type type) { if (!this._eventHandlers.ContainsKey(type)) this._eventHandlers[type] = new List<IEventHandler>(); } public void Subscribe<T, TArg>(IEventHandler<T, TArg> eventHendler) where T : class, IEvent<TArg>, new() where TArg : class, IEventArgument<T> { lock (this._syncObject) { var type = typeof (TArg); this.UpdateHandlers(type); this._eventHandlers[type].Add(eventHendler); } } public void Subscribe<TArg>(Action<TArg> action) where TArg : class, IEventArgument { lock (this._syncObject) { var type = typeof (TArg); this.UpdateHandlers(type); this._eventHandlers[type].Add(new ActionEventHandler<TArg>(action)); } } public void Subscribe<TArg>(IEventHandler<TArg> eventHendler) where TArg : class, IEventArgument { lock (this._syncObject) { var type = typeof (TArg); this.UpdateHandlers(type); this._eventHandlers[type].Add(eventHendler); } } public void Unsubscribe<T, TArg>(Action<TArg> action) where T : class where TArg : class, IEventArgument<T> { lock (this._syncObject) { var type = typeof (TArg); this.UpdateHandlers(type); this._eventHandlers[type].RemoveAll( x => x is ActionEventHandler<TArg> && ((ActionEventHandler<TArg>) x).IsAction(action)); } } public void Unsubscribe<TArg>(Action<TArg> action) where TArg : class, IEventArgument { lock (this._syncObject) { var type = typeof (TArg); this.UpdateHandlers(type); this._eventHandlers[type].RemoveAll( x => x is ActionEventHandler<TArg> && ((ActionEventHandler<TArg>) x).IsAction(action)); } } public void Unsubscribe<T, TArg>(IEventHandler<T, TArg> eventHendler) where T : class, IEvent<TArg>, new() where TArg : class, IEventArgument<T> { lock (this._syncObject) { var type = typeof (TArg); this.UpdateHandlers(type); this._eventHandlers[type].RemoveAll(x => x == eventHendler); } } public void Unsubscribe<TArg>(IEventHandler<TArg> eventHendler) where TArg : class, IEventArgument { lock (this._syncObject) { var type = typeof (TArg); this.UpdateHandlers(type); this._eventHandlers[type].RemoveAll(x => x == eventHendler); } } public void OnNext<T, TArg>(TArg args) where T : class, IEvent<TArg>, new() where TArg : class, IEventArgument<T> { lock (this._syncObject) { var type = typeof (TArg); if (!this._eventHandlers.ContainsKey(type)) return; this._eventHandlers[type].ForEach(x => this.Execute<T, TArg>(args, x)); } } private void Execute<T, TArg>(TArg argument, IEventHandler eventHandler) where TArg : class, IEventArgument<T> where T : class, IEvent<TArg>, new() { if (this._context == null || this._context.IsDisposed) { eventHandler.OnNext(argument); } else { this._context.Add<T, TArg>(eventHandler, argument); } } #region Observable pattern //public ISubject<IEventArgument> GetSubject<TArg>() // where TArg : class //{ // var type = typeof(TArg); // if (!this._eventHandlers.ContainsKey(type)) // this._eventHandlers[type] = new Subject<IEventArgument>(); // return this._eventHandlers[type]; //} //public void OnCompleted<T, TArg>(TArg args) // where T : class // where TArg : class, IEventArgument<T> //{ // var type = typeof(TArg); // if (!this._eventHandlers.ContainsKey(type)) // return; // _eventHandlers[type].OnCompleted(); //} //public void OnError<T>(Exception e) // where T : class //{ // var type = typeof(T); // if (!this._eventHandlers.ContainsKey(type)) // return; // this._eventHandlers[type].OnError(e); //} //public void OnError(Exception error) //{ // var type = typeof(Unknown); // if (!this._eventHandlers.ContainsKey(type)) // return; // this._eventHandlers[type].OnError(error); //} //public void OnCompleted() //{ // var type = typeof(Unknown); // if (!this._eventHandlers.ContainsKey(type)) // return; // this._eventHandlers[type].OnCompleted(); //} #endregion #region Implementation of IDisposable public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { lock (this._syncObject) { if (this._disposed) return; if (disposing) { this._eventHandlers?.Clear(); } this._disposed = true; } } ~EventDispatcher() { this.Dispose(false); } #endregion private IEventDispatcherContext _context; public IDisposable CreateContext() { if (this._context != null && !this._context.IsDisposed) throw new InvalidOperationException("context exists"); return this._context = new EventDispatcherContext(); } } }
// // Mono.Data.SybaseTypes.SybaseDecimal // // Author: // Tim Coleman <tim@timcoleman.com> // // Based on System.Data.SqlTypes.SqlDecimal // // (C) Ximian, Inc. 2002-2003 // (C) Copyright Tim Coleman, 2002 // // // 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 Mono.Data.Tds.Protocol; using System; using System.Data.SqlTypes; using System.Globalization; using System.Text; namespace Mono.Data.SybaseTypes { public struct SybaseDecimal : INullable, IComparable { #region Fields int[] value; byte precision; byte scale; bool positive; bool notNull; // borrowed from System.Decimal const int SCALE_SHIFT = 16; const int SIGN_SHIFT = 31; const int RESERVED_SS32_BITS = 0x7F00FFFF; const ulong LIT_GUINT64_HIGHBIT = 0x8000000000000000; const ulong LIT_GUINT32_HIGHBIT = 0x80000000; const byte DECIMAL_MAX_INTFACTORS = 9; static uint [] constantsDecadeInt32Factors = new uint [10] { 1u, 10u, 100u, 1000u, 10000u, 100000u, 1000000u, 10000000u, 100000000u, 1000000000u }; public static readonly byte MaxPrecision = 38; public static readonly byte MaxScale = 38; public static readonly SybaseDecimal MaxValue = new SybaseDecimal (MaxPrecision, (byte)0, true, (int)716002642, Int32.MaxValue, (int)1518778966, (int)1262177448); public static readonly SybaseDecimal MinValue = new SybaseDecimal (MaxPrecision, (byte)0, false, (int)716002642, Int32.MaxValue, (int)1518778966, (int)1262177448); public static readonly SybaseDecimal Null; #endregion #region Constructors public SybaseDecimal (decimal value) { int[] binData = Decimal.GetBits (value); this.scale = (byte)(binData[3] >> SCALE_SHIFT); if (this.scale > MaxScale || (this.scale & RESERVED_SS32_BITS) != 0) throw new ArgumentException(Locale.GetText ("Invalid scale")); this.value = new int[4]; this.value[0] = binData[0]; this.value[1] = binData[1]; this.value[2] = binData[2]; this.value[3] = 0; notNull = true; positive = (value >= 0); precision = GetPrecision (value); } public SybaseDecimal (double value) : this ((decimal)value) { } public SybaseDecimal (int value) : this ((decimal)value) { } public SybaseDecimal (long value) : this ((decimal)value) { } public SybaseDecimal (byte bPrecision, byte bScale, bool fPositive, int[] bits) : this (bPrecision, bScale, fPositive, bits[0], bits[1], bits[2], bits[3]) { } public SybaseDecimal (byte bPrecision, byte bScale, bool fPositive, int data1, int data2, int data3, int data4) { this.precision = bPrecision; this.scale = bScale; this.positive = fPositive; this.value = new int[4]; this.value[0] = data1; this.value[1] = data2; this.value[2] = data3; this.value[3] = data4; notNull = true; if (precision < scale) throw new ArgumentException ("Invalid scale"); if (this.ToDouble () > (System.Math.Pow (10, 38) -1) || this.ToDouble () < -(System.Math.Pow (10, 38))) throw new SybaseTypeException ("Can't convert to SybaseDecimal."); } #endregion #region Properties public byte[] BinData { get { byte[] b = new byte [value.Length * 4]; int j = 0; for (int i = 0; i < value.Length; i += 1) { b [j++] = (byte) (0xff & value [i]); b [j++] = (byte) (0xff & value [i] >> 8); b [j++] = (byte) (0xff & value [i] >> 16); b [j++] = (byte) (0xff & value [i] >> 24); } return b; } } public int[] Data { get { if (this.IsNull) throw new SybaseNullValueException (); else return (value); } } public bool IsNull { get { return !notNull; } } public bool IsPositive { get { return positive; } } public byte Precision { get { return precision; } } public byte Scale { get { return scale; } } public decimal Value { get { if (this.IsNull) throw new SybaseNullValueException (); if (this.value[3] > 0) throw new OverflowException (); return new decimal (value[0], value[1], value[2], !positive, scale); } } #endregion #region Methods public static SybaseDecimal Abs (SybaseDecimal n) { return new SybaseDecimal (n.Precision, n.Scale, true, n.BinData [0], n.BinData [1], n.BinData [2], n.BinData [3]); } public static SybaseDecimal Add (SybaseDecimal x, SybaseDecimal y) { return (x + y); } public static SybaseDecimal AdjustScale (SybaseDecimal n, int digits, bool fRound) { byte prec = n.Precision; if (n.IsNull) throw new SybaseNullValueException (); if (digits > 0) prec = (byte) (prec + digits); if (fRound) n = Round (n, digits + n.Scale); return new SybaseDecimal (prec, (byte) (n.Scale + digits), n.IsPositive, n.Data); } public static SybaseDecimal Ceiling (SybaseDecimal n) { return AdjustScale (n, -(n.Scale), true); } public int CompareTo (object value) { if (value == null) return 1; else if (!(value is SybaseDecimal)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SybaseTypes.SybaseDecimal")); else if (((SybaseDecimal)value).IsNull) return 1; else return this.Value.CompareTo (((SybaseDecimal)value).Value); } public static SybaseDecimal ConvertToPrecScale (SybaseDecimal n, int precision, int scale) { return new SybaseDecimal ((byte) precision, (byte) scale, n.IsPositive, n.Data); } public static SybaseDecimal Divide (SybaseDecimal x, SybaseDecimal y) { return (x / y); } public override bool Equals (object value) { if (!(value is SybaseDecimal)) return false; else if (this.IsNull && ((SybaseDecimal) value).IsNull) return true; else if (((SybaseDecimal) value).IsNull) return false; else return (bool) (this == (SybaseDecimal)value); } public static SybaseBoolean Equals (SybaseDecimal x, SybaseDecimal y) { return (x == y); } public static SybaseDecimal Floor (SybaseDecimal n) { return AdjustScale (n, -(n.Scale), false); } internal static SybaseDecimal FromTdsBigDecimal (TdsBigDecimal x) { if (x == null) return Null; else return new SybaseDecimal (x.Precision, x.Scale, !x.IsNegative, x.Data); } public override int GetHashCode () { int result = 10; result = 91 * result + this.Data [0]; result = 91 * result + this.Data [1]; result = 91 * result + this.Data [2]; result = 91 * result + this.Data [3]; result = 91 * result + (int) this.Scale; result = 91 * result + (int) this.Precision; return result; } public static SybaseBoolean GreaterThan (SybaseDecimal x, SybaseDecimal y) { return (x > y); } public static SybaseBoolean GreaterThanOrEqual (SybaseDecimal x, SybaseDecimal y) { return (x >= y); } public static SybaseBoolean LessThan (SybaseDecimal x, SybaseDecimal y) { return (x < y); } public static SybaseBoolean LessThanOrEqual (SybaseDecimal x, SybaseDecimal y) { return (x <= y); } public static SybaseDecimal Multiply (SybaseDecimal x, SybaseDecimal y) { return (x * y); } public static SybaseBoolean NotEquals (SybaseDecimal x, SybaseDecimal y) { return (x != y); } public static SybaseDecimal Parse (string s) { if (s == null) throw new ArgumentNullException (); else return SybaseDouble.Parse (s).ToSybaseDecimal (); } public static SybaseDecimal Power (SybaseDecimal n, double exp) { if (n.IsNull) return SybaseDecimal.Null; return new SybaseDecimal (System.Math.Pow (n.ToDouble (), exp)); } public static SybaseDecimal Round (SybaseDecimal n, int position) { if (n.IsNull) throw new SybaseNullValueException (); SybaseDecimal result = new SybaseDecimal (System.Math.Round ((double) (n.ToDouble () * System.Math.Pow (10, position)))); result = result / new SybaseDecimal (System.Math.Pow (10, position)); return result; } public static SybaseInt32 Sign (SybaseDecimal n) { SybaseInt32 result = 0; if (n >= new SybaseDecimal (0)) result = 1; else result = -1; return result; } public static SybaseDecimal Subtract (SybaseDecimal x, SybaseDecimal y) { return (x - y); } private static byte GetPrecision (decimal value) { string str = value.ToString (); byte result = 0; foreach (char c in str) if (c >= '0' && c <= '9') result ++; return result; } public double ToDouble () { // FIXME: This is the wrong way to do this double d = (uint) this.Data [0]; d += ((uint) this.Data [1]) * System.Math.Pow (2, 32); d += ((uint) this.Data [2]) * System.Math.Pow (2, 64); d += ((uint) this.Data [3]) * System.Math.Pow (2, 96); d /= System.Math.Pow (10, scale); return d; } public SybaseBoolean ToSybaseBoolean () { return ((SybaseBoolean)this); } public SybaseByte ToSybaseByte () { return ((SybaseByte)this); } public SybaseDouble ToSybaseDouble () { return ((SybaseDouble)this); } public SybaseInt16 ToSybaseInt16 () { return ((SybaseInt16)this); } public SybaseInt32 ToSybaseInt32 () { return ((SybaseInt32)this); } public SybaseInt64 ToSybaseInt64 () { return ((SybaseInt64)this); } public SybaseMoney ToSybaseMoney () { return ((SybaseMoney)this); } public SybaseSingle ToSybaseSingle () { return ((SybaseSingle)this); } public SybaseString ToSybaseString () { return ((SybaseString)this); } public override string ToString () { if (this.IsNull) return String.Empty; // convert int [4] -> ulong [2] ulong lo = (uint) this.Data [0] + (ulong) ((ulong) this.Data [1] << 32); ulong hi = (uint) this.Data [2] + (ulong) ((ulong) this.Data [3] << 32); uint rest = 0; StringBuilder result = new StringBuilder (); for (int i = 0; lo != 0 || hi != 0; i += 1) { Div128By32 (ref hi, ref lo, 10, ref rest); result.Insert (0, rest.ToString ()); } while (result.Length < Precision) result.Append ("0"); while (result.Length > Precision) result.Remove (result.Length - 1, 1); if (Scale > 0) result.Insert (result.Length - Scale, "."); return result.ToString (); } // from decimal.c private static int Div128By32 (ref ulong hi, ref ulong lo, uint divider) { uint t = 0; return Div128By32 (ref hi, ref lo, divider, ref t); } // from decimal.c private static int Div128By32 (ref ulong hi, ref ulong lo, uint divider, ref uint rest) { ulong a = 0; ulong b = 0; ulong c = 0; a = (uint) (hi >> 32); b = a / divider; a -= b * divider; a <<= 32; a |= (uint) hi; c = a / divider; a -= c * divider; a <<= 32; hi = b << 32 | (uint) c; a = (uint) (lo >> 32); b = a / divider; a -= b * divider; a <<= 32; a |= (uint) lo; c = a / divider; a -= c * divider; a <<= 32; lo = b << 32 | (uint) c; rest = (uint) a; a <<= 1; return (a > divider || (a == divider && (c & 1) == 1)) ? 1 : 0; } [MonoTODO ("Find out what is the right way to set scale and precision")] private static SybaseDecimal DecimalDiv (SybaseDecimal x, SybaseDecimal y) { ulong lo = 0; ulong hi = 0; int sc = 0; // scale int texp = 0; byte prec = 0; prec = x.Precision >= y.Precision ? x.Precision : y.Precision; DecimalDivSub (ref x, ref y, ref lo, ref hi, ref texp); sc = x.Scale - y.Scale; Rescale128 (ref lo, ref hi, ref sc, texp, 0, 38, 1); uint r = 0; while (prec < sc) { Div128By32 (ref hi, ref lo, 10, ref r); sc -= 1; } if (r >= 5) lo += 1; while ((((double) hi) * System.Math.Pow (2, 64) + lo) - System.Math.Pow (10, prec) > 0) prec += 1; while ((prec + sc) > MaxScale) { Div128By32 (ref hi, ref lo, 10, ref r); sc -= 1; if (r >= 5) lo += 1; } int resultLo = (int) lo; int resultMi = (int) (lo >> 32); int resultMi2 = (int) hi; int resultHi = (int) (hi >> 32); return new SybaseDecimal (prec, (byte) sc, true, resultLo, resultMi, resultMi2, resultHi); } // From decimal.c private static void Rescale128 (ref ulong clo, ref ulong chi, ref int scale, int texp, int minScale, int maxScale, int roundFlag) { uint factor = 0; uint overhang = 0; int sc = 0; int i = 0; int roundBit = 0; sc = scale; if (texp > 0) { // reduce exp while (texp > 0 && sc <= maxScale) { overhang = (uint) (chi >> 64); while (texp > 0 && (((clo & 1) == 0) || overhang > 0)) { if (--texp == 0) roundBit = (int) (clo & 1); RShift128 (ref clo, ref chi); overhang = (uint) (chi >> 32); } if (texp > DECIMAL_MAX_INTFACTORS) i = DECIMAL_MAX_INTFACTORS; else i = texp; if (sc + i > maxScale) i = maxScale - sc; if (i == 0) break; texp -= i; sc += i; // 10^i/2^i=5^i factor = constantsDecadeInt32Factors [i] >> i; Mult128By32 (ref clo, ref chi, factor, 0); } while (texp > 0) { if (--texp == 0) roundBit = (int) (clo & 1); RShift128 (ref clo, ref chi); } } while (sc > maxScale) { i = scale - maxScale; if (i > DECIMAL_MAX_INTFACTORS) i = DECIMAL_MAX_INTFACTORS; sc -= i; roundBit = Div128By32 (ref clo, ref chi, constantsDecadeInt32Factors [i]); } while (sc < minScale) { if (roundFlag == 0) roundBit = 0; i = minScale - sc; if (i > DECIMAL_MAX_INTFACTORS) i = DECIMAL_MAX_INTFACTORS; sc += i; Mult128By32 (ref clo, ref chi, constantsDecadeInt32Factors [i], roundBit); roundBit = 0; } scale = sc; Normalize128 (ref clo, ref chi, ref sc, roundFlag, roundBit); } // from decimal.c private static void Normalize128 (ref ulong clo, ref ulong chi, ref int scale, int roundFlag, int roundBit) { if ((roundFlag != 0) && (roundBit != 0)) RoundUp128 (ref clo, ref chi); } // from decimal.c private static void RoundUp128 (ref ulong lo, ref ulong hi) { if ((++lo) == 0) ++hi; } // from decimal.c private static void DecimalDivSub (ref SybaseDecimal x, ref SybaseDecimal y, ref ulong clo, ref ulong chi, ref int exp) { ulong xlo, xmi, xhi; ulong tlo = 0; ulong tmi = 0; ulong thi = 0; uint ylo = 0; uint ymi = 0; uint ymi2 = 0; uint yhi = 0; int ashift = 0; int bshift = 0; int extraBit = 0; xhi = (ulong) ((ulong) x.Data [3] << 32) | (ulong) x.Data [2]; xmi = (ulong) ((ulong) x.Data [1] << 32) | (ulong) x.Data [0]; xlo = (uint) 0; ylo = (uint) y.Data [0]; ymi = (uint) y.Data [1]; ymi2 = (uint) y.Data [2]; yhi = (uint) y.Data [3]; if (ylo == 0 && ymi == 0 && ymi2 == 0 && yhi == 0) throw new DivideByZeroException (); if (xmi == 0 && xhi == 0) { clo = chi = 0; return; } // enlarge dividend to get maximal precision for (ashift = 0; (xhi & LIT_GUINT64_HIGHBIT) == 0; ++ashift) LShift128 (ref xmi, ref xhi); // ensure that divisor is at least 2^95 for (bshift = 0; (yhi & LIT_GUINT32_HIGHBIT) == 0; ++bshift) LShift128 (ref ylo, ref ymi, ref ymi2, ref yhi); thi = ((ulong) yhi) << 32 | (ulong) ymi2; tmi = ((ulong) ymi) << 32 | (ulong) ylo; tlo = 0; if (xhi > thi || (xhi == thi && xmi >= tmi)) { Sub192 (xlo, xmi, xhi, tlo, tmi, thi, ref xlo, ref xmi, ref xhi); extraBit = 1; } else { extraBit = 0; } Div192By128To128 (xlo, xmi, xhi, ylo, ymi, ymi2, yhi, ref clo, ref chi); exp = 128 + ashift - bshift; if (extraBit != 0) { RShift128 (ref clo, ref chi); chi += LIT_GUINT64_HIGHBIT; exp -= 1; } // try loss free right shift while (exp > 0 && (clo & 1) == 0) { RShift128 (ref clo, ref chi); exp -= 1; } } // From decimal.c private static void RShift192 (ref ulong lo, ref ulong mi, ref ulong hi) { lo >>= 1; if ((mi & 1) != 0) lo |= LIT_GUINT64_HIGHBIT; mi >>= 1; if ((hi & 1) != 0) mi |= LIT_GUINT64_HIGHBIT; hi >>= 1; } // From decimal.c private static void RShift128 (ref ulong lo, ref ulong hi) { lo >>= 1; if ((hi & 1) != 0) lo |= LIT_GUINT64_HIGHBIT; hi >>= 1; } // From decimal.c private static void LShift128 (ref ulong lo, ref ulong hi) { hi <<= 1; if ((lo & LIT_GUINT64_HIGHBIT) != 0) hi += 1; lo <<= 1; } // From decimal.c private static void LShift128 (ref uint lo, ref uint mi, ref uint mi2, ref uint hi) { hi <<= 1; if ((mi2 & LIT_GUINT32_HIGHBIT) != 0) hi += 1; mi2 <<= 1; if ((mi & LIT_GUINT32_HIGHBIT) != 0) mi2 += 1; mi <<= 1; if ((lo & LIT_GUINT32_HIGHBIT) != 0) mi += 1; lo <<= 1; } // From decimal.c private static void Div192By128To128 (ulong xlo, ulong xmi, ulong xhi, uint ylo, uint ymi, uint ymi2, uint yhi, ref ulong clo, ref ulong chi) { ulong rlo, rmi, rhi; // remainders uint h, c; rlo = xlo; rmi = xmi; rhi = xhi; h = Div192By128To32WithRest (ref rlo, ref rmi, ref rhi, ylo, ymi, ymi2, yhi); // mid 32 bit rhi = (rhi << 32) | (rmi >> 32); rmi = (rmi << 32) | (rlo >> 32); rlo <<= 32; chi = (((ulong)h) << 32) | Div192By128To32WithRest (ref rlo, ref rmi, ref rhi, ylo, ymi, ymi2, yhi); // low 32 bit rhi = (rhi << 32) | (rmi >> 32); rmi = (rmi << 32) | (rlo >> 32); rlo <<= 32; h = Div192By128To32WithRest (ref rlo, ref rmi, ref rhi, ylo, ymi, ymi2, yhi); // estimate lowest 32 bit (two last bits may be wrong) if (rhi >= yhi) c = 0xFFFFFFFF; else { rhi <<= 32; c = (uint)(rhi / yhi); } clo = (((ulong)h) << 32) | c; } // From decimal.c private static uint Div192By128To32WithRest (ref ulong xlo, ref ulong xmi, ref ulong xhi, uint ylo, uint ymi, uint ymi2, uint yhi) { ulong rlo, rmi, rhi; // remainder ulong tlo = 0; ulong thi = 0; uint c; rlo = xlo; rmi = xmi; rhi = xhi; if (rhi >= (((ulong)yhi << 32))) c = 0xFFFFFFFF; else c = (uint) (rhi / yhi); Mult128By32To128 (ylo, ymi, ymi2, yhi, c, ref tlo, ref thi); Sub192 (rlo, rmi, rhi, 0, tlo, thi, ref rlo, ref rmi, ref rhi); while (((long)rhi) < 0) { c--; Add192 (rlo, rmi, rhi, 0, (((ulong)ymi) << 32) | ylo, yhi | ymi2, ref rlo, ref rmi, ref rhi); } xlo = rlo; xmi = rmi; xhi = rhi; return c; } // From decimal.c private static void Mult192By32 (ref ulong clo, ref ulong cmi, ref ulong chi, ulong factor, int roundBit) { ulong a = 0; uint h0 = 0; uint h1 = 0; a = ((ulong)(uint)clo) * factor; if (roundBit != 0) a += factor / 2; h0 = (uint)a; a >>= 32; a += (clo >> 32) * factor; h1 = (uint)a; clo = ((ulong)h1) << 32 | h0; a >>= 32; a += ((ulong)(uint)cmi) * factor; h0 = (uint)a; a >>= 32; a += (cmi >> 32) * factor; h1 = (uint)a; cmi = ((ulong)h1) << 32 | h0; a >>= 32; a += ((ulong)(uint)chi) * factor; h0 = (uint)a; a >>= 32; a += (chi >> 32) * factor; h1 = (uint)a; chi = ((ulong)h1) << 32 | h0; } // From decimal.c private static void Mult128By32 (ref ulong clo, ref ulong chi, uint factor, int roundBit) { ulong a = 0; uint h0 = 0; uint h1 = 0; a = ((ulong)(uint)clo) * factor; if (roundBit != 0) a += factor / 2; h0 = (uint)a; a >>= 32; a += (clo >> 32) * factor; h1 = (uint)a; clo = ((ulong)h1) << 32 | h0; a >>= 32; a += ((ulong)(uint)chi) * factor; h0 = (uint)a; a >>= 32; a += (chi >> 32) * factor; h1 = (uint)a; chi = ((ulong)h1) << 32 | h0; } // From decimal.c private static void Mult128By32To128 (uint xlo, uint xmi, uint xmi2, uint xhi, uint factor, ref ulong clo, ref ulong chi) { ulong a; uint h0, h1, h2; a = ((ulong)xlo) * factor; h0 = (uint)a; a >>= 32; a += ((ulong)xmi) * factor; h1 = (uint)a; a >>= 32; a += ((ulong)xmi2) * factor; h2 = (uint)a; a >>= 32; a += ((ulong)xhi) * factor; clo = ((ulong)h1) << 32 | h0; chi = a | h2; } // From decimal.c private static void Add192 (ulong xlo, ulong xmi, ulong xhi, ulong ylo, ulong ymi, ulong yhi, ref ulong clo, ref ulong cmi, ref ulong chi) { xlo += ylo; if (xlo < ylo) { xmi++; if (xmi == 0) xhi++; } xmi += ymi; if (xmi < ymi) xmi++; xhi += yhi; clo = xlo; cmi = xmi; chi = xhi; } // From decimal.c private static void Sub192 (ulong xlo, ulong xmi, ulong xhi, ulong ylo, ulong ymi, ulong yhi, ref ulong lo, ref ulong mi, ref ulong hi) { ulong clo = 0; ulong cmi = 0; ulong chi = 0; clo = xlo - ylo; cmi = xmi - ymi; chi = xhi - yhi; if (xlo < ylo) { if (cmi == 0) chi--; cmi--; } if (xmi < ymi) chi--; lo = clo; mi = cmi; hi = chi; } public static SybaseDecimal Truncate (SybaseDecimal n, int position) { return new SybaseDecimal ((byte) n.Precision, (byte) position, n.IsPositive, n.Data); } public static SybaseDecimal operator + (SybaseDecimal x, SybaseDecimal y) { // if one of them is negative, perform subtraction if (x.IsPositive && !y.IsPositive) return x - y; if (y.IsPositive && !x.IsPositive) return y - x; // adjust the scale to the smaller of the two beforehand if (x.Scale > y.Scale) x = SybaseDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SybaseDecimal.AdjustScale(y, x.Scale - y.Scale, true); // set the precision to the greater of the two byte resultPrecision; if (x.Precision > y.Precision) resultPrecision = x.Precision; else resultPrecision = y.Precision; int[] xData = x.Data; int[] yData = y.Data; int[] resultBits = new int[4]; ulong res; ulong carry = 0; // add one at a time, and carry the results over to the next for (int i = 0; i < 4; i +=1) { carry = 0; res = (ulong)(xData[i]) + (ulong)(yData[i]) + carry; if (res > Int32.MaxValue) { carry = res - Int32.MaxValue; res = Int32.MaxValue; } resultBits [i] = (int)res; } // if we have carry left, then throw an exception if (carry > 0) throw new OverflowException (); else return new SybaseDecimal (resultPrecision, x.Scale, x.IsPositive, resultBits); } public static SybaseDecimal operator / (SybaseDecimal x, SybaseDecimal y) { return DecimalDiv (x, y); } public static SybaseBoolean operator == (SybaseDecimal x, SybaseDecimal y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; if (x.Scale > y.Scale) x = SybaseDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SybaseDecimal.AdjustScale(y, x.Scale - y.Scale, true); for (int i = 0; i < 4; i += 1) { if (x.Data[i] != y.Data[i]) return new SybaseBoolean (false); } return new SybaseBoolean (true); } public static SybaseBoolean operator > (SybaseDecimal x, SybaseDecimal y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; if (x.Scale > y.Scale) x = SybaseDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SybaseDecimal.AdjustScale(y, x.Scale - y.Scale, true); for (int i = 3; i >= 0; i -= 1) { if (x.Data[i] == 0 && y.Data[i] == 0) continue; else return new SybaseBoolean (x.Data[i] > y.Data[i]); } return new SybaseBoolean (false); } public static SybaseBoolean operator >= (SybaseDecimal x, SybaseDecimal y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; if (x.Scale > y.Scale) x = SybaseDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SybaseDecimal.AdjustScale(y, x.Scale - y.Scale, true); for (int i = 3; i >= 0; i -= 1) { if (x.Data[i] == 0 && y.Data[i] == 0) continue; else return new SybaseBoolean (x.Data[i] >= y.Data[i]); } return new SybaseBoolean (true); } public static SybaseBoolean operator != (SybaseDecimal x, SybaseDecimal y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; if (x.Scale > y.Scale) x = SybaseDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SybaseDecimal.AdjustScale(y, x.Scale - y.Scale, true); for (int i = 0; i < 4; i += 1) { if (x.Data[i] != y.Data[i]) return new SybaseBoolean (true); } return new SybaseBoolean (false); } public static SybaseBoolean operator < (SybaseDecimal x, SybaseDecimal y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; if (x.Scale > y.Scale) x = SybaseDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SybaseDecimal.AdjustScale(y, x.Scale - y.Scale, true); for (int i = 3; i >= 0; i -= 1) { if (x.Data[i] == 0 && y.Data[i] == 0) continue; return new SybaseBoolean (x.Data[i] < y.Data[i]); } return new SybaseBoolean (false); } public static SybaseBoolean operator <= (SybaseDecimal x, SybaseDecimal y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; if (x.Scale > y.Scale) x = SybaseDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SybaseDecimal.AdjustScale(y, x.Scale - y.Scale, true); for (int i = 3; i >= 0; i -= 1) { if (x.Data[i] == 0 && y.Data[i] == 0) continue; else return new SybaseBoolean (x.Data[i] <= y.Data[i]); } return new SybaseBoolean (true); } public static SybaseDecimal operator * (SybaseDecimal x, SybaseDecimal y) { // adjust the scale to the smaller of the two beforehand if (x.Scale > y.Scale) x = SybaseDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SybaseDecimal.AdjustScale(y, x.Scale - y.Scale, true); // set the precision to the greater of the two byte resultPrecision; if (x.Precision > y.Precision) resultPrecision = x.Precision; else resultPrecision = y.Precision; int[] xData = x.Data; int[] yData = y.Data; int[] resultBits = new int[4]; ulong res; ulong carry = 0; // multiply one at a time, and carry the results over to the next for (int i = 0; i < 4; i +=1) { carry = 0; res = (ulong)(xData[i]) * (ulong)(yData[i]) + carry; if (res > Int32.MaxValue) { carry = res - Int32.MaxValue; res = Int32.MaxValue; } resultBits [i] = (int)res; } // if we have carry left, then throw an exception if (carry > 0) throw new OverflowException (); else return new SybaseDecimal (resultPrecision, x.Scale, (x.IsPositive == y.IsPositive), resultBits); } public static SybaseDecimal operator - (SybaseDecimal x, SybaseDecimal y) { if (x.IsPositive && !y.IsPositive) return x + y; if (!x.IsPositive && y.IsPositive) return -(x + y); if (!x.IsPositive && !y.IsPositive) return y - x; // otherwise, x is positive and y is positive bool resultPositive = (bool)(x > y); int[] yData = y.Data; for (int i = 0; i < 4; i += 1) yData[i] = -yData[i]; SybaseDecimal yInverse = new SybaseDecimal (y.Precision, y.Scale, y.IsPositive, yData); if (resultPositive) return x + yInverse; else return -(x + yInverse); } public static SybaseDecimal operator - (SybaseDecimal n) { return new SybaseDecimal (n.Precision, n.Scale, !n.IsPositive, n.Data); } public static explicit operator SybaseDecimal (SybaseBoolean x) { if (x.IsNull) return Null; else return new SybaseDecimal ((decimal)x.ByteValue); } public static explicit operator Decimal (SybaseDecimal n) { return n.Value; } public static explicit operator SybaseDecimal (SybaseDouble x) { if (x.IsNull) return Null; else return new SybaseDecimal ((decimal)x.Value); } public static explicit operator SybaseDecimal (SybaseSingle x) { if (x.IsNull) return Null; else return new SybaseDecimal ((decimal)x.Value); } [MonoTODO] public static explicit operator SybaseDecimal (SybaseString x) { throw new NotImplementedException (); } public static implicit operator SybaseDecimal (decimal x) { return new SybaseDecimal (x); } public static implicit operator SybaseDecimal (SybaseByte x) { if (x.IsNull) return Null; else return new SybaseDecimal ((decimal)x.Value); } public static implicit operator SybaseDecimal (SybaseInt16 x) { if (x.IsNull) return Null; else return new SybaseDecimal ((decimal)x.Value); } public static implicit operator SybaseDecimal (SybaseInt32 x) { if (x.IsNull) return Null; else return new SybaseDecimal ((decimal)x.Value); } public static implicit operator SybaseDecimal (SybaseInt64 x) { if (x.IsNull) return Null; else return new SybaseDecimal ((decimal)x.Value); } public static implicit operator SybaseDecimal (SybaseMoney x) { if (x.IsNull) return Null; else return new SybaseDecimal ((decimal)x.Value); } #endregion } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using Newtonsoft.Json.Utilities; using System.IO; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON array. /// </summary> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" /> /// </example> public class JArray : JContainer, IList<JToken> { private readonly List<JToken> _values = new List<JToken>(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _values; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return JTokenType.Array; } } /// <summary> /// Initializes a new instance of the <see cref="JArray"/> class. /// </summary> public JArray() { } /// <summary> /// Initializes a new instance of the <see cref="JArray"/> class from another <see cref="JArray"/> object. /// </summary> /// <param name="other">A <see cref="JArray"/> object to copy from.</param> public JArray(JArray other) : base(other) { } /// <summary> /// Initializes a new instance of the <see cref="JArray"/> class with the specified content. /// </summary> /// <param name="content">The contents of the array.</param> public JArray(params object[] content) : this((object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JArray"/> class with the specified content. /// </summary> /// <param name="content">The contents of the array.</param> public JArray(object content) { Add(content); } internal override bool DeepEquals(JToken node) { JArray t = node as JArray; return (t != null && ContentsEqual(t)); } internal override JToken CloneToken() { return new JArray(this); } /// <summary> /// Loads an <see cref="JArray"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JArray"/>.</param> /// <returns>A <see cref="JArray"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JArray Load(JsonReader reader) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader."); } while (reader.TokenType == JsonToken.Comment) { reader.Read(); } if (reader.TokenType != JsonToken.StartArray) throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JArray a = new JArray(); a.SetLineInfo(reader as IJsonLineInfo); a.ReadTokenFrom(reader); return a; } /// <summary> /// Load a <see cref="JArray"/> from a string that contains JSON. /// </summary> /// <param name="json">A <see cref="String"/> that contains JSON.</param> /// <returns>A <see cref="JArray"/> populated from the string that contains JSON.</returns> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" /> /// </example> public static new JArray Parse(string json) { JsonReader reader = new JsonTextReader(new StringReader(json)); JArray a = Load(reader); if (reader.Read() && reader.TokenType != JsonToken.Comment) throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); return a; } /// <summary> /// Creates a <see cref="JArray"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JArray"/>.</param> /// <returns>A <see cref="JArray"/> with the values of the specified object</returns> public static new JArray FromObject(object o) { return FromObject(o, JsonSerializer.CreateDefault()); } /// <summary> /// Creates a <see cref="JArray"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JArray"/>.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param> /// <returns>A <see cref="JArray"/> with the values of the specified object</returns> public static new JArray FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); if (token.Type != JTokenType.Array) throw new ArgumentException("Object serialized to {0}. JArray instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); return (JArray)token; } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartArray(); for (int i = 0; i < _values.Count; i++) { _values[i].WriteTo(writer, converters); } writer.WriteEndArray(); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Accessed JArray values with invalid key value: {0}. Array position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); return GetItem((int)key); } set { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Set JArray values with invalid key value: {0}. Array position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); SetItem((int)key, value); } } /// <summary> /// Gets or sets the <see cref="Newtonsoft.Json.Linq.JToken"/> at the specified index. /// </summary> /// <value></value> public JToken this[int index] { get { return GetItem(index); } set { SetItem(index, value); } } #region IList<JToken> Members /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> public int IndexOf(JToken item) { return IndexOfItem(item); } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception> public void Insert(int index, JToken item) { InsertItem(index, item, false); } /// <summary> /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception> public void RemoveAt(int index) { RemoveItemAt(index); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. /// </returns> public IEnumerator<JToken> GetEnumerator() { return Children().GetEnumerator(); } #endregion #region ICollection<JToken> Members /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public void Add(JToken item) { Add((object)item); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception> public void Clear() { ClearItems(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> public bool Contains(JToken item) { return ContainsItem(item); } /// <summary> /// Copies to. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> public void CopyTo(JToken[] array, int arrayIndex) { CopyItemsTo(array, arrayIndex); } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. /// </summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.</returns> public bool IsReadOnly { get { return false; } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public bool Remove(JToken item) { return RemoveItem(item); } #endregion internal override int GetDeepHashCode() { return ContentsHashCode(); } } } #endif
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Text; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif ASPNETCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Tests.Serialization; using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JTokenReaderTest : TestFixtureBase { [Test] public void ErrorTokenIndex() { JObject json = JObject.Parse(@"{""IntList"":[1, ""two""]}"); ExceptionAssert.Throws<Exception>(() => { JsonSerializer serializer = new JsonSerializer(); serializer.Deserialize<TraceTestObject>(json.CreateReader()); }, "Could not convert string to integer: two. Path 'IntList[1]', line 1, position 20."); } #if !NET20 [Test] public void YahooFinance() { JObject o = new JObject( new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)), new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))), new JProperty("Test3", "Test3Value"), new JProperty("Test4", null) ); using (JTokenReader jsonReader = new JTokenReader(o)) { IJsonLineInfo lineInfo = jsonReader; jsonReader.Read(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); Assert.AreEqual(false, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); Assert.AreEqual(false, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), jsonReader.Value); Assert.AreEqual(false, lineInfo.HasLineInfo()); Assert.AreEqual(0, lineInfo.LinePosition); Assert.AreEqual(0, lineInfo.LineNumber); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test2", jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test3", jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.String, jsonReader.TokenType); Assert.AreEqual("Test3Value", jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test4", jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Null, jsonReader.TokenType); Assert.AreEqual(null, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); Assert.IsFalse(jsonReader.Read()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } using (JsonReader jsonReader = new JTokenReader(o.Property("Test2"))) { Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test2", jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value); Assert.IsFalse(jsonReader.Read()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } } [Test] public void ReadAsDateTimeOffsetBadString() { string json = @"{""Offset"":""blablahbla""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTimeOffset(); }, "Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22."); } [Test] public void ReadAsDateTimeOffsetBoolean() { string json = @"{""Offset"":true}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTimeOffset(); }, "Error reading date. Unexpected token: Boolean. Path 'Offset', line 1, position 14."); } [Test] public void ReadAsDateTimeOffsetString() { string json = @"{""Offset"":""2012-01-24T03:50Z""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); reader.ReadAsDateTimeOffset(); Assert.AreEqual(JsonToken.Date, reader.TokenType); Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType); Assert.AreEqual(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero), reader.Value); } #endif [Test] public void ReadLineInfo() { string input = @"{ CPU: 'Intel', Drives: [ 'DVD read/writer', ""500 gigabyte hard drive"" ] }"; StringReader sr = new StringReader(input); JObject o = JObject.Parse(input); using (JTokenReader jsonReader = new JTokenReader(o)) { IJsonLineInfo lineInfo = jsonReader; Assert.AreEqual(jsonReader.TokenType, JsonToken.None); Assert.AreEqual(0, lineInfo.LineNumber); Assert.AreEqual(0, lineInfo.LinePosition); Assert.AreEqual(false, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject); Assert.AreEqual(1, lineInfo.LineNumber); Assert.AreEqual(1, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.Value, "CPU"); Assert.AreEqual(2, lineInfo.LineNumber); Assert.AreEqual(7, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "Intel"); Assert.AreEqual(2, lineInfo.LineNumber); Assert.AreEqual(15, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.Value, "Drives"); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(10, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(12, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "DVD read/writer"); Assert.AreEqual(4, lineInfo.LineNumber); Assert.AreEqual(22, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "500 gigabyte hard drive"); Assert.AreEqual(5, lineInfo.LineNumber); Assert.AreEqual(30, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(12, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject); Assert.AreEqual(1, lineInfo.LineNumber); Assert.AreEqual(1, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.None); } } [Test] public void ReadBytes() { byte[] data = Encoding.UTF8.GetBytes("Hello world!"); JObject o = new JObject( new JProperty("Test1", data) ); using (JTokenReader jsonReader = new JTokenReader(o)) { jsonReader.Read(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); byte[] readBytes = jsonReader.ReadAsBytes(); Assert.AreEqual(data, readBytes); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); Assert.IsFalse(jsonReader.Read()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } } [Test] public void ReadBytesFailure() { ExceptionAssert.Throws<JsonReaderException>(() => { JObject o = new JObject( new JProperty("Test1", 1) ); using (JTokenReader jsonReader = new JTokenReader(o)) { jsonReader.Read(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); jsonReader.ReadAsBytes(); } }, "Error reading bytes. Unexpected token: Integer. Path 'Test1'."); } public class HasBytes { public byte[] Bytes { get; set; } } [Test] public void ReadBytesFromString() { var bytes = new HasBytes { Bytes = new byte[] { 1, 2, 3, 4 } }; var json = JsonConvert.SerializeObject(bytes); TextReader textReader = new StringReader(json); JsonReader jsonReader = new JsonTextReader(textReader); var jToken = JToken.ReadFrom(jsonReader); jsonReader = new JTokenReader(jToken); var result2 = (HasBytes)JsonSerializer.Create(null) .Deserialize(jsonReader, typeof(HasBytes)); CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, result2.Bytes); } [Test] public void ReadBytesFromEmptyString() { var bytes = new HasBytes { Bytes = new byte[0] }; var json = JsonConvert.SerializeObject(bytes); TextReader textReader = new StringReader(json); JsonReader jsonReader = new JsonTextReader(textReader); var jToken = JToken.ReadFrom(jsonReader); jsonReader = new JTokenReader(jToken); var result2 = (HasBytes)JsonSerializer.Create(null) .Deserialize(jsonReader, typeof(HasBytes)); CollectionAssert.AreEquivalent(new byte[0], result2.Bytes); } public class ReadAsBytesTestObject { public byte[] Data; } [Test] public void ReadAsBytesNull() { JsonSerializer s = new JsonSerializer(); JToken nullToken = JToken.ReadFrom(new JsonTextReader(new StringReader("{ Data: null }"))); ReadAsBytesTestObject x = s.Deserialize<ReadAsBytesTestObject>(new JTokenReader(nullToken)); Assert.IsNull(x.Data); } [Test] public void DeserializeByteArrayWithTypeNameHandling() { TestObject test = new TestObject("Test", new byte[] { 72, 63, 62, 71, 92, 55 }); string json = JsonConvert.SerializeObject(test, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); JObject o = JObject.Parse(json); JsonSerializer serializer = new JsonSerializer(); serializer.TypeNameHandling = TypeNameHandling.All; using (JsonReader nodeReader = o.CreateReader()) { // Get exception here TestObject newObject = (TestObject)serializer.Deserialize(nodeReader); Assert.AreEqual("Test", newObject.Name); CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data); } } [Test] public void DeserializeStringInt() { string json = @"{ ""PreProperty"": ""99"", ""PostProperty"": ""-1"" }"; JObject o = JObject.Parse(json); JsonSerializer serializer = new JsonSerializer(); using (JsonReader nodeReader = o.CreateReader()) { MyClass c = serializer.Deserialize<MyClass>(nodeReader); Assert.AreEqual(99, c.PreProperty); Assert.AreEqual(-1, c.PostProperty); } } [Test] public void ReadAsDecimalInt() { string json = @"{""Name"":1}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); Assert.AreEqual(typeof(decimal), reader.ValueType); Assert.AreEqual(1m, reader.Value); } [Test] public void ReadAsInt32Int() { string json = @"{""Name"":1}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); reader.ReadAsInt32(); Assert.AreEqual(JsonToken.Integer, reader.TokenType); Assert.AreEqual(typeof(int), reader.ValueType); Assert.AreEqual(1, reader.Value); } [Test] public void ReadAsInt32BadString() { string json = @"{""Name"":""hi""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Could not convert string to integer: hi. Path 'Name', line 1, position 12."); } [Test] public void ReadAsInt32Boolean() { string json = @"{""Name"":true}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Error reading integer. Unexpected token: Boolean. Path 'Name', line 1, position 12."); } [Test] public void ReadAsDecimalString() { string json = @"{""Name"":""1.1""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); Assert.AreEqual(typeof(decimal), reader.ValueType); Assert.AreEqual(1.1m, reader.Value); } [Test] public void ReadAsDecimalBadString() { string json = @"{""Name"":""blah""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDecimal(); }, "Could not convert string to decimal: blah. Path 'Name', line 1, position 14."); } [Test] public void ReadAsDecimalBoolean() { string json = @"{""Name"":true}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDecimal(); }, "Error reading decimal. Unexpected token: Boolean. Path 'Name', line 1, position 12."); } [Test] public void ReadAsDecimalNull() { string json = @"{""Name"":null}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Null, reader.TokenType); Assert.AreEqual(null, reader.ValueType); Assert.AreEqual(null, reader.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. //************************************************************************************************************* // For each dynamic assembly there will be two AssemblyBuilder objects: the "internal" // AssemblyBuilder object and the "external" AssemblyBuilder object. // 1. The "internal" object is the real assembly object that the VM creates and knows about. However, // you can perform RefEmit operations on it only if you have its granted permission. From the AppDomain // and other "internal" objects like the "internal" ModuleBuilders and runtime types, you can only // get the "internal" objects. This is to prevent low-trust code from getting a hold of the dynamic // AssemblyBuilder/ModuleBuilder/TypeBuilder/MethodBuilder/etc other people have created by simply // enumerating the AppDomain and inject code in it. // 2. The "external" object is merely an wrapper of the "internal" object and all operations on it // are directed to the internal object. This is the one you get by calling DefineDynamicAssembly // on AppDomain and the one you can always perform RefEmit operations on. You can get other "external" // objects from the "external" AssemblyBuilder, ModuleBuilder, TypeBuilder, MethodBuilder, etc. Note // that VM doesn't know about this object. So every time we call into the VM we need to pass in the // "internal" object. // // "internal" and "external" ModuleBuilders are similar //************************************************************************************************************* namespace System.Reflection.Emit { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.SymbolStore; using CultureInfo = System.Globalization.CultureInfo; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Policy; using System.Threading; // These must match the definitions in Assembly.hpp [Flags] internal enum DynamicAssemblyFlags { None = 0x00000000, // Security attributes which affect the module security descriptor AllCritical = 0x00000001, Aptca = 0x00000002, Critical = 0x00000004, Transparent = 0x00000008, TreatAsSafe = 0x00000010, } // When the user calls AppDomain.DefineDynamicAssembly the loader creates a new InternalAssemblyBuilder. // This InternalAssemblyBuilder can be retrieved via a call to Assembly.GetAssemblies() by untrusted code. // In the past, when InternalAssemblyBuilder was AssemblyBuilder, the untrusted user could down cast the // Assembly to an AssemblyBuilder and emit code with the elevated permissions of the trusted code which // origionally created the AssemblyBuilder via DefineDynamicAssembly. Today, this can no longer happen // because the Assembly returned via AssemblyGetAssemblies() will be an InternalAssemblyBuilder. // Only the caller of DefineDynamicAssembly will get an AssemblyBuilder. // There is a 1-1 relationship between InternalAssemblyBuilder and AssemblyBuilder. // AssemblyBuilder is composed of its InternalAssemblyBuilder. // The AssemblyBuilder data members (e.g. m_foo) were changed to properties which then delegate // the access to the composed InternalAssemblyBuilder. This way, AssemblyBuilder simply wraps // InternalAssemblyBuilder and still operates on InternalAssemblyBuilder members. // This also makes the change transparent to the loader. This is good because most of the complexity // of Assembly building is in the loader code so not touching that code reduces the chance of // introducing new bugs. internal sealed class InternalAssemblyBuilder : RuntimeAssembly { private InternalAssemblyBuilder() { } #region object overrides public override bool Equals(object obj) { if (obj == null) return false; if (obj is InternalAssemblyBuilder) return ((object)this == obj); return obj.Equals(this); } // Need a dummy GetHashCode to pair with Equals public override int GetHashCode() { return base.GetHashCode(); } #endregion // Assembly methods that are overridden by AssemblyBuilder should be overridden by InternalAssemblyBuilder too #region Methods inherited from Assembly public override String[] GetManifestResourceNames() { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override FileStream GetFile(String name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override FileStream[] GetFiles(bool getResourceModules) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override Stream GetManifestResourceStream(Type type, String name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override Stream GetManifestResourceStream(String name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override ManifestResourceInfo GetManifestResourceInfo(String resourceName) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override String Location { get { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } } public override String CodeBase { get { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } } public override Type[] GetExportedTypes() { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override String ImageRuntimeVersion { get { return RuntimeEnvironment.GetSystemVersion(); } } #endregion } // AssemblyBuilder class. // deliberately not [serializable] public sealed class AssemblyBuilder : Assembly { #region FCALL [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly); private Module nGetInMemoryAssemblyModule() { return AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle()); } #endregion #region Internal Data Members // This is only valid in the "external" AssemblyBuilder internal AssemblyBuilderData m_assemblyData; private InternalAssemblyBuilder m_internalAssemblyBuilder; private ModuleBuilder m_manifestModuleBuilder; // Set to true if the manifest module was returned by code:DefineDynamicModule to the user private bool m_fManifestModuleUsedAsDefinedModule; internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule"; internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module) { Contract.Requires(module != null); Debug.Assert(this.InternalAssembly == module.Assembly); lock (SyncRoot) { // in CoreCLR there is only one module in each dynamic assembly, the manifest module if (m_manifestModuleBuilder.InternalModule == module) return m_manifestModuleBuilder; throw new ArgumentException(null, nameof(module)); } } internal object SyncRoot { get { return InternalAssembly.SyncRoot; } } internal InternalAssemblyBuilder InternalAssembly { get { return m_internalAssemblyBuilder; } } internal RuntimeAssembly GetNativeHandle() { return InternalAssembly.GetNativeHandle(); } #endregion #region Constructor internal AssemblyBuilder(AppDomain domain, AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence, ref StackCrawlMark stackMark, IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes, SecurityContextSource securityContextSource) { if (name == null) throw new ArgumentNullException(nameof(name)); if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.RunAndCollect ) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access)); } if (securityContextSource < SecurityContextSource.CurrentAppDomain || securityContextSource > SecurityContextSource.CurrentAssembly) { throw new ArgumentOutOfRangeException(nameof(securityContextSource)); } // Clone the name in case the caller modifies it underneath us. name = (AssemblyName)name.Clone(); // Scan the assembly level attributes for any attributes which modify how we create the // assembly. Currently, we look for any attribute which modifies the security transparency // of the assembly. List<CustomAttributeBuilder> assemblyAttributes = null; DynamicAssemblyFlags assemblyFlags = DynamicAssemblyFlags.None; byte[] securityRulesBlob = null; byte[] aptcaBlob = null; if (unsafeAssemblyAttributes != null) { // Create a copy to ensure that it cannot be modified from another thread // as it is used further below. assemblyAttributes = new List<CustomAttributeBuilder>(unsafeAssemblyAttributes); #pragma warning disable 618 // We deal with legacy attributes here as well for compat foreach (CustomAttributeBuilder attribute in assemblyAttributes) { if (attribute.m_con.DeclaringType == typeof(SecurityTransparentAttribute)) { assemblyFlags |= DynamicAssemblyFlags.Transparent; } else if (attribute.m_con.DeclaringType == typeof(SecurityCriticalAttribute)) { { assemblyFlags |= DynamicAssemblyFlags.AllCritical; } } } #pragma warning restore 618 } m_internalAssemblyBuilder = (InternalAssemblyBuilder)nCreateDynamicAssembly(domain, name, evidence, ref stackMark, securityRulesBlob, aptcaBlob, access, assemblyFlags, securityContextSource); m_assemblyData = new AssemblyBuilderData(m_internalAssemblyBuilder, name.Name, access, dir); // Make sure that ManifestModule is properly initialized // We need to do this before setting any CustomAttribute InitManifestModule(); if (assemblyAttributes != null) { foreach (CustomAttributeBuilder assemblyAttribute in assemblyAttributes) SetCustomAttribute(assemblyAttribute); } } private void InitManifestModule() { InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule(); // Note that this ModuleBuilder cannot be used for RefEmit yet // because it hasn't been initialized. // However, it can be used to set the custom attribute on the Assembly m_manifestModuleBuilder = new ModuleBuilder(this, modBuilder); // We are only setting the name in the managed ModuleBuilderData here. // The name in the underlying metadata will be set when the // manifest module is created during nCreateDynamicAssembly. // This name needs to stay in sync with that used in // Assembly::Init to call ReflectionModule::Create (in VM) m_manifestModuleBuilder.Init(AssemblyBuilder.MANIFEST_MODULE_NAME, null, 0); m_fManifestModuleUsedAsDefinedModule = false; } #endregion #region DefineDynamicAssembly /********************************************** * If an AssemblyName has a public key specified, the assembly is assumed * to have a strong name and a hash will be computed when the assembly * is saved. **********************************************/ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static AssemblyBuilder DefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access) { Contract.Ensures(Contract.Result<AssemblyBuilder>() != null); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalDefineDynamicAssembly(name, access, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static AssemblyBuilder DefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) { Contract.Ensures(Contract.Result<AssemblyBuilder>() != null); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalDefineDynamicAssembly(name, access, null, null, ref stackMark, assemblyAttributes, SecurityContextSource.CurrentAssembly); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Assembly nCreateDynamicAssembly(AppDomain domain, AssemblyName name, Evidence identity, ref StackCrawlMark stackMark, byte[] securityRulesBlob, byte[] aptcaBlob, AssemblyBuilderAccess access, DynamicAssemblyFlags flags, SecurityContextSource securityContextSource); private class AssemblyBuilderLock { } internal static AssemblyBuilder InternalDefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence, ref StackCrawlMark stackMark, IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes, SecurityContextSource securityContextSource) { lock (typeof(AssemblyBuilderLock)) { // we can only create dynamic assemblies in the current domain return new AssemblyBuilder(AppDomain.CurrentDomain, name, access, dir, evidence, ref stackMark, unsafeAssemblyAttributes, securityContextSource); } //lock(typeof(AssemblyBuilderLock)) } #endregion #region DefineDynamicModule /********************************************** * * Defines a named dynamic module. It is an error to define multiple * modules within an Assembly with the same name. This dynamic module is * a transient module. * **********************************************/ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public ModuleBuilder DefineDynamicModule( String name) { Contract.Ensures(Contract.Result<ModuleBuilder>() != null); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return DefineDynamicModuleInternal(name, false, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public ModuleBuilder DefineDynamicModule( String name, bool emitSymbolInfo) // specify if emit symbol info or not { Contract.Ensures(Contract.Result<ModuleBuilder>() != null); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return DefineDynamicModuleInternal(name, emitSymbolInfo, ref stackMark); } private ModuleBuilder DefineDynamicModuleInternal( String name, bool emitSymbolInfo, // specify if emit symbol info or not ref StackCrawlMark stackMark) { lock (SyncRoot) { return DefineDynamicModuleInternalNoLock(name, emitSymbolInfo, ref stackMark); } } private ModuleBuilder DefineDynamicModuleInternalNoLock( String name, bool emitSymbolInfo, // specify if emit symbol info or not ref StackCrawlMark stackMark) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); if (name[0] == '\0') throw new ArgumentException(SR.Argument_InvalidName, nameof(name)); Contract.Ensures(Contract.Result<ModuleBuilder>() != null); Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )"); Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal"); ModuleBuilder dynModule; ISymbolWriter writer = null; IntPtr pInternalSymWriter = new IntPtr(); // create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created if (m_fManifestModuleUsedAsDefinedModule == true) throw new InvalidOperationException(SR.InvalidOperation_NoMultiModuleAssembly); // Init(...) has already been called on m_manifestModuleBuilder in InitManifestModule() dynModule = m_manifestModuleBuilder; // Create the symbol writer if (emitSymbolInfo) { writer = SymWrapperCore.SymWriter.CreateSymWriter(); String fileName = "Unused"; // this symfile is never written to disk so filename does not matter. // Pass the "real" module to the VM pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, fileName); // In Telesto, we took the SetUnderlyingWriter method private as it's a very rickety method. // This might someday be a good move for the desktop CLR too. ((SymWrapperCore.SymWriter)writer).InternalSetUnderlyingWriter(pInternalSymWriter); } // Creating the symbol writer dynModule.SetSymWriter(writer); m_assemblyData.AddModule(dynModule); if (dynModule == m_manifestModuleBuilder) { // We are reusing manifest module as user-defined dynamic module m_fManifestModuleUsedAsDefinedModule = true; } return dynModule; } // DefineDynamicModuleInternalNoLock #endregion internal void CheckContext(params Type[][] typess) { if (typess == null) return; foreach (Type[] types in typess) if (types != null) CheckContext(types); } internal void CheckContext(params Type[] types) { if (types == null) return; foreach (Type type in types) { if (type == null) continue; if (type.Module == null || type.Module.Assembly == null) throw new ArgumentException(SR.Argument_TypeNotValid); if (type.Module.Assembly == typeof(object).Module.Assembly) continue; if (type.Module.Assembly.ReflectionOnly && !ReflectionOnly) throw new InvalidOperationException(SR.Format(SR.Arugment_EmitMixedContext1, type.AssemblyQualifiedName)); if (!type.Module.Assembly.ReflectionOnly && ReflectionOnly) throw new InvalidOperationException(SR.Format(SR.Arugment_EmitMixedContext2, type.AssemblyQualifiedName)); } } #region object overrides public override bool Equals(object obj) { return InternalAssembly.Equals(obj); } // Need a dummy GetHashCode to pair with Equals public override int GetHashCode() { return InternalAssembly.GetHashCode(); } #endregion #region ICustomAttributeProvider Members public override Object[] GetCustomAttributes(bool inherit) { return InternalAssembly.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return InternalAssembly.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return InternalAssembly.IsDefined(attributeType, inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return InternalAssembly.GetCustomAttributesData(); } #endregion #region Assembly overrides // Returns the names of all the resources public override String[] GetManifestResourceNames() { return InternalAssembly.GetManifestResourceNames(); } public override FileStream GetFile(String name) { return InternalAssembly.GetFile(name); } public override FileStream[] GetFiles(bool getResourceModules) { return InternalAssembly.GetFiles(getResourceModules); } public override Stream GetManifestResourceStream(Type type, String name) { return InternalAssembly.GetManifestResourceStream(type, name); } public override Stream GetManifestResourceStream(String name) { return InternalAssembly.GetManifestResourceStream(name); } public override ManifestResourceInfo GetManifestResourceInfo(String resourceName) { return InternalAssembly.GetManifestResourceInfo(resourceName); } public override String Location { get { return InternalAssembly.Location; } } public override String ImageRuntimeVersion { get { return InternalAssembly.ImageRuntimeVersion; } } public override String CodeBase { get { return InternalAssembly.CodeBase; } } // Override the EntryPoint method on Assembly. // This doesn't need to be synchronized because it is simple enough public override MethodInfo EntryPoint { get { return m_assemblyData.m_entryPointMethod; } } // Get an array of all the public types defined in this assembly public override Type[] GetExportedTypes() { return InternalAssembly.GetExportedTypes(); } public override AssemblyName GetName(bool copiedName) { return InternalAssembly.GetName(copiedName); } public override String FullName { get { return InternalAssembly.FullName; } } public override Type GetType(String name, bool throwOnError, bool ignoreCase) { return InternalAssembly.GetType(name, throwOnError, ignoreCase); } public override Module ManifestModule { get { return m_manifestModuleBuilder.InternalModule; } } public override bool ReflectionOnly { get { return InternalAssembly.ReflectionOnly; } } public override Module GetModule(String name) { return InternalAssembly.GetModule(name); } public override AssemblyName[] GetReferencedAssemblies() { return InternalAssembly.GetReferencedAssemblies(); } public override bool GlobalAssemblyCache { get { return InternalAssembly.GlobalAssemblyCache; } } public override Int64 HostContext { get { return InternalAssembly.HostContext; } } public override Module[] GetModules(bool getResourceModules) { return InternalAssembly.GetModules(getResourceModules); } public override Module[] GetLoadedModules(bool getResourceModules) { return InternalAssembly.GetLoadedModules(getResourceModules); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Assembly GetSatelliteAssembly(CultureInfo culture) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalAssembly.InternalGetSatelliteAssembly(culture, null, ref stackMark); } // Useful for binding to a very specific version of a satellite assembly [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalAssembly.InternalGetSatelliteAssembly(culture, version, ref stackMark); } public override bool IsDynamic { get { return true; } } #endregion /********************************************** * * return a dynamic module with the specified name. * **********************************************/ public ModuleBuilder GetDynamicModule( String name) // the name of module for the look up { lock (SyncRoot) { return GetDynamicModuleNoLock(name); } } private ModuleBuilder GetDynamicModuleNoLock( String name) // the name of module for the look up { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.GetDynamicModule( " + name + " )"); int size = m_assemblyData.m_moduleBuilderList.Count; for (int i = 0; i < size; i++) { ModuleBuilder moduleBuilder = (ModuleBuilder)m_assemblyData.m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strModuleName.Equals(name)) { return moduleBuilder; } } return null; } /********************************************** * Use this function if client decides to form the custom attribute blob themselves **********************************************/ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); lock (SyncRoot) { SetCustomAttributeNoLock(con, binaryAttribute); } } private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute) { TypeBuilder.DefineCustomAttribute( m_manifestModuleBuilder, // pass in the in-memory assembly module AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token m_manifestModuleBuilder.GetConstructorToken(con).Token, binaryAttribute, false, typeof(System.Diagnostics.DebuggableAttribute) == con.DeclaringType); // Track the CA for persistence if (m_assemblyData.m_access != AssemblyBuilderAccess.Run) { // tracking the CAs for persistence m_assemblyData.AddCustomAttribute(con, binaryAttribute); } } /********************************************** * Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder **********************************************/ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException(nameof(customBuilder)); } Contract.EndContractBlock(); lock (SyncRoot) { SetCustomAttributeNoLock(customBuilder); } } private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder) { customBuilder.CreateCustomAttribute( m_manifestModuleBuilder, AssemblyBuilderData.m_tkAssembly); // This is the AssemblyDef token // Track the CA for persistence if (m_assemblyData.m_access != AssemblyBuilderAccess.Run) { m_assemblyData.AddCustomAttribute(customBuilder); } } /********************************************** * * Private methods * **********************************************/ /********************************************** * Make a private constructor so these cannot be constructed externally. * @internonly **********************************************/ private AssemblyBuilder() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplySubtractAddDouble() { var test = new AlternatingTernaryOpTest__MultiplySubtractAddDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class AlternatingTernaryOpTest__MultiplySubtractAddDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public Vector128<Double> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(AlternatingTernaryOpTest__MultiplySubtractAddDouble testClass) { var result = Fma.MultiplySubtractAdd(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(AlternatingTernaryOpTest__MultiplySubtractAddDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) fixed (Vector128<Double>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Double[] _data3 = new Double[Op3ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private static Vector128<Double> _clsVar3; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private Vector128<Double> _fld3; private DataTable _dataTable; static AlternatingTernaryOpTest__MultiplySubtractAddDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public AlternatingTernaryOpTest__MultiplySubtractAddDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplySubtractAdd( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplySubtractAdd( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplySubtractAdd( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplySubtractAdd( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) fixed (Vector128<Double>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplySubtractAdd( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)), Sse2.LoadVector128((Double*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new AlternatingTernaryOpTest__MultiplySubtractAddDouble(); var result = Fma.MultiplySubtractAdd(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new AlternatingTernaryOpTest__MultiplySubtractAddDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) fixed (Vector128<Double>* pFld3 = &test._fld3) { var result = Fma.MultiplySubtractAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplySubtractAdd(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) fixed (Vector128<Double>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractAdd(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractAdd( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)), Sse2.LoadVector128((Double*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i += 2) { if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i] * secondOp[i]) + thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9))) { succeeded = false; break; } if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i + 1] * secondOp[i + 1]) - thirdOp[i + 1], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i + 1], 9))) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractAdd)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Text; using System.Xml; using Reporting.Rdl; namespace Reporting.RdlDesign { /// <summary> /// Summary description for DialogDataSourceRef. /// </summary> internal class DialogNewChart : System.Windows.Forms.Form { private DesignXmlDraw _Draw; private System.Windows.Forms.Button bOK; private System.Windows.Forms.Button bCancel; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox cbDataSets; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ListBox lbFields; private System.Windows.Forms.ListBox lbChartCategories; private System.Windows.Forms.Button bCategoryUp; private System.Windows.Forms.Button bCategoryDown; private System.Windows.Forms.Button bCategory; private System.Windows.Forms.Button bSeries; private System.Windows.Forms.ListBox lbChartSeries; private System.Windows.Forms.Button bCategoryDelete; private System.Windows.Forms.Button bSeriesDelete; private System.Windows.Forms.Button bSeriesDown; private System.Windows.Forms.Button bSeriesUp; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label lChartData; private System.Windows.Forms.ComboBox cbChartData; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox cbSubType; private System.Windows.Forms.ComboBox cbChartType; private System.Windows.Forms.Label label7; private ComboBox cbChartData2; private Label lChartData2; private ComboBox cbChartData3; private Label lChartData3; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal DialogNewChart(DesignXmlDraw dxDraw, XmlNode container) { _Draw = dxDraw; // // Required for Windows Form Designer support // InitializeComponent(); InitValues(container); } private void InitValues(XmlNode container) { this.bOK.Enabled = false; // // Obtain the existing DataSets info // object[] datasets = _Draw.DataSetNames; if (datasets == null) return; // not much to do if no DataSets if (_Draw.IsDataRegion(container)) { string s = _Draw.GetDataSetNameValue(container); if (s == null) return; this.cbDataSets.Items.Add(s); this.cbDataSets.Enabled = false; } else this.cbDataSets.Items.AddRange(datasets); cbDataSets.SelectedIndex = 0; this.cbChartType.SelectedIndex = 2; } internal string ChartXml { get { StringBuilder chart = new StringBuilder("<Chart><Height>2in</Height><Width>4in</Width>"); chart.AppendFormat("<DataSetName>{0}</DataSetName>", this.cbDataSets.Text); chart.Append("<NoRows>Query returned no rows!</NoRows><Style>"+ "<BorderStyle><Default>Solid</Default></BorderStyle>"+ "<BackgroundColor>White</BackgroundColor>"+ "<BackgroundGradientType>LeftRight</BackgroundGradientType>"+ "<BackgroundGradientEndColor>Azure</BackgroundGradientEndColor>"+ "</Style>"); chart.AppendFormat("<Type>{0}</Type><Subtype>{1}</Subtype>", this.cbChartType.Text, this.cbSubType.Text); // do the categories string tcat=""; if (this.lbChartCategories.Items.Count > 0) { chart.Append("<CategoryGroupings>"); foreach (string cname in this.lbChartCategories.Items) { if (tcat == "") tcat = cname; chart.Append("<CategoryGrouping>"); chart.Append("<DynamicCategories>"); chart.AppendFormat("<Grouping><GroupExpressions>"+ "<GroupExpression>=Fields!{0}.Value</GroupExpression>"+ "</GroupExpressions></Grouping>", cname); chart.Append("</DynamicCategories>"); chart.Append("</CategoryGrouping>"); } chart.Append("</CategoryGroupings>"); // Do the category axis chart.AppendFormat("<CategoryAxis><Axis><Visible>true</Visible>"+ "<MajorTickMarks>Inside</MajorTickMarks>"+ "<MajorGridLines><ShowGridLines>true</ShowGridLines>"+ "<Style><BorderStyle><Default>Solid</Default></BorderStyle>"+ "</Style></MajorGridLines>" + "<MinorGridLines><ShowGridLines>true</ShowGridLines>"+ "<Style><BorderStyle><Default>Solid</Default></BorderStyle>"+ "</Style></MinorGridLines>"+ "<Title><Caption>{0}</Caption>"+ "</Title></Axis></CategoryAxis>",tcat); } // do the series string tser=""; if (this.lbChartSeries.Items.Count > 0) { chart.Append("<SeriesGroupings>"); //If we have chartData Set then we want dynamic series GJL if (this.cbChartData.Text.Length > 0) { foreach (string sname in this.lbChartSeries.Items) { if (tser == "") tser = sname; chart.Append("<SeriesGrouping>"); chart.Append("<DynamicSeries>"); chart.AppendFormat("<Grouping><GroupExpressions>" + "<GroupExpression>=Fields!{0}.Value</GroupExpression>" + "</GroupExpressions></Grouping>", sname); chart.AppendFormat("<Label>=Fields!{0}.Value</Label>", sname); chart.Append("</DynamicSeries>"); chart.Append("</SeriesGrouping>"); } } //If we don't have chart data set we want static series GJL else { chart.Append("<SeriesGrouping>"); chart.Append("<StaticSeries>"); foreach (string sname in this.lbChartSeries.Items) { chart.Append("<StaticMember>"); chart.AppendFormat("<Label>{0}</Label>", sname); chart.AppendFormat("<Value>=Fields!{0}.Value</Value>",sname); chart.Append("</StaticMember>"); } chart.Append("</StaticSeries>"); chart.Append("</SeriesGrouping>"); } chart.Append("</SeriesGroupings>"); } // Chart Data string vtitle; if (this.cbChartData.Text.Length > 0) { chart.Append("<ChartData><ChartSeries><DataPoints><DataPoint>" + "<DataValues>"); chart.AppendFormat("<DataValue><Value>{0}</Value></DataValue>", this.cbChartData.Text); string ctype = this.cbChartType.Text.ToLowerInvariant(); if (ctype == "scatter" || ctype == "bubble") { chart.AppendFormat("<DataValue><Value>{0}</Value></DataValue>", this.cbChartData2.Text); if (ctype == "bubble") { chart.AppendFormat("<DataValue><Value>{0}</Value></DataValue>", this.cbChartData3.Text); } } chart.Append("</DataValues>" + "</DataPoint></DataPoints></ChartSeries></ChartData>"); // Do the value axis int start = this.cbChartData.Text.LastIndexOf("!"); if (start > 0) { int end = this.cbChartData.Text.LastIndexOf(".Value"); if (end < 0 || end <= start+1) vtitle = this.cbChartData.Text.Substring(start+1); else vtitle = this.cbChartData.Text.Substring(start+1, end-start-1); } else vtitle = "Values"; } else { //If we don't have chartData then use the items in the series box //to create Static Series chart.Append("<ChartData>"); foreach (string sname in this.lbChartSeries.Items) { chart.Append("<ChartSeries>"); chart.Append("<DataPoints>"); chart.Append("<DataPoint>"); chart.Append("<DataValues>"); if (cbChartType.SelectedItem.Equals("Scatter")) { //we need a y datavalue as well... string xname = (string)lbChartCategories.Items[0]; chart.Append("<DataValue>"); chart.AppendFormat("<Value>=Fields!{0}.Value</Value>", xname); chart.Append("</DataValue>"); chart.Append("<DataValue>"); chart.AppendFormat("<Value>=Fields!{0}.Value</Value>", sname); chart.Append("</DataValue>"); } else { chart.Append("<DataValue>"); chart.AppendFormat("<Value>=Fields!{0}.Value</Value>", sname); chart.Append("</DataValue>"); } chart.Append("</DataValues>"); chart.Append("</DataPoint>"); chart.Append("</DataPoints>"); chart.Append("</ChartSeries>"); } chart.Append("</ChartData>"); vtitle = "Values"; } chart.AppendFormat("<ValueAxis><Axis><Visible>true</Visible>" + "<MajorTickMarks>Inside</MajorTickMarks>" + "<MajorGridLines><ShowGridLines>true</ShowGridLines>" + "<Style><BorderStyle><Default>Solid</Default></BorderStyle>" + "<FontSize>8pt</FontSize>" + "</Style></MajorGridLines>" + "<MinorGridLines><ShowGridLines>true</ShowGridLines>" + "<Style><BorderStyle><Default>Solid</Default></BorderStyle>" + "</Style></MinorGridLines>" + "<Title><Caption>{0}</Caption>" + "<Style><WritingMode>tb-rl</WritingMode></Style>" + "</Title></Axis></ValueAxis>", vtitle); // Legend chart.Append("<Legend><Style><BorderStyle><Default>Solid</Default>"+ "</BorderStyle><PaddingLeft>5pt</PaddingLeft>"+ "<FontSize>8pt</FontSize></Style><Visible>true</Visible>"+ "<Position>RightCenter</Position></Legend>"); // Title chart.AppendFormat("<Title><Style><FontWeight>Bold</FontWeight>"+ "<FontSize>14pt</FontSize><TextAlign>Center</TextAlign>"+ "</Style><Caption>{0} {1} Chart</Caption></Title>", tcat, tser); // end of Chart defintion chart.Append("</Chart>"); return chart.ToString(); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.bOK = new System.Windows.Forms.Button(); this.bCancel = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.cbDataSets = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.lbFields = new System.Windows.Forms.ListBox(); this.lbChartCategories = new System.Windows.Forms.ListBox(); this.bCategoryUp = new System.Windows.Forms.Button(); this.bCategoryDown = new System.Windows.Forms.Button(); this.bCategory = new System.Windows.Forms.Button(); this.bSeries = new System.Windows.Forms.Button(); this.lbChartSeries = new System.Windows.Forms.ListBox(); this.bCategoryDelete = new System.Windows.Forms.Button(); this.bSeriesDelete = new System.Windows.Forms.Button(); this.bSeriesDown = new System.Windows.Forms.Button(); this.bSeriesUp = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.lChartData = new System.Windows.Forms.Label(); this.cbChartData = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.cbSubType = new System.Windows.Forms.ComboBox(); this.cbChartType = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.cbChartData2 = new System.Windows.Forms.ComboBox(); this.lChartData2 = new System.Windows.Forms.Label(); this.cbChartData3 = new System.Windows.Forms.ComboBox(); this.lChartData3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // bOK // this.bOK.Location = new System.Drawing.Point(326, 452); this.bOK.Name = "bOK"; this.bOK.Size = new System.Drawing.Size(90, 27); this.bOK.TabIndex = 16; this.bOK.Text = "OK"; this.bOK.Click += new System.EventHandler(this.bOK_Click); // // bCancel // this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.Location = new System.Drawing.Point(442, 452); this.bCancel.Name = "bCancel"; this.bCancel.Size = new System.Drawing.Size(90, 27); this.bCancel.TabIndex = 17; this.bCancel.Text = "Cancel"; // // label1 // this.label1.Location = new System.Drawing.Point(19, 18); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(58, 27); this.label1.TabIndex = 11; this.label1.Text = "DataSet"; // // cbDataSets // this.cbDataSets.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataSets.Location = new System.Drawing.Point(96, 18); this.cbDataSets.Name = "cbDataSets"; this.cbDataSets.Size = new System.Drawing.Size(432, 24); this.cbDataSets.TabIndex = 0; this.cbDataSets.SelectedIndexChanged += new System.EventHandler(this.cbDataSets_SelectedIndexChanged); // // label2 // this.label2.Location = new System.Drawing.Point(19, 92); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(120, 27); this.label2.TabIndex = 13; this.label2.Text = "DataSet Fields"; // // label3 // this.label3.Location = new System.Drawing.Point(269, 94); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(221, 27); this.label3.TabIndex = 14; this.label3.Text = "Chart Categories (X) Groupings"; // // lbFields // this.lbFields.ItemHeight = 16; this.lbFields.Location = new System.Drawing.Point(19, 120); this.lbFields.Name = "lbFields"; this.lbFields.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; this.lbFields.Size = new System.Drawing.Size(183, 196); this.lbFields.TabIndex = 3; // // lbChartCategories // this.lbChartCategories.ItemHeight = 16; this.lbChartCategories.Location = new System.Drawing.Point(278, 120); this.lbChartCategories.Name = "lbChartCategories"; this.lbChartCategories.Size = new System.Drawing.Size(183, 84); this.lbChartCategories.TabIndex = 4; // // bCategoryUp // this.bCategoryUp.Location = new System.Drawing.Point(478, 109); this.bCategoryUp.Name = "bCategoryUp"; this.bCategoryUp.Size = new System.Drawing.Size(58, 28); this.bCategoryUp.TabIndex = 5; this.bCategoryUp.Text = "Up"; this.bCategoryUp.Click += new System.EventHandler(this.bCategoryUp_Click); // // bCategoryDown // this.bCategoryDown.Location = new System.Drawing.Point(478, 143); this.bCategoryDown.Name = "bCategoryDown"; this.bCategoryDown.Size = new System.Drawing.Size(58, 28); this.bCategoryDown.TabIndex = 6; this.bCategoryDown.Text = "Down"; this.bCategoryDown.Click += new System.EventHandler(this.bCategoryDown_Click); // // bCategory // this.bCategory.Location = new System.Drawing.Point(221, 129); this.bCategory.Name = "bCategory"; this.bCategory.Size = new System.Drawing.Size(38, 28); this.bCategory.TabIndex = 2; this.bCategory.Text = ">"; this.bCategory.Click += new System.EventHandler(this.bCategory_Click); // // bSeries // this.bSeries.Location = new System.Drawing.Point(222, 230); this.bSeries.Name = "bSeries"; this.bSeries.Size = new System.Drawing.Size(38, 28); this.bSeries.TabIndex = 8; this.bSeries.Text = ">"; this.bSeries.Click += new System.EventHandler(this.bSeries_Click); // // lbChartSeries // this.lbChartSeries.ItemHeight = 16; this.lbChartSeries.Location = new System.Drawing.Point(278, 232); this.lbChartSeries.Name = "lbChartSeries"; this.lbChartSeries.Size = new System.Drawing.Size(183, 84); this.lbChartSeries.TabIndex = 9; // // bCategoryDelete // this.bCategoryDelete.Location = new System.Drawing.Point(478, 176); this.bCategoryDelete.Name = "bCategoryDelete"; this.bCategoryDelete.Size = new System.Drawing.Size(58, 28); this.bCategoryDelete.TabIndex = 7; this.bCategoryDelete.Text = "Delete"; this.bCategoryDelete.Click += new System.EventHandler(this.bCategoryDelete_Click); // // bSeriesDelete // this.bSeriesDelete.Location = new System.Drawing.Point(478, 298); this.bSeriesDelete.Name = "bSeriesDelete"; this.bSeriesDelete.Size = new System.Drawing.Size(58, 27); this.bSeriesDelete.TabIndex = 12; this.bSeriesDelete.Text = "Delete"; this.bSeriesDelete.Click += new System.EventHandler(this.bSeriesDelete_Click); // // bSeriesDown // this.bSeriesDown.Location = new System.Drawing.Point(478, 264); this.bSeriesDown.Name = "bSeriesDown"; this.bSeriesDown.Size = new System.Drawing.Size(58, 28); this.bSeriesDown.TabIndex = 11; this.bSeriesDown.Text = "Down"; this.bSeriesDown.Click += new System.EventHandler(this.bSeriesDown_Click); // // bSeriesUp // this.bSeriesUp.Location = new System.Drawing.Point(478, 230); this.bSeriesUp.Name = "bSeriesUp"; this.bSeriesUp.Size = new System.Drawing.Size(58, 28); this.bSeriesUp.TabIndex = 10; this.bSeriesUp.Text = "Up"; this.bSeriesUp.Click += new System.EventHandler(this.bSeriesUp_Click); // // label4 // this.label4.Location = new System.Drawing.Point(269, 204); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(194, 16); this.label4.TabIndex = 31; this.label4.Text = "Chart Series"; // // lChartData // this.lChartData.Location = new System.Drawing.Point(19, 363); this.lChartData.Name = "lChartData"; this.lChartData.Size = new System.Drawing.Size(135, 27); this.lChartData.TabIndex = 32; this.lChartData.Text = "Data Expression"; // // cbChartData // this.cbChartData.Location = new System.Drawing.Point(164, 360); this.cbChartData.Name = "cbChartData"; this.cbChartData.Size = new System.Drawing.Size(297, 24); this.cbChartData.TabIndex = 13; this.cbChartData.Enter += new System.EventHandler(this.cbChartData_Enter); this.cbChartData.TextChanged += new System.EventHandler(this.cbChartData_TextChanged); // // label6 // this.label6.Location = new System.Drawing.Point(278, 55); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(77, 27); this.label6.TabIndex = 36; this.label6.Text = "Sub-type"; // // cbSubType // this.cbSubType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbSubType.Location = new System.Drawing.Point(374, 55); this.cbSubType.Name = "cbSubType"; this.cbSubType.Size = new System.Drawing.Size(96, 24); this.cbSubType.TabIndex = 2; // // cbChartType // this.cbChartType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbChartType.Items.AddRange(new object[] { "Area", "Bar", "Column", "Doughnut", "Line", "Pie", "Bubble", "Scatter"}); this.cbChartType.Location = new System.Drawing.Point(115, 55); this.cbChartType.Name = "cbChartType"; this.cbChartType.Size = new System.Drawing.Size(145, 24); this.cbChartType.TabIndex = 1; this.cbChartType.SelectedIndexChanged += new System.EventHandler(this.cbChartType_SelectedIndexChanged); // // label7 // this.label7.Location = new System.Drawing.Point(19, 55); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(87, 19); this.label7.TabIndex = 33; this.label7.Text = "Chart Type"; // // cbChartData2 // this.cbChartData2.Location = new System.Drawing.Point(164, 391); this.cbChartData2.Name = "cbChartData2"; this.cbChartData2.Size = new System.Drawing.Size(297, 24); this.cbChartData2.TabIndex = 14; this.cbChartData2.Enter += new System.EventHandler(this.cbChartData_Enter); this.cbChartData2.TextChanged += new System.EventHandler(this.cbChartData_TextChanged); // // lChartData2 // this.lChartData2.Location = new System.Drawing.Point(22, 395); this.lChartData2.Name = "lChartData2"; this.lChartData2.Size = new System.Drawing.Size(134, 26); this.lChartData2.TabIndex = 38; this.lChartData2.Text = "Y Coordinate"; // // cbChartData3 // this.cbChartData3.Location = new System.Drawing.Point(164, 422); this.cbChartData3.Name = "cbChartData3"; this.cbChartData3.Size = new System.Drawing.Size(297, 24); this.cbChartData3.TabIndex = 15; this.cbChartData3.Enter += new System.EventHandler(this.cbChartData_Enter); this.cbChartData3.TextChanged += new System.EventHandler(this.cbChartData_TextChanged); // // lChartData3 // this.lChartData3.Location = new System.Drawing.Point(22, 426); this.lChartData3.Name = "lChartData3"; this.lChartData3.Size = new System.Drawing.Size(134, 26); this.lChartData3.TabIndex = 40; this.lChartData3.Text = "Bubble Size"; // // DialogNewChart // this.AcceptButton = this.bOK; this.AutoScaleBaseSize = new System.Drawing.Size(6, 15); this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(544, 486); this.Controls.Add(this.cbChartData3); this.Controls.Add(this.lChartData3); this.Controls.Add(this.cbChartData2); this.Controls.Add(this.lChartData2); this.Controls.Add(this.label6); this.Controls.Add(this.cbSubType); this.Controls.Add(this.cbChartType); this.Controls.Add(this.label7); this.Controls.Add(this.cbChartData); this.Controls.Add(this.lChartData); this.Controls.Add(this.label4); this.Controls.Add(this.bSeriesDelete); this.Controls.Add(this.bSeriesDown); this.Controls.Add(this.bSeriesUp); this.Controls.Add(this.bCategoryDelete); this.Controls.Add(this.lbChartSeries); this.Controls.Add(this.bSeries); this.Controls.Add(this.bCategory); this.Controls.Add(this.bCategoryDown); this.Controls.Add(this.bCategoryUp); this.Controls.Add(this.lbChartCategories); this.Controls.Add(this.lbFields); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.cbDataSets); this.Controls.Add(this.label1); this.Controls.Add(this.bCancel); this.Controls.Add(this.bOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogNewChart"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "New Chart"; this.ResumeLayout(false); } #endregion private void bOK_Click(object sender, System.EventArgs e) { bool bFail = false; string ctype = cbChartType.Text.ToLowerInvariant(); if (cbChartData.Text.Length == 0 && lbChartSeries.Items.Count == 0) //Added second condition 05122007GJL { MessageBox.Show("Please fill out the chart data expression, or include a series."); bFail = true; } else if (ctype == "scatter" && cbChartData2.Text.Length == 0 && lbChartSeries.Items.Count == 0) { MessageBox.Show("Please fill out the chart Y coordinate data expression."); bFail = true; } else if (ctype == "bubble" && (cbChartData2.Text.Length == 0 || cbChartData3.Text.Length == 0)) { MessageBox.Show("Please fill out the chart Y coordinate and Bubble width expressions."); bFail = true; } if (bFail) return; // apply the result DialogResult = DialogResult.OK; } private void cbDataSets_SelectedIndexChanged(object sender, System.EventArgs e) { this.lbChartCategories.Items.Clear(); this.lbChartSeries.Items.Clear(); bOK.Enabled = false; this.lbFields.Items.Clear(); string [] fields = _Draw.GetFields(cbDataSets.Text, false); if (fields != null) lbFields.Items.AddRange(fields); } private void bCategory_Click(object sender, System.EventArgs e) { ICollection sic = lbFields.SelectedIndices; int count=sic.Count; foreach (int i in sic) { string fname = (string) lbFields.Items[i]; if (this.lbChartCategories.Items.IndexOf(fname) < 0) lbChartCategories.Items.Add(fname); } OkEnable(); } private void bSeries_Click(object sender, System.EventArgs e) { ICollection sic = lbFields.SelectedIndices; int count=sic.Count; foreach (int i in sic) { string fname = (string) lbFields.Items[i]; if (this.lbChartSeries.Items.IndexOf(fname) < 0 || cbChartType.SelectedItem.Equals("Scatter")) lbChartSeries.Items.Add(fname); } OkEnable(); } private void bCategoryUp_Click(object sender, System.EventArgs e) { int index = lbChartCategories.SelectedIndex; if (index <= 0) return; string prename = (string) lbChartCategories.Items[index-1]; lbChartCategories.Items.RemoveAt(index-1); lbChartCategories.Items.Insert(index, prename); } private void bCategoryDown_Click(object sender, System.EventArgs e) { int index = lbChartCategories.SelectedIndex; if (index < 0 || index + 1 == lbChartCategories.Items.Count) return; string postname = (string) lbChartCategories.Items[index+1]; lbChartCategories.Items.RemoveAt(index+1); lbChartCategories.Items.Insert(index, postname); } private void bCategoryDelete_Click(object sender, System.EventArgs e) { int index = lbChartCategories.SelectedIndex; if (index < 0) return; lbChartCategories.Items.RemoveAt(index); OkEnable(); } private void bSeriesUp_Click(object sender, System.EventArgs e) { int index = lbChartSeries.SelectedIndex; if (index <= 0) return; string prename = (string) lbChartSeries.Items[index-1]; lbChartSeries.Items.RemoveAt(index-1); lbChartSeries.Items.Insert(index, prename); } private void bSeriesDown_Click(object sender, System.EventArgs e) { int index = lbChartSeries.SelectedIndex; if (index < 0 || index + 1 == lbChartSeries.Items.Count) return; string postname = (string) lbChartSeries.Items[index+1]; lbChartSeries.Items.RemoveAt(index+1); lbChartSeries.Items.Insert(index, postname); } private void bSeriesDelete_Click(object sender, System.EventArgs e) { int index = lbChartSeries.SelectedIndex; if (index < 0) return; lbChartSeries.Items.RemoveAt(index); OkEnable(); } private void OkEnable() { // We need values in datasets and Categories or Series for OK to work correctly bool bEnable = (this.lbChartCategories.Items.Count > 0 || this.lbChartSeries.Items.Count > 0) && this.cbDataSets.Text != null && this.cbDataSets.Text.Length > 0; // && this.cbChartData.Text.Length > 0; Not needed with static series 05122007GJL string ctype = cbChartType.Text.ToLowerInvariant(); if (ctype == "scatter") bEnable = bEnable && (this.cbChartData2.Text.Length > 0 || lbChartSeries.Items.Count > 0); else if (ctype == "bubble") bEnable = bEnable && (this.cbChartData2.Text.Length > 0 && this.cbChartData3.Text.Length > 0); bOK.Enabled = bEnable; } private void cbChartData_Enter(object sender, System.EventArgs e) { ComboBox cb = sender as ComboBox; if (cb == null) return; cb.Items.Clear(); foreach (string field in this.lbFields.Items) { if (this.lbChartCategories.Items.IndexOf(field) >= 0 || this.lbChartSeries.Items.IndexOf(field) >= 0) continue; // Field selected in columns and rows cb.Items.Add(string.Format("=Sum(Fields!{0}.Value)", field)); } } private void cbChartData_TextChanged(object sender, System.EventArgs e) { OkEnable(); } private void cbChartType_SelectedIndexChanged(object sender, System.EventArgs e) { // Change the potential sub-types string savesub = cbSubType.Text; string[] subItems; bool bEnableData2 = false; bool bEnableData3 = false; switch (cbChartType.Text) { case "Column": subItems = new string [] {"Plain", "Stacked", "PercentStacked"}; break; case "Bar": subItems = new string [] {"Plain", "Stacked", "PercentStacked"}; break; case "Line": subItems = new string [] {"Plain", "Smooth"}; break; case "Pie": subItems = new string [] {"Plain", "Exploded"}; break; case "Area": subItems = new string [] {"Plain", "Stacked"}; break; case "Doughnut": subItems = new string [] {"Plain"}; break; case "Scatter": subItems = new string [] {"Plain", "Line", "SmoothLine"}; bEnableData2 = true; break; case "Bubble": subItems = new string[] { "Plain" }; bEnableData2 = bEnableData3 = true; break; case "Stock": default: subItems = new string [] {"Plain"}; break; } lChartData2.Enabled = cbChartData2.Enabled = bEnableData2; lChartData3.Enabled = cbChartData3.Enabled = bEnableData3; // handle the subtype cbSubType.Items.Clear(); cbSubType.Items.AddRange(subItems); int i=0; foreach (string s in subItems) { if (s == savesub) { cbSubType.SelectedIndex = i; break; } i++; } // Didn't match old style if (i >= subItems.Length) i = 0; cbSubType.SelectedIndex = i; } } }
#nullable disable // ZlibBaseStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-October-28 15:45:15> // // ------------------------------------------------------------------ // // This module defines the ZlibBaseStream class, which is an intnernal // base class for DeflateStream, ZlibStream and GZipStream. // // ------------------------------------------------------------------ using System; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; using SharpCompress.Common.Tar.Headers; using System.Text; namespace SharpCompress.Compressors.Deflate { internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 } internal class ZlibBaseStream : Stream { protected internal ZlibCodec _z; // deferred init... new ZlibCodec(); protected internal StreamMode _streamMode = StreamMode.Undefined; protected internal FlushType _flushMode; protected internal ZlibStreamFlavor _flavor; protected internal CompressionMode _compressionMode; protected internal CompressionLevel _level; protected internal byte[] _workingBuffer; protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault; protected internal byte[] _buf1 = new byte[1]; protected internal Stream _stream; protected internal CompressionStrategy Strategy = CompressionStrategy.Default; // workitem 7159 private readonly CRC32 crc; protected internal string _GzipFileName; protected internal string _GzipComment; protected internal DateTime _GzipMtime; protected internal int _gzipHeaderByteCount; private readonly Encoding _encoding; internal int Crc32 => crc?.Crc32Result ?? 0; public ZlibBaseStream(Stream stream, CompressionMode compressionMode, CompressionLevel level, ZlibStreamFlavor flavor, Encoding encoding) { _flushMode = FlushType.None; //this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT]; _stream = stream; _compressionMode = compressionMode; _flavor = flavor; _level = level; _encoding = encoding; // workitem 7159 if (flavor == ZlibStreamFlavor.GZIP) { crc = new CRC32(); } } protected internal bool _wantCompress => (_compressionMode == CompressionMode.Compress); private ZlibCodec z { get { if (_z is null) { bool wantRfc1950Header = (_flavor == ZlibStreamFlavor.ZLIB); _z = new ZlibCodec(); if (_compressionMode == CompressionMode.Decompress) { _z.InitializeInflate(wantRfc1950Header); } else { _z.Strategy = Strategy; _z.InitializeDeflate(_level, wantRfc1950Header); } } return _z; } } private byte[] workingBuffer { get => _workingBuffer ??= new byte[_bufferSize]; } public override void Write(byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (crc != null) { crc.SlurpBlock(buffer, offset, count); } if (_streamMode == StreamMode.Undefined) { _streamMode = StreamMode.Writer; } else if (_streamMode != StreamMode.Writer) { throw new ZlibException("Cannot Write after Reading."); } if (count == 0) { return; } // first reference of z property will initialize the private var _z z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) { throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); } //if (_workingBuffer.Length - _z.AvailableBytesOut > 0) _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) { done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } } while (!done); } private void finish() { if (_z is null) { return; } if (_streamMode == StreamMode.Writer) { bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(FlushType.Finish) : _z.Inflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) { string verb = (_wantCompress ? "de" : "in") + "flating"; if (_z.Message is null) { throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc)); } throw new ZlibException(verb + ": " + _z.Message); } if (_workingBuffer.Length - _z.AvailableBytesOut > 0) { _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); } done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) { done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } } while (!done); Flush(); // workitem 7159 if (_flavor == ZlibStreamFlavor.GZIP) { if (_wantCompress) { // Emit the GZIP trailer: CRC32 and size mod 2^32 Span<byte> intBuf = stackalloc byte[4]; BinaryPrimitives.WriteInt32LittleEndian(intBuf, crc.Crc32Result); _stream.Write(intBuf); int c2 = (int)(crc.TotalBytesRead & 0x00000000FFFFFFFF); BinaryPrimitives.WriteInt32LittleEndian(intBuf, c2); _stream.Write(intBuf); } else { throw new ZlibException("Writing with decompression is not supported."); } } } // workitem 7159 else if (_streamMode == StreamMode.Reader) { if (_flavor == ZlibStreamFlavor.GZIP) { if (!_wantCompress) { // workitem 8501: handle edge case (decompress empty stream) if (_z.TotalBytesOut == 0L) { return; } // Read and potentially verify the GZIP trailer: CRC32 and size mod 2^32 Span<byte> trailer = stackalloc byte[8]; // workitem 8679 if (_z.AvailableBytesIn != 8) { // Make sure we have read to the end of the stream _z.InputBuffer.AsSpan(_z.NextIn, _z.AvailableBytesIn).CopyTo(trailer); int bytesNeeded = 8 - _z.AvailableBytesIn; int bytesRead = _stream.Read(trailer.Slice(_z.AvailableBytesIn, bytesNeeded)); if (bytesNeeded != bytesRead) { throw new ZlibException(String.Format( "Protocol error. AvailableBytesIn={0}, expected 8", _z.AvailableBytesIn + bytesRead)); } } else { _z.InputBuffer.AsSpan(_z.NextIn, trailer.Length).CopyTo(trailer); } Int32 crc32_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer); Int32 crc32_actual = crc.Crc32Result; Int32 isize_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer.Slice(4)); Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); if (crc32_actual != crc32_expected) { throw new ZlibException( String.Format("Bad CRC32 in GZIP stream. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected)); } if (isize_actual != isize_expected) { throw new ZlibException( String.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isize_actual, isize_expected)); } } else { throw new ZlibException("Reading with compression is not supported."); } } } } private void end() { if (z is null) { return; } if (_wantCompress) { _z.EndDeflate(); } else { _z.EndInflate(); } _z = null; } protected override void Dispose(bool disposing) { if (isDisposed) { return; } isDisposed = true; base.Dispose(disposing); if (disposing) { if (_stream is null) { return; } try { finish(); } finally { end(); _stream?.Dispose(); _stream = null; } } } public override void Flush() { _stream.Flush(); } public override Int64 Seek(Int64 offset, SeekOrigin origin) { throw new NotSupportedException(); //_outStream.Seek(offset, origin); } public override void SetLength(Int64 value) { _stream.SetLength(value); } #if NOT public int Read() { if (Read(_buf1, 0, 1) == 0) return 0; // calculate CRC after reading if (crc!=null) crc.SlurpBlock(_buf1,0,1); return (_buf1[0] & 0xFF); } #endif private bool nomoreinput; private bool isDisposed; private string ReadZeroTerminatedString() { var list = new List<byte>(); bool done = false; do { // workitem 7740 int n = _stream.Read(_buf1, 0, 1); if (n != 1) { throw new ZlibException("Unexpected EOF reading GZIP header."); } if (_buf1[0] == 0) { done = true; } else { list.Add(_buf1[0]); } } while (!done); byte[] buffer = list.ToArray(); return _encoding.GetString(buffer, 0, buffer.Length); } private int _ReadAndValidateGzipHeader() { int totalBytesRead = 0; // read the header on the first read Span<byte> header = stackalloc byte[10]; int n = _stream.Read(header); // workitem 8501: handle edge case (decompress empty stream) if (n == 0) { return 0; } if (n != 10) { throw new ZlibException("Not a valid GZIP stream."); } if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) { throw new ZlibException("Bad GZIP header."); } int timet = BinaryPrimitives.ReadInt32LittleEndian(header.Slice(4)); _GzipMtime = TarHeader.EPOCH.AddSeconds(timet); totalBytesRead += n; if ((header[3] & 0x04) == 0x04) { // read and discard extra field n = _stream.Read(header.Slice(0, 2)); // 2-byte length field totalBytesRead += n; short extraLength = (short)(header[0] + header[1] * 256); byte[] extra = new byte[extraLength]; n = _stream.Read(extra, 0, extra.Length); if (n != extraLength) { throw new ZlibException("Unexpected end-of-file reading GZIP header."); } totalBytesRead += n; } if ((header[3] & 0x08) == 0x08) { _GzipFileName = ReadZeroTerminatedString(); } if ((header[3] & 0x10) == 0x010) { _GzipComment = ReadZeroTerminatedString(); } if ((header[3] & 0x02) == 0x02) { Read(_buf1, 0, 1); // CRC16, ignore } return totalBytesRead; } public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (_streamMode == StreamMode.Undefined) { if (!_stream.CanRead) { throw new ZlibException("The stream is not readable."); } // for the first read, set up some controls. _streamMode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) { return 0; } } } if (_streamMode != StreamMode.Reader) { throw new ZlibException("Cannot Read after Writing."); } int rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; if (count == 0) { return 0; } if (nomoreinput && _wantCompress) { // no more input data available; therefore we flush to // try to complete the read rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) { throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); } rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) { crc.SlurpBlock(buffer, offset, rc); } return rc; } if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (offset < buffer.GetLowerBound(0)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if ((offset + count) > buffer.GetLength(0)) { throw new ArgumentOutOfRangeException(nameof(count)); } // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) _z.InputBuffer = workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) { nomoreinput = true; } } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) { return 0; } if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) { throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); } if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) { break; // nothing more to read } } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); // workitem 8557 // is there more room in output? if (_z.AvailableBytesOut > 0) { if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) { // deferred } // are we completely done reading? if (nomoreinput) { // and in compression? if (_wantCompress) { // no more input data available; therefore we flush to // try to complete the read rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) { throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); } } } } rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) { crc.SlurpBlock(buffer, offset, rc); } return rc; } public override Boolean CanRead => _stream.CanRead; public override Boolean CanSeek => _stream.CanSeek; public override Boolean CanWrite => _stream.CanWrite; public override Int64 Length => _stream.Length; public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } internal enum StreamMode { Writer, Reader, Undefined } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using o2dtk.Collections; namespace o2dtk { namespace TileMap { public class TileMapController : MonoBehaviour { // Static properties // The colors to draw the gizmos with public static Color gizmos_color_tile = new Color(0.5f, 0.5f, 0.5f, 1.0f); public static Color gizmos_color_chunk = new Color(0.75f, 0.75f, 0.75f, 1.0f); // User properties // The tile map the controller will use public TileMap tile_map = null; // The number of pixels per unit the controller should render at public float pixels_per_unit = 32.0f; // The render intercept to use (if any) public TileMapRenderIntercept render_intercept = null; // Whether to draw gridlines for the chunks public bool draw_chunk_gridlines = true; public bool draw_tile_gridlines = true; // When to draw gridlines (always, selected, or never) public enum GridlinesDrawTime { Always, Selected, Never } public GridlinesDrawTime when_draw_gridlines = GridlinesDrawTime.Always; // Public properties // Whether the controller has been initialized [SerializeField] private bool is_initialized = false; public bool initialized { get { return is_initialized; } private set { is_initialized = value; } } // The 4x4 matrix that transforms world space into local space public Matrix4x4 worldToLocalMatrix { get { return transform.worldToLocalMatrix; } } // The 4x4 matrix that transforms world space into map space public Matrix4x4 worldToMapMatrix { get { return localToMapMatrix * worldToLocalMatrix; } } // The 4x4 matrix that transforms world space into normal space public Matrix4x4 worldToNormalMatrix { get { return tile_map.mapToNormalMatrix * worldToMapMatrix; } } // The 4x4 matrix that transforms local space into world space public Matrix4x4 localToWorldMatrix { get { return transform.localToWorldMatrix; } } // The 4x4 matrix that transforms local space into map space public Matrix4x4 localToMapMatrix { get { return Matrix4x4.Scale(new Vector3(pixels_per_unit, pixels_per_unit, 1.0f)); } } // The 4x4 matrix that tarnsforms local space into normal space public Matrix4x4 localToNormalMatrix { get { return tile_map.mapToNormalMatrix * localToMapMatrix; } } // The 4x4 matrix that transforms map space into world space public Matrix4x4 mapToWorldMatrix { get { return localToWorldMatrix * mapToLocalMatrix; } } // The 4x4 matrix that transforms map space into world space public Matrix4x4 mapToLocalMatrix { get { return Matrix4x4.Scale(new Vector3(1.0f / pixels_per_unit, 1.0f / pixels_per_unit, 1.0f)); } } // The 4x4 matrix that transforms map space into normal space public Matrix4x4 mapToNormalMatrix { get { return tile_map.mapToNormalMatrix; } } // The compound 4x4 matrix that transforms normal space into world space public Matrix4x4 normalToWorldMatrix { get { return mapToWorldMatrix * tile_map.normalToMapMatrix; } } // The compound 4x4 matrix that transforms normal space into local space public Matrix4x4 normalToLocalMatrix { get { return mapToLocalMatrix * tile_map.normalToMapMatrix; } } // The compound 4x4 matrix that transforms normal space into map space public Matrix4x4 normalToMapMatrix { get { return tile_map.normalToMapMatrix; } } // Gets the coordinates of a tile in normal space public Vector3 TileToNormalSpace(int x, int y) { return tile_map.GetNormalCoordinates(x, y); } // Gets the tile of coordinates in normal space public void NormalToTile(Vector3 normal_point, out int x, out int y) { tile_map.GetTileFromNormalPoint(normal_point, out x, out y); } // Private properties // The transform of the controller [SerializeField] private Transform transform_ = null; public new Transform transform { get { if (transform_ == null) transform_ = GetComponent<Transform>(); return transform_; } } // The chunks that are currently loaded [System.Serializable] public class ChunkControllerMap : Map<IPair, TileChunkController> { } public ChunkControllerMap chunk_controllers = new ChunkControllerMap(); // The rendering root for the controller public GameObject render_root = null; public Transform render_root_transform = null; // The chunk root for rendering public GameObject chunk_root = null; public Transform chunk_root_transform = null; public void Awake() { if (initialized) throw new System.InvalidOperationException("Tile map initialized before play mode was entered"); Begin(); } public void OnDrawGizmos() { if (when_draw_gridlines == GridlinesDrawTime.Always) DrawGridlineGizmos(); } public void OnDrawGizmosSelected() { if (when_draw_gridlines == GridlinesDrawTime.Selected) DrawGridlineGizmos(); } bool ChooseGizmosColor(bool user_choice) { if (user_choice && draw_chunk_gridlines) Gizmos.color = gizmos_color_chunk; else { if (!draw_tile_gridlines) return false; Gizmos.color = gizmos_color_tile; } return true; } public void DrawGridlineGizmos() { if (tile_map == null || !(draw_chunk_gridlines || draw_tile_gridlines)) return; Gizmos.matrix = normalToWorldMatrix; switch (tile_map.tiling) { case TileMap.Tiling.Rectangular: case TileMap.Tiling.Isometric: { for (int x = tile_map.left; x <= tile_map.right + 1; ++x) { if (!ChooseGizmosColor(x % tile_map.chunk_size_x == 0)) continue; Gizmos.DrawLine(new Vector3(x, tile_map.bottom, 0.0f), new Vector3(x, tile_map.top + 1.0f, 0.0f)); } for (int y = tile_map.bottom; y <= tile_map.top + 1; ++y) { if (!ChooseGizmosColor(y % tile_map.chunk_size_y == 0)) continue; Gizmos.DrawLine(new Vector3(tile_map.left, y, 0.0f), new Vector3(tile_map.right + 1.0f, y, 0.0f)); } break; } case TileMap.Tiling.StaggeredOdd: case TileMap.Tiling.StaggeredEven: { float even_stagger = (tile_map.tiling == TileMap.Tiling.StaggeredOdd ? 0.0f : 0.5f); float odd_stagger = (tile_map.tiling == TileMap.Tiling.StaggeredOdd ? 0.5f : 0.0f); bool border_even = (tile_map.tiling == TileMap.Tiling.StaggeredOdd); for (int x = tile_map.left; x <= tile_map.right; ++x) { for (int y = tile_map.bottom; y <= tile_map.top; ++y) { bool border_chunk_down = (y % tile_map.chunk_size_y == 0); bool border_chunk_up = ((y + 1) % tile_map.chunk_size_y == 0); bool border_chunk_left = (x % tile_map.chunk_size_x == 0) && ((y % 2 == 0) == border_even); bool border_chunk_right = ((x + 1) % tile_map.chunk_size_x == 0) && ((y % 2 == 0) != border_even); float dx = x + (y % 2 == 0 ? even_stagger : odd_stagger); float dy = y / 2.0f; if (ChooseGizmosColor(border_chunk_down || border_chunk_left)) Gizmos.DrawLine(new Vector3(dx + 0.5f, dy, 0.0f), new Vector3(dx, dy + 0.5f, 0.0f)); if (ChooseGizmosColor(border_chunk_left || border_chunk_up)) Gizmos.DrawLine(new Vector3(dx, dy + 0.5f, 0.0f), new Vector3(dx + 0.5f, dy + 1.0f, 0.0f)); if (ChooseGizmosColor(border_chunk_up || border_chunk_right)) Gizmos.DrawLine(new Vector3(dx + 0.5f, dy + 1.0f, 0.0f), new Vector3(dx + 1.0f, dy + 0.5f, 0.0f)); if (ChooseGizmosColor(border_chunk_right || border_chunk_down)) Gizmos.DrawLine(new Vector3(dx + 1.0f, dy + 0.5f, 0.0f), new Vector3(dx + 0.5f, dy, 0.0f)); } } break; } default: Debug.LogWarning("Unsupported tiling on tile map!"); break; } } // Initializes the tile map controller public void Begin() { if (initialized || tile_map == null) return; chunk_controllers = new ChunkControllerMap(); render_root = new GameObject("render_root"); render_root_transform = render_root.GetComponent<Transform>(); render_root_transform.parent = transform; render_root_transform.localPosition = Vector3.zero; render_root_transform.localScale = Vector3.one; chunk_root = new GameObject("chunk_root"); chunk_root_transform = chunk_root.GetComponent<Transform>(); chunk_root_transform.parent = render_root_transform; chunk_root_transform.localPosition = Vector3.zero; chunk_root_transform.localScale = Vector3.one; initialized = true; } // Returns the tile map controller to its initial state public void End() { if (!initialized) return; Utility.GameObject.Destroy(render_root); Utility.GameObject.Destroy(chunk_root); chunk_controllers = null; render_root = null; render_root_transform = null; chunk_root = null; chunk_root_transform = null; initialized = false; } // Determines whether the given chunk is loaded or not public bool IsChunkLoaded(int index_x, int index_y) { return chunk_controllers.ContainsKey(new IPair(index_x, index_y)); } // Loads the chunk at the given indices public void LoadChunk(int index_x, int index_y) { IPair index = new IPair(index_x, index_y); if (chunk_controllers.ContainsKey(index)) return; TileChunk chunk = tile_map.GetChunk(index_x, index_y); if (chunk == null) return; chunk_controllers[index] = CreateChunk(chunk, index_x, index_y); } // Unloads the chunk at the given coordinates public void UnloadChunk(int index_x, int index_y) { IPair index = new IPair(index_x, index_y); if (chunk_controllers.ContainsKey(index)) { Utility.GameObject.Destroy(chunk_controllers[index].gameObject); chunk_controllers.Remove(index); } } // Makes a chunk and returns it public TileChunkController CreateChunk(TileChunk chunk, int index_x, int index_y) { GameObject chunk_go = new GameObject(index_x + "_" + index_y); TileChunkController controller = chunk_go.AddComponent<TileChunkController>(); controller.Initialize(this, chunk); return controller; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using BLToolkit.Common; using BLToolkit.ComponentModel; using BLToolkit.EditableObjects; using BLToolkit.Mapping; using BLToolkit.TypeBuilder; using BLToolkit.TypeBuilder.Builders; using JNotNull = JetBrains.Annotations.NotNullAttribute; namespace BLToolkit.Reflection { public delegate object NullValueProvider(Type type); public delegate bool IsNullHandler (object obj); [DebuggerDisplay("Type = {Type}, OriginalType = {OriginalType}")] public abstract class TypeAccessor : ICollection, ITypeDescriptionProvider, IEnumerable<MemberAccessor> { #region Protected Emit Helpers protected MemberInfo GetMember(int memberType, string memberName) { const BindingFlags allInstaceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; MemberInfo mi; switch (memberType) { case 1: mi = Type.GetField (memberName, allInstaceMembers); break; case 2: mi = Type. GetProperty(memberName, allInstaceMembers) ?? OriginalType.GetProperty(memberName, allInstaceMembers); break; default: throw new InvalidOperationException(); } return mi; } protected void AddMember(MemberAccessor member) { if (member == null) throw new ArgumentNullException("member"); _members.Add(member); _memberNames.Add(member.MemberInfo.Name, member); } #endregion #region CreateInstance [DebuggerStepThrough] public virtual object CreateInstance() { throw new TypeBuilderException(string.Format( "The '{0}' type must have public default or init constructor.", OriginalType.Name)); } [DebuggerStepThrough] public virtual object CreateInstance(InitContext context) { return CreateInstance(); } [DebuggerStepThrough] public object CreateInstanceEx() { return _objectFactory != null? _objectFactory.CreateInstance(this, null): CreateInstance((InitContext)null); } [DebuggerStepThrough] public object CreateInstanceEx(InitContext context) { return _objectFactory != null? _objectFactory.CreateInstance(this, context): CreateInstance(context); } #endregion #region ObjectFactory private IObjectFactory _objectFactory; public IObjectFactory ObjectFactory { get { return _objectFactory; } set { _objectFactory = value; } } #endregion #region Copy & AreEqual internal static object CopyInternal(object source, object dest, TypeAccessor ta) { bool isDirty = false; IMemberwiseEditable sourceEditable = source as IMemberwiseEditable; IMemberwiseEditable destEditable = dest as IMemberwiseEditable; if (sourceEditable != null && destEditable != null) { foreach (MemberAccessor ma in ta) { // BVChanges: XmlIgnoreAttribute && RelationAttribute if (ma.GetAttribute<System.Xml.Serialization.XmlIgnoreAttribute>() == null) { ma.CloneValue(source, dest); if (sourceEditable.IsDirtyMember(null, ma.MemberInfo.Name, ref isDirty) && !isDirty) destEditable.AcceptMemberChanges(null, ma.MemberInfo.Name); } } } else { foreach (MemberAccessor ma in ta) { // BVChanges: XmlIgnoreAttribute && RelationAttribute if (ma.GetAttribute<System.Xml.Serialization.XmlIgnoreAttribute>() == null) { ma.CloneValue(source, dest); } } } return dest; } public static object Copy(object source, object dest) { if (source == null) throw new ArgumentNullException("source"); if (dest == null) throw new ArgumentNullException("dest"); TypeAccessor ta; Type sType = source.GetType(); Type dType = dest. GetType(); if (TypeHelper.IsSameOrParent(sType, dType)) ta = GetAccessor(sType); else if (TypeHelper.IsSameOrParent(dType, sType)) ta = GetAccessor(dType); else throw new ArgumentException(); return CopyInternal(source, dest, ta); } public static object Copy(object source) { if (source == null) throw new ArgumentNullException("source"); TypeAccessor ta = GetAccessor(source.GetType()); return CopyInternal(source, ta.CreateInstanceEx(), ta); } public static bool AreEqual(object obj1, object obj2) { if (ReferenceEquals(obj1, obj2)) return true; if (obj1 == null || obj2 == null) return false; TypeAccessor ta; Type sType = obj1.GetType(); Type dType = obj2.GetType(); if (TypeHelper.IsSameOrParent(sType, dType)) ta = GetAccessor(sType); else if (TypeHelper.IsSameOrParent(dType, sType)) ta = GetAccessor(dType); else return false; foreach (MemberAccessor ma in ta) if ((!Equals(ma.GetValue(obj1), ma.GetValue(obj2)))) return false; return true; } public static int GetHashCode(object obj) { if (obj == null) throw new ArgumentNullException("obj"); int hash = 0; object value; foreach (MemberAccessor ma in GetAccessor(obj.GetType())) { value = ma.GetValue(obj); hash = ((hash << 5) + hash) ^ (value == null ? 0 : value.GetHashCode()); } return hash; } #endregion #region Abstract Members public abstract Type Type { get; } public abstract Type OriginalType { get; } #endregion #region Items private readonly ArrayList _members = new ArrayList(); private readonly Hashtable _memberNames = new Hashtable(); public MemberAccessor this[string memberName] { get { return (MemberAccessor)_memberNames[memberName]; } } public MemberAccessor this[int index] { get { return (MemberAccessor)_members[index]; } } public MemberAccessor this[NameOrIndexParameter nameOrIndex] { get { return (MemberAccessor) (nameOrIndex.ByName ? _memberNames[nameOrIndex.Name] : _members[nameOrIndex.Index]); } } #endregion #region Static Members [Obsolete("Use TypeFactory.LoadTypes instead")] public static bool LoadTypes { get { return TypeFactory.LoadTypes; } set { TypeFactory.LoadTypes = value; } } private static readonly Hashtable _accessors = new Hashtable(10); public static TypeAccessor GetAccessor(Type originalType) { if (originalType == null) throw new ArgumentNullException("originalType"); TypeAccessor accessor = (TypeAccessor)_accessors[originalType]; if (accessor == null) { lock (_accessors.SyncRoot) { accessor = (TypeAccessor)_accessors[originalType]; if (accessor == null) { if (IsAssociatedType(originalType)) return (TypeAccessor)_accessors[originalType]; Type instanceType = IsClassBulderNeeded(originalType)? null: originalType; if (instanceType == null) instanceType = TypeFactory.GetType(originalType); Type accessorType = TypeFactory.GetType(originalType, originalType, new TypeAccessorBuilder(instanceType, originalType)); accessor = (TypeAccessor)Activator.CreateInstance(accessorType); _accessors[originalType] = accessor; if (originalType != instanceType) _accessors[instanceType] = accessor; } } } return accessor; } public static TypeAccessor GetAccessor([JNotNull] object obj) { if (obj == null) throw new ArgumentNullException("obj"); return GetAccessor(obj.GetType()); } public static TypeAccessor GetAccessor<T>() { return TypeAccessor<T>.Instance; } private static bool IsClassBulderNeeded(Type type) { if (type.IsAbstract && !type.IsSealed) { if (!type.IsInterface) { if (TypeHelper.GetDefaultConstructor(type) != null) return true; if (TypeHelper.GetConstructor(type, typeof(InitContext)) != null) return true; } else { object[] attrs = TypeHelper.GetAttributes(type, typeof(AutoImplementInterfaceAttribute)); if (attrs != null && attrs.Length > 0) return true; } } return false; } internal static bool IsInstanceBuildable(Type type) { if (!type.IsInterface) return true; lock (_accessors.SyncRoot) { if (_accessors[type] != null) return true; if (IsAssociatedType(type)) return true; } object[] attrs = TypeHelper.GetAttributes(type, typeof(AutoImplementInterfaceAttribute)); return attrs != null && attrs.Length > 0; } private static bool IsAssociatedType(Type type) { if (AssociatedTypeHandler != null) { Type child = AssociatedTypeHandler(type); if (child != null) { AssociateType(type, child); return true; } } return false; } public static object CreateInstance(Type type) { return GetAccessor(type).CreateInstance(); } public static object CreateInstance(Type type, InitContext context) { return GetAccessor(type).CreateInstance(context); } public static object CreateInstanceEx(Type type) { return GetAccessor(type).CreateInstanceEx(); } public static object CreateInstanceEx(Type type, InitContext context) { return GetAccessor(type).CreateInstance(context); } public static T CreateInstance<T>() { return TypeAccessor<T>.CreateInstance(); } public static T CreateInstance<T>(InitContext context) { return TypeAccessor<T>.CreateInstance(context); } public static T CreateInstanceEx<T>() { return TypeAccessor<T>.CreateInstanceEx(); } public static T CreateInstanceEx<T>(InitContext context) { return TypeAccessor<T>.CreateInstance(context); } public static TypeAccessor AssociateType(Type parent, Type child) { if (!TypeHelper.IsSameOrParent(parent, child)) throw new ArgumentException( string.Format("'{0}' must be a base type of '{1}'", parent, child), "child"); TypeAccessor accessor = GetAccessor(child); accessor = (TypeAccessor)Activator.CreateInstance(accessor.GetType()); lock (_accessors.SyncRoot) _accessors[parent] = accessor; return accessor; } public delegate Type GetAssociatedType(Type parent); public static event GetAssociatedType AssociatedTypeHandler; #endregion #region GetNullValue private static NullValueProvider _getNullValue = GetNullInternal; public static NullValueProvider GetNullValue { get { return _getNullValue ?? (_getNullValue = GetNullInternal);} set { _getNullValue = value; } } private static object GetNullInternal(Type type) { if (type == null) throw new ArgumentNullException("type"); if (type.IsValueType) { if (type.IsEnum) return GetEnumNullValue(type); if (type.IsPrimitive) { if (type == typeof(Int32)) return Common.Configuration.NullableValues.Int32; if (type == typeof(Double)) return Common.Configuration.NullableValues.Double; if (type == typeof(Int16)) return Common.Configuration.NullableValues.Int16; if (type == typeof(Boolean)) return Common.Configuration.NullableValues.Boolean; if (type == typeof(SByte)) return Common.Configuration.NullableValues.SByte; if (type == typeof(Int64)) return Common.Configuration.NullableValues.Int64; if (type == typeof(Byte)) return Common.Configuration.NullableValues.Byte; if (type == typeof(UInt16)) return Common.Configuration.NullableValues.UInt16; if (type == typeof(UInt32)) return Common.Configuration.NullableValues.UInt32; if (type == typeof(UInt64)) return Common.Configuration.NullableValues.UInt64; if (type == typeof(Single)) return Common.Configuration.NullableValues.Single; if (type == typeof(Char)) return Common.Configuration.NullableValues.Char; } else { if (type == typeof(DateTime)) return Common.Configuration.NullableValues.DateTime; #if FW3 if (type == typeof(DateTimeOffset)) return Common.Configuration.NullableValues.DateTimeOffset; #endif if (type == typeof(Decimal)) return Common.Configuration.NullableValues.Decimal; if (type == typeof(Guid)) return Common.Configuration.NullableValues.Guid; if (type == typeof(SqlInt32)) return SqlInt32. Null; if (type == typeof(SqlString)) return SqlString. Null; if (type == typeof(SqlBoolean)) return SqlBoolean. Null; if (type == typeof(SqlByte)) return SqlByte. Null; if (type == typeof(SqlDateTime)) return SqlDateTime.Null; if (type == typeof(SqlDecimal)) return SqlDecimal. Null; if (type == typeof(SqlDouble)) return SqlDouble. Null; if (type == typeof(SqlGuid)) return SqlGuid. Null; if (type == typeof(SqlInt16)) return SqlInt16. Null; if (type == typeof(SqlInt64)) return SqlInt64. Null; if (type == typeof(SqlMoney)) return SqlMoney. Null; if (type == typeof(SqlSingle)) return SqlSingle. Null; if (type == typeof(SqlBinary)) return SqlBinary. Null; } } else { if (type == typeof(String)) return Common.Configuration.NullableValues.String; if (type == typeof(DBNull)) return DBNull.Value; if (type == typeof(Stream)) return Stream.Null; if (type == typeof(SqlXml)) return SqlXml.Null; } return null; } const FieldAttributes EnumField = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal; private static readonly Hashtable _nullValues = new Hashtable(); private static object GetEnumNullValue(Type type) { object nullValue = _nullValues[type]; if (nullValue != null || _nullValues.Contains(type)) return nullValue; FieldInfo[] fields = type.GetFields(); foreach (FieldInfo fi in fields) { if ((fi.Attributes & EnumField) == EnumField) { Attribute[] attrs = Attribute.GetCustomAttributes(fi, typeof(NullValueAttribute)); if (attrs.Length > 0) { nullValue = Enum.Parse(type, fi.Name); break; } } } _nullValues[type] = nullValue; return nullValue; } private static IsNullHandler _isNull = IsNullInternal; public static IsNullHandler IsNull { get { return _isNull ?? (_isNull = IsNullInternal); } set { _isNull = value; } } private static bool IsNullInternal(object value) { if (value == null) return true; object nullValue = GetNullValue(value.GetType()); return nullValue != null && value.Equals(nullValue); } #endregion #region ICollection Members public void CopyTo(Array array, int index) { _members.CopyTo(array, index); } public int Count { get { return _members.Count; } } public bool IsSynchronized { get { return _members.IsSynchronized; } } public object SyncRoot { get { return _members.SyncRoot; } } public int IndexOf(MemberAccessor ma) { return _members.IndexOf(ma); } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return _members.GetEnumerator(); } #endregion #region Write Object Info public static void WriteDebug(object o) { #if DEBUG Write(o, DebugWriteLine); #endif } private static void DebugWriteLine(string text) { Debug.WriteLine(text); } public static void WriteConsole(object o) { Write(o, Console.WriteLine); } [SuppressMessage("Microsoft.Performance", "CA1818:DoNotConcatenateStringsInsideLoops")] private static string MapTypeName(Type type) { if (type.IsGenericType) { if (type.GetGenericTypeDefinition() == typeof(Nullable<>)) return string.Format("{0}?", MapTypeName(Nullable.GetUnderlyingType(type))); string name = type.Name; int idx = name.IndexOf('`'); if (idx >= 0) name = name.Substring(0, idx); name += "<"; foreach (Type t in type.GetGenericArguments()) name += MapTypeName(t) + ','; if (name[name.Length - 1] == ',') name = name.Substring(0, name.Length - 1); name += ">"; return name; } if (type.IsPrimitive || type == typeof(string) || type == typeof(object) || type == typeof(decimal)) { if (type == typeof(int)) return "int"; if (type == typeof(bool)) return "bool"; if (type == typeof(short)) return "short"; if (type == typeof(long)) return "long"; if (type == typeof(ushort)) return "ushort"; if (type == typeof(uint)) return "uint"; if (type == typeof(ulong)) return "ulong"; if (type == typeof(float)) return "float"; return type.Name.ToLower(); } return type.Name; } public delegate void WriteLine(string text); [SuppressMessage("Microsoft.Usage", "CA2241:ProvideCorrectArgumentsToFormattingMethods")] public static void Write(object o, WriteLine writeLine) { if (o == null) { writeLine("*** (null) ***"); return; } TypeAccessor ta = GetAccessor(o.GetType()); MemberAccessor ma; int nameLen = 0; int typeLen = 0; foreach (DictionaryEntry de in ta._memberNames) { if (nameLen < de.Key.ToString().Length) nameLen = de.Key.ToString().Length; ma = (MemberAccessor)de.Value; if (typeLen < MapTypeName(ma.Type).Length) typeLen = MapTypeName(ma.Type).Length; } string text = "*** " + o.GetType().FullName + ": ***"; writeLine(text); string format = string.Format("{{0,-{0}}} {{1,-{1}}} : {{2}}", typeLen, nameLen); foreach (DictionaryEntry de in ta._memberNames) { ma = (MemberAccessor)de.Value; object value = ma.GetValue(o); if (value == null) value = "(null)"; else if (value is ICollection) value = string.Format("(Count = {0})", ((ICollection)value).Count); text = string.Format(format, MapTypeName(ma.Type), de.Key, value); writeLine(text); } writeLine("***"); } #endregion #region CustomTypeDescriptor private static readonly Hashtable _descriptors = new Hashtable(); public static ICustomTypeDescriptor GetCustomTypeDescriptor(Type type) { ICustomTypeDescriptor descriptor = (ICustomTypeDescriptor)_descriptors[type]; if (descriptor == null) { lock (_descriptors.SyncRoot) { descriptor = (ICustomTypeDescriptor)_descriptors[type]; if (descriptor == null) { descriptor = new CustomTypeDescriptorImpl(type); _descriptors.Add(type, descriptor); } } } return descriptor; } private ICustomTypeDescriptor _customTypeDescriptor; public ICustomTypeDescriptor CustomTypeDescriptor { get { if (_customTypeDescriptor == null) _customTypeDescriptor = GetCustomTypeDescriptor(OriginalType); return _customTypeDescriptor; } } #endregion #region Property Descriptors private PropertyDescriptorCollection _propertyDescriptors; public PropertyDescriptorCollection PropertyDescriptors { get { if (_propertyDescriptors == null) { if (TypeHelper.IsSameOrParent(typeof(ICustomTypeDescriptor), OriginalType)) { ICustomTypeDescriptor descriptor = CreateInstance() as ICustomTypeDescriptor; if (descriptor != null) _propertyDescriptors = descriptor.GetProperties(); } if (_propertyDescriptors == null) _propertyDescriptors = CreatePropertyDescriptors(); } return _propertyDescriptors; } } public PropertyDescriptorCollection CreatePropertyDescriptors() { Debug.WriteLineIf(BLToolkit.Data.DbManager.TraceSwitch.TraceInfo, OriginalType.FullName, "CreatePropertyDescriptors"); PropertyDescriptor[] pd = new PropertyDescriptor[Count]; int i = 0; foreach (MemberAccessor ma in _members) pd[i++] = ma.PropertyDescriptor; return new PropertyDescriptorCollection(pd); } public PropertyDescriptorCollection CreateExtendedPropertyDescriptors( Type objectViewType, IsNullHandler isNull) { // This is definitely wrong. // //if (isNull == null) // isNull = _isNull; PropertyDescriptorCollection pdc; pdc = CreatePropertyDescriptors(); if (objectViewType != null) { TypeAccessor viewAccessor = GetAccessor(objectViewType); IObjectView objectView = (IObjectView)viewAccessor.CreateInstanceEx(); List<PropertyDescriptor> list = new List<PropertyDescriptor>(); PropertyDescriptorCollection viewpdc = viewAccessor.PropertyDescriptors; foreach (PropertyDescriptor pd in viewpdc) list.Add(new ObjectViewPropertyDescriptor(pd, objectView)); foreach (PropertyDescriptor pd in pdc) if (viewpdc.Find(pd.Name, false) == null) list.Add(pd); pdc = new PropertyDescriptorCollection(list.ToArray()); } pdc = pdc.Sort(new PropertyDescriptorComparer()); pdc = GetExtendedProperties(pdc, OriginalType, String.Empty, Type.EmptyTypes, new PropertyDescriptor[0], isNull); return pdc; } private static PropertyDescriptorCollection GetExtendedProperties( PropertyDescriptorCollection pdc, Type itemType, string propertyPrefix, Type[] parentTypes, PropertyDescriptor[] parentAccessors, IsNullHandler isNull) { ArrayList list = new ArrayList(pdc.Count); ArrayList objects = new ArrayList(); bool isDataRow = itemType.IsSubclassOf(typeof(DataRow)); foreach (PropertyDescriptor p in pdc) { Type propertyType = p.PropertyType; // bv var disp = false; foreach (Attribute o in p.Attributes) { if (((Type)o.TypeId).FullName == "eidss.model.Core.LocalizedDisplayNameAttribute") { disp = true; break; } } if (!disp) continue; // bv if (p.Attributes.Matches(BindableAttribute.No) || //propertyType == typeof(Type) || isDataRow && p.Name == "ItemArray") continue; bool isList = false; bool explicitlyBound = p.Attributes.Contains(BindableAttribute.Yes); PropertyDescriptor pd = p; if (propertyType.GetInterface("IList") != null) { //if (!explicitlyBound) // continue; isList = true; pd = new ListPropertyDescriptor(pd); } if (!isList && !propertyType.IsValueType && !propertyType.IsArray && (!propertyType.FullName.StartsWith("System.") || explicitlyBound || propertyType.IsGenericType) && propertyType != typeof(Type) && propertyType != typeof(string) && propertyType != typeof(object) && Array.IndexOf(parentTypes, propertyType) == -1) { Type[] childParentTypes = new Type[parentTypes.Length + 1]; parentTypes.CopyTo(childParentTypes, 0); childParentTypes[parentTypes.Length] = itemType; PropertyDescriptor[] childParentAccessors = new PropertyDescriptor[parentAccessors.Length + 1]; parentAccessors.CopyTo(childParentAccessors, 0); childParentAccessors[parentAccessors.Length] = pd; PropertyDescriptorCollection pdch = GetAccessor(propertyType).PropertyDescriptors; pdch = pdch.Sort(new PropertyDescriptorComparer()); pdch = GetExtendedProperties( pdch, propertyType, propertyPrefix + pd.Name + "+", childParentTypes, childParentAccessors, isNull); objects.AddRange(pdch); } else { if (propertyPrefix.Length != 0 || isNull != null) pd = new StandardPropertyDescriptor(pd, propertyPrefix, parentAccessors, isNull); list.Add(pd); } } list.AddRange(objects); return new PropertyDescriptorCollection( (PropertyDescriptor[])list.ToArray(typeof(PropertyDescriptor))); } #region PropertyDescriptorComparer class PropertyDescriptorComparer : IComparer { public int Compare(object x, object y) { return String.Compare(((PropertyDescriptor)x).Name, ((PropertyDescriptor)y).Name); } } #endregion #region ListPropertyDescriptor class ListPropertyDescriptor : PropertyDescriptorWrapper { public ListPropertyDescriptor(PropertyDescriptor descriptor) : base(descriptor) { } public override object GetValue(object component) { object value = base.GetValue(component); if (value == null) return value; if (value is IBindingList && value is ITypedList) return value; return EditableArrayList.Adapter((IList)value); } } #endregion #region StandardPropertyDescriptor class StandardPropertyDescriptor : PropertyDescriptorWrapper { protected readonly PropertyDescriptor _descriptor = null; protected readonly IsNullHandler _isNull; protected readonly string _prefixedName; protected readonly PropertyDescriptor[] _chainAccessors; public StandardPropertyDescriptor( PropertyDescriptor pd, string namePrefix, PropertyDescriptor[] chainAccessors, IsNullHandler isNull) : base(pd) { _descriptor = pd; _isNull = isNull; _prefixedName = namePrefix + pd.Name; _chainAccessors = chainAccessors; } protected object GetNestedComponent(object component) { for (int i = 0; i < _chainAccessors.Length && component != null && !(component is DBNull); i++) { component = _chainAccessors[i].GetValue(component); } return component; } public override void SetValue(object component, object value) { component = GetNestedComponent(component); if (component != null && !(component is DBNull)) _descriptor.SetValue(component, value); } public override object GetValue(object component) { component = GetNestedComponent(component); return CheckNull( component != null && !(component is DBNull)? _descriptor.GetValue(component): null); } public override string Name { get { return _prefixedName; } } protected object CheckNull(object value) { if (_isNull != null && _isNull(value)) { switch (Common.Configuration.CheckNullReturnIfNull) { case Common.Configuration.NullEquivalent.DBNull: return DBNull.Value; case Common.Configuration.NullEquivalent.Null: return null; case Common.Configuration.NullEquivalent.Value: return value; } return DBNull.Value; } return value; } } #endregion #region objectViewPropertyDescriptor class ObjectViewPropertyDescriptor : PropertyDescriptorWrapper { public ObjectViewPropertyDescriptor(PropertyDescriptor pd, IObjectView objectView) : base(pd) { _objectView = objectView; } private readonly IObjectView _objectView; public override object GetValue(object component) { _objectView.Object = component; return base.GetValue(_objectView); } public override void SetValue(object component, object value) { _objectView.Object = component; base.SetValue(_objectView, value); } } #endregion #endregion #region ITypeDescriptionProvider Members string ITypeDescriptionProvider.ClassName { get { return OriginalType.Name; } } string ITypeDescriptionProvider.ComponentName { get { return OriginalType.Name; } } EventDescriptor ITypeDescriptionProvider.GetEvent(string name) { return new CustomEventDescriptor(OriginalType.GetEvent(name)); } PropertyDescriptor ITypeDescriptionProvider.GetProperty(string name) { MemberAccessor ma = this[name]; return ma != null ? ma.PropertyDescriptor : null; } AttributeCollection ITypeDescriptionProvider.GetAttributes() { return new AttributeCollection((Attribute[])new TypeHelper(OriginalType).GetAttributes()); } EventDescriptorCollection ITypeDescriptionProvider.GetEvents() { EventInfo[] ei = OriginalType.GetEvents(); EventDescriptor[] ed = new EventDescriptor[ei.Length]; for (int i = 0; i < ei.Length; i++) ed[i] = new CustomEventDescriptor(ei[i]); return new EventDescriptorCollection(ed); } PropertyDescriptorCollection ITypeDescriptionProvider.GetProperties() { return CreatePropertyDescriptors(); } #region CustomEventDescriptor class CustomEventDescriptor : EventDescriptor { public CustomEventDescriptor(EventInfo eventInfo) : base(eventInfo.Name, null) { _eventInfo = eventInfo; } private readonly EventInfo _eventInfo; public override void AddEventHandler(object component, Delegate value) { _eventInfo.AddEventHandler(component, value); } public override void RemoveEventHandler(object component, Delegate value) { _eventInfo.RemoveEventHandler(component, value); } public override Type ComponentType { get { return _eventInfo.DeclaringType; } } public override Type EventType { get { return _eventInfo.EventHandlerType; } } public override bool IsMulticast { get { return _eventInfo.IsMulticast; } } } #endregion #endregion #region IEnumerable<MemberAccessor> Members IEnumerator<MemberAccessor> IEnumerable<MemberAccessor>.GetEnumerator() { foreach (MemberAccessor member in _members) yield return member; } #endregion } }
//============================================================================= // System : EWSoftware Design Time Attributes and Editors // File : NamespaceSummaryItemEditorDlg.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 07/27/2008 // Note : Copyright 2006-2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains the form used to edit namespace summaries and to indicate // which namespaces should appear in the help file. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.2.0.0 09/04/2006 EFW Created the code // 1.4.0.0 02/12/2007 EFW Added the ability to delete old namespaces // 1.6.0.4 01/17/2008 EFW Added more error info to help diagnose exceptions // when an assembly fails to load. // 1.6.0.6 03/07/2008 EFW Added filter options and reworked the namespace // extract to use a partial build rather than the // assembly loader to prevent "assembly not found" // errors caused by nested dependencies. // 1.8.0.0 06/30/2008 EFW Reworked to support MSBuild project format //============================================================================= using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; using SandcastleBuilder.Utils; using SandcastleBuilder.Utils.BuildEngine; using SandcastleBuilder.Utils.Gac; namespace SandcastleBuilder.Utils.Design { /// <summary> /// This form is used to edit namespace summaries and to indicate which /// namespaces should appear in the help file. /// </summary> public partial class NamespaceSummaryItemEditorDlg : Form { #region Private data members //===================================================================== private SandcastleProject tempProject; private NamespaceSummaryItemCollection nsColl; private Dictionary<string, List<string>> namespaceInfo; private SortedDictionary<string, NamespaceSummaryItem> namespaceItems; private Thread buildThread; private BuildProcess buildProcess; #endregion #region Constructor //===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="items">The namespace summary item collection to edit</param> public NamespaceSummaryItemEditorDlg(NamespaceSummaryItemCollection items) { InitializeComponent(); nsColl = items; namespaceItems = new SortedDictionary<string, NamespaceSummaryItem>(); // Get a copy of the current namespace summary items foreach(NamespaceSummaryItem nsi in nsColl) namespaceItems.Add(nsi.Name, nsi); } #endregion #region Build methods //===================================================================== // Build methods /// <summary> /// This is called by the build process thread to update the main /// window with the current build step. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void buildProcess_BuildStepChanged(object sender, BuildProgressEventArgs e) { if(this.InvokeRequired) { // Ignore it if we've already shut down or it hasn't // completed yet. if(!this.IsDisposed) this.Invoke(new EventHandler<BuildProgressEventArgs>( buildProcess_BuildStepChanged), new object[] { sender, e }); } else { lblProgress.Text = e.BuildStep.ToString(); if(e.HasCompleted) { // Switch back to the current project's folder Directory.SetCurrentDirectory(Path.GetDirectoryName( nsColl.Project.Filename)); // If successful, load the namespace nodes, and enable // the UI. if(e.BuildStep == BuildStep.Completed) { this.LoadNamespaces(buildProcess.ReflectionInfoFilename); cboAssembly.Enabled = txtSearchText.Enabled = btnApplyFilter.Enabled = btnAll.Enabled = btnNone.Enabled = true; } pbWait.Visible = lblProgress.Visible = false; lbNamespaces.Focus(); buildThread = null; buildProcess = null; } } } /// <summary> /// This is called by the build process thread to update the main /// window with information about its progress. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void buildProcess_BuildProgress(object sender, BuildProgressEventArgs e) { if(this.InvokeRequired) { // Ignore it if we've already shut down if(!this.IsDisposed) this.Invoke(new EventHandler<BuildProgressEventArgs>( buildProcess_BuildProgress), new object[] { sender, e }); } else { if(e.BuildStep == BuildStep.Failed) { MessageBox.Show("Unable to build project to obtain " + "API information. Please perform a normal build " + "to identify and correct the problem.", Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } /// <summary> /// Load the namespace information from the reflection information /// </summary> /// <param name="reflectionFile">The reflection information filename</param> private void LoadNamespaces(string reflectionFile) { XPathDocument reflectionInfo; XPathNavigator navDoc, navNamespace, navLibrary; List<string> assemblies; string nsName, asmName; namespaceInfo = new Dictionary<string, List<string>>(); try { this.Cursor = Cursors.WaitCursor; lblProgress.Text = "Loading namespace information..."; Application.DoEvents(); reflectionInfo = new XPathDocument(reflectionFile); navDoc = reflectionInfo.CreateNavigator(); // Namespace nodes don't contain assembly info so we'll have // to look at all types and add all unique namespaces from // their container info. foreach(XPathNavigator container in navDoc.Select( "reflection/apis/api[starts-with(@id, 'T:')]/containers")) { navNamespace = container.SelectSingleNode("namespace"); navLibrary = container.SelectSingleNode("library"); if(navNamespace != null && navLibrary != null) { nsName = navNamespace.GetAttribute("api", String.Empty).Substring(2); asmName = navLibrary.GetAttribute("assembly", String.Empty); if(namespaceInfo.TryGetValue(nsName, out assemblies)) { if(!assemblies.Contains(asmName)) assemblies.Add(asmName); } else { assemblies = new List<string>(); assemblies.Add(asmName); namespaceInfo.Add(nsName, assemblies); } } Application.DoEvents(); } // The global namespace (N:) isn't always listed but we'll // add it as it does show up in the reflection info anyway. if(!namespaceInfo.ContainsKey(String.Empty)) namespaceInfo.Add(String.Empty, new List<string>()); // Add new namespaces to the list as temporary items. They // will get added to the project if modified. foreach(string ns in namespaceInfo.Keys) { nsName = (ns.Length == 0) ? "(global)" : ns; if(!namespaceItems.ContainsKey(nsName)) namespaceItems.Add(ns, nsColl.CreateTemporaryItem(ns)); // Sort the assemblies for each namespace assemblies = namespaceInfo[ns]; assemblies.Sort(); } Application.DoEvents(); // Add all unique assembly names to the assembly combo box assemblies = new List<string>(); foreach(List<string> asmList in namespaceInfo.Values) foreach(string asm in asmList) if(!assemblies.Contains(asm)) assemblies.Add(asm); assemblies.Sort(); assemblies.Insert(0, "<All>"); cboAssembly.DataSource = assemblies; btnApplyFilter_Click(this, EventArgs.Empty); } finally { this.Cursor = Cursors.Default; } } #endregion #region General event handlers //===================================================================== /// <summary> /// Do a partial build on load to gather new namespace information that /// isn't currently in the project's namespace list. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void NamespacesDlg_Load(object sender, EventArgs e) { string tempPath; cboAssembly.Enabled = txtSearchText.Enabled = btnAll.Enabled = btnNone.Enabled = btnApplyFilter.Enabled = btnDelete.Enabled = false; try { // Clone the project for the build and adjust its properties // for our needs. tempProject = new SandcastleProject(nsColl.Project, true); // The temporary project resides in the same folder as the // current project (by filename only, it isn't saved) to // maintain relative paths. However, build output is stored // in a temporary folder and it keeps the intermediate files. tempProject.CleanIntermediates = false; tempPath = Path.GetTempFileName(); File.Delete(tempPath); tempPath = Path.Combine(Path.GetDirectoryName(tempPath), "SHFBPartialBuild"); if(!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath); tempProject.OutputPath = tempPath; buildProcess = new BuildProcess(tempProject, true); buildProcess.BuildStepChanged += new EventHandler<BuildProgressEventArgs>( buildProcess_BuildStepChanged); buildProcess.BuildProgress += new EventHandler<BuildProgressEventArgs>( buildProcess_BuildProgress); buildThread = new Thread(new ThreadStart(buildProcess.Build)); buildThread.Name = "Namespace partial build thread"; buildThread.IsBackground = true; buildThread.Start(); } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); MessageBox.Show("Unable to build project to obtain " + "API information. Error: " + ex.Message, Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// Shut down the build process thread and clean up on exit /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void NamespacesDlg_FormClosing(object sender, FormClosingEventArgs e) { if(buildThread != null && buildThread.IsAlive) { if(MessageBox.Show("A build is currently taking place to " + "obtain namespace information. Do you want to abort it " + "and close this form?", Constants.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { e.Cancel = true; return; } try { this.Cursor = Cursors.WaitCursor; if(buildThread != null) buildThread.Abort(); while(buildThread != null && !buildThread.Join(1000)) Application.DoEvents(); System.Diagnostics.Debug.WriteLine("Thread stopped"); } finally { this.Cursor = Cursors.Default; buildThread = null; buildProcess = null; } } // Delete the temporary project's working files if(!String.IsNullOrEmpty(tempProject.OutputPath) && Directory.Exists(tempProject.OutputPath)) Directory.Delete(tempProject.OutputPath, true); GC.Collect(2); GC.WaitForPendingFinalizers(); GC.Collect(2); } /// <summary> /// Store the changes and close the dialog box /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnClose_Click(object sender, EventArgs e) { // Add new items that were modified foreach(NamespaceSummaryItem item in lbNamespaces.Items) if(item.IsDirty && nsColl[item.Name] == null) nsColl.Add(item); this.DialogResult = nsColl.IsDirty ? DialogResult.OK : DialogResult.Cancel; this.Close(); } /// <summary> /// View help for this form /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnHelp_Click(object sender, EventArgs e) { string path = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location); try { #if DEBUG path += @"\..\..\..\Doc\Help\SandcastleBuilder.chm"; #else path += @"\SandcastleBuilder.chm"; #endif Form form = new Form(); form.CreateControl(); Help.ShowHelp(form, path, HelpNavigator.Topic, "html/eb7e1bc7-21c5-4453-bbaf-dec8c62c15bd.htm"); } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); MessageBox.Show(String.Format(CultureInfo.CurrentCulture, "Unable to open help file '{0}'. Reason: {1}", path, ex.Message), Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } /// <summary> /// When the item changes, show its summary in the text box and set /// the Appears In list box data source. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void lbNamespaces_SelectedIndexChanged(object sender, EventArgs e) { List<string> assemblies; string name; if(lbNamespaces.SelectedIndex != -1) { NamespaceSummaryItem nsi = (NamespaceSummaryItem)lbNamespaces.SelectedItem; txtSummary.Text = nsi.Summary; name = nsi.Name; if(name[0] == '(') name = String.Empty; if(namespaceInfo.TryGetValue(name, out assemblies)) lbAppearsIn.DataSource = assemblies; else lbAppearsIn.DataSource = null; } else { txtSummary.Text = null; lbAppearsIn.DataSource = null; } } /// <summary> /// Mark the summary item as documented or not when the check state /// changes. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lbNamespaces_ItemCheck(object sender, ItemCheckEventArgs e) { NamespaceSummaryItem nsi = (NamespaceSummaryItem)lbNamespaces.Items[e.Index]; bool isChecked = (e.NewValue == CheckState.Checked); if(nsi.IsDocumented != isChecked) nsi.IsDocumented = isChecked; } /// <summary> /// Clear the selection to prevent accidental deletion of the text /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void txtSummary_Enter(object sender, EventArgs e) { txtSummary.Select(0, 0); txtSummary.ScrollToCaret(); } /// <summary> /// Store changes to the summary when the textbox loses focus /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void txtSummary_Leave(object sender, EventArgs e) { NamespaceSummaryItem nsi = (NamespaceSummaryItem)lbNamespaces.SelectedItem; if(nsi != null && nsi.Summary != txtSummary.Text) nsi.Summary = txtSummary.Text; } /// <summary> /// Delete an old namespace entry that is no longer needed. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnDelete_Click(object sender, EventArgs e) { NamespaceSummaryItem nsi; int idx = lbNamespaces.SelectedIndex; if(idx == -1) lbNamespaces.SelectedIndex = 0; else { nsi = (NamespaceSummaryItem)lbNamespaces.Items[idx]; lbNamespaces.Items.RemoveAt(idx); nsi = nsColl[nsi.Name]; if(nsi != null) nsColl.Remove(nsi); if(lbNamespaces.Items.Count == 0) btnDelete.Enabled = txtSummary.Enabled = false; else if(idx < lbNamespaces.Items.Count) lbNamespaces.SelectedIndex = idx; else lbNamespaces.SelectedIndex = lbNamespaces.Items.Count - 1; } } /// <summary> /// Apply the namespace filter to the namespace list /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnApplyFilter_Click(object sender, EventArgs e) { NamespaceSummaryItem nsi; List<string> assemblies; Regex reFilter = null; lbNamespaces.Items.Clear(); string name; txtSearchText.Text = txtSearchText.Text.Trim(); if(txtSearchText.Text.Length != 0) try { reFilter = new Regex(txtSearchText.Text, RegexOptions.IgnoreCase); } catch(ArgumentException ex) { epErrors.SetError(txtSearchText, "The search regular " + "expression is not valid: " + ex.Message); return; } // Add the items to the listbox in sorted order by name foreach(string key in namespaceItems.Keys) { nsi = namespaceItems[key]; // Filter by assembly? if(cboAssembly.SelectedIndex != 0) { name = nsi.Name; if(name[0] == '(') name = String.Empty; if(namespaceInfo.TryGetValue(name, out assemblies)) if(!assemblies.Contains(cboAssembly.Text)) continue; } // Filter by search text? if(reFilter != null && !reFilter.IsMatch(nsi.Name)) continue; lbNamespaces.Items.Add(nsi, nsi.IsDocumented); } if(lbNamespaces.Items.Count != 0) { btnDelete.Enabled = txtSummary.Enabled = true; lbNamespaces.SelectedIndex = 0; } else btnDelete.Enabled = txtSummary.Enabled = false; } /// <summary> /// Mark all namespaces as included /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnAll_Click(object sender, EventArgs e) { for(int idx = 0; idx < lbNamespaces.Items.Count; idx++) lbNamespaces.SetItemChecked(idx, true); } /// <summary> /// Mark all namespaces as excluded /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> /// <remarks>Note that at least one will need to be selected or the /// build will fail due to lack of information to document.</remarks> private void btnNone_Click(object sender, EventArgs e) { for(int idx = 0; idx < lbNamespaces.Items.Count; idx++) lbNamespaces.SetItemChecked(idx, false); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalGridServicesConnector")] public class LocalGridServicesConnector : ISharedRegionModule, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[LOCAL GRID SERVICE CONNECTOR]"; private bool m_Enabled; private IGridService m_GridService; private Dictionary<UUID, RegionCache> m_LocalCache = new Dictionary<UUID, RegionCache>(); public LocalGridServicesConnector() { m_log.DebugFormat("{0} LocalGridServicesConnector no parms.", LogHeader); } public LocalGridServicesConnector(IConfigSource source) { m_log.DebugFormat("{0} LocalGridServicesConnector instantiated directly.", LogHeader); InitialiseService(source); } #region ISharedRegionModule public string Name { get { return "LocalGridServicesConnector"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (!m_Enabled) return; scene.RegisterModuleInterface<IGridService>(this); lock (m_LocalCache) { if (m_LocalCache.ContainsKey(scene.RegionInfo.RegionID)) m_log.ErrorFormat("[LOCAL GRID SERVICE CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!"); else m_LocalCache.Add(scene.RegionInfo.RegionID, new RegionCache(scene)); } } public void Close() { } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("GridServices", ""); if (name == Name) { InitialiseService(source); m_log.Info("[LOCAL GRID SERVICE CONNECTOR]: Local grid connector enabled"); } } } public void PostInitialise() { // FIXME: We will still add this command even if we aren't enabled since RemoteGridServiceConnector // will have instantiated us directly. MainConsole.Instance.Commands.AddCommand("Regions", false, "show neighbours", "show neighbours", "Shows the local regions' neighbours", HandleShowNeighboursCommand); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; lock (m_LocalCache) { m_LocalCache[scene.RegionInfo.RegionID].Clear(); m_LocalCache.Remove(scene.RegionInfo.RegionID); } } private void InitialiseService(IConfigSource source) { IConfig assetConfig = source.Configs["GridService"]; if (assetConfig == null) { m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: GridService missing from OpenSim.ini"); return; } string serviceDll = assetConfig.GetString("LocalServiceModule", String.Empty); if (serviceDll == String.Empty) { m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: No LocalServiceModule named in section GridService"); return; } Object[] args = new Object[] { source }; m_GridService = ServerUtils.LoadPlugin<IGridService>(serviceDll, args); if (m_GridService == null) { m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: Can't load grid service"); return; } m_Enabled = true; } #endregion ISharedRegionModule #region IGridService public bool DeregisterRegion(UUID regionID) { return m_GridService.DeregisterRegion(regionID); } public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID) { return m_GridService.GetDefaultHypergridRegions(scopeID); } public List<GridRegion> GetDefaultRegions(UUID scopeID) { return m_GridService.GetDefaultRegions(scopeID); } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { return m_GridService.GetFallbackRegions(scopeID, x, y); } public List<GridRegion> GetHyperlinks(UUID scopeID) { return m_GridService.GetHyperlinks(scopeID); } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { return m_GridService.GetNeighbours(scopeID, regionID); } public GridRegion GetRegionByName(UUID scopeID, string regionName) { return m_GridService.GetRegionByName(scopeID, regionName); } // Get a region given its base coordinates. // NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST // be the base coordinate of the region. public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { GridRegion region = null; // First see if it's a neighbour, even if it isn't on this sim. // Neighbour data is cached in memory, so this is fast lock (m_LocalCache) { foreach (RegionCache rcache in m_LocalCache.Values) { region = rcache.GetRegionByPosition(x, y); if (region != null) { // m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in cache. Pos=<{2},{3}>", // LogHeader, region.RegionName, x, y); break; } } } // Then try on this sim (may be a lookup in DB if this is using MySql). if (region == null) { region = m_GridService.GetRegionByPosition(scopeID, x, y); if (region == null) m_log.DebugFormat("{0} GetRegionByPosition. Region not found by grid service. Pos=<{1},{2}>", LogHeader, x, y); else m_log.DebugFormat("{0} GetRegionByPosition. Requested region {1} from grid service. Pos=<{2},{3}>", LogHeader, region.RegionName, x, y); } return region; } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { return m_GridService.GetRegionByUUID(scopeID, regionID); } public int GetRegionFlags(UUID scopeID, UUID regionID) { return m_GridService.GetRegionFlags(scopeID, regionID); } public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { return m_GridService.GetRegionsByName(scopeID, name, maxNumber); } public string RegisterRegion(UUID scopeID, GridRegion regionInfo) { return m_GridService.RegisterRegion(scopeID, regionInfo); } #endregion IGridService public void HandleShowNeighboursCommand(string module, string[] cmdparams) { System.Text.StringBuilder caps = new System.Text.StringBuilder(); lock (m_LocalCache) { foreach (KeyValuePair<UUID, RegionCache> kvp in m_LocalCache) { caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", kvp.Value.RegionName, kvp.Key); List<GridRegion> regions = kvp.Value.GetNeighbours(); foreach (GridRegion r in regions) caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY)); } } MainConsole.Instance.Output(caps.ToString()); } } }
// This file was generated by CSLA Object Generator - CslaGenFork v4.5 // // Filename: Doc // ObjectType: Doc // CSLAType: EditableRoot using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using DocStore.Business.Util; using Csla.Rules; using Csla.Rules.CommonRules; using CslaGenFork.Rules.AuthorizationRules; using CslaGenFork.Rules.DateRules; using CslaGenFork.Rules.TransformationRules; using DocStore.Business.Circulations; using DocStore.Business.Security; using System.Collections.Generic; namespace DocStore.Business { /// <summary> /// Doc (editable root object).<br/> /// This is a generated <see cref="Doc"/> business object. /// </summary> /// <remarks> /// This class contains three child collections:<br/> /// - <see cref="Folders"/> of type <see cref="DocFolderColl"/> (M:M relation to <see cref="Folder"/>)<br/> /// - <see cref="Circulations"/> of type <see cref="DocCircColl"/> (1:M relation to <see cref="DocCirc"/>)<br/> /// - <see cref="Contents"/> of type <see cref="DocContentList"/> (1:M relation to <see cref="DocContentInfo"/>) /// </remarks> [Serializable] public partial class Doc : BusinessBase<Doc> { #region Static Fields private static int _lastId; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="DocID"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> DocIDProperty = RegisterProperty<int>(p => p.DocID, "Doc ID"); /// <summary> /// Gets or sets the Document ID. /// </summary> /// <value>The Doc ID.</value> public int DocID { get { return GetProperty(DocIDProperty); } } /// <summary> /// Maintains metadata about <see cref="DocClassID"/> property. /// </summary> public static readonly PropertyInfo<int> DocClassIDProperty = RegisterProperty<int>(p => p.DocClassID, "Doc Class ID"); /// <summary> /// Gets or sets the Document Class ID. /// </summary> /// <value>The Doc Class ID.</value> public int DocClassID { get { return GetProperty(DocClassIDProperty); } set { SetProperty(DocClassIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="DocTypeID"/> property. /// </summary> public static readonly PropertyInfo<int> DocTypeIDProperty = RegisterProperty<int>(p => p.DocTypeID, "Doc Type ID"); /// <summary> /// Gets or sets the Document Type ID. /// </summary> /// <value>The Doc Type ID.</value> public int DocTypeID { get { return GetProperty(DocTypeIDProperty); } set { SetProperty(DocTypeIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="SenderID"/> property. /// </summary> public static readonly PropertyInfo<int> SenderIDProperty = RegisterProperty<int>(p => p.SenderID, "Sender ID"); /// <summary> /// Gets or sets the Entity ID of the document sender. /// </summary> /// <value>The Sender ID.</value> public int SenderID { get { return GetProperty(SenderIDProperty); } set { SetProperty(SenderIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="RecipientID"/> property. /// </summary> public static readonly PropertyInfo<int> RecipientIDProperty = RegisterProperty<int>(p => p.RecipientID, "Recipient ID"); /// <summary> /// Gets or sets the Entity ID of the document recipient. /// </summary> /// <value>The Recipient ID.</value> public int RecipientID { get { return GetProperty(RecipientIDProperty); } set { SetProperty(RecipientIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="DocRef"/> property. /// </summary> public static readonly PropertyInfo<string> DocRefProperty = RegisterProperty<string>(p => p.DocRef, "Doc Ref"); /// <summary> /// Gets or sets the Doc Ref. /// </summary> /// <value>The Doc Ref.</value> public string DocRef { get { return GetProperty(DocRefProperty); } set { SetProperty(DocRefProperty, value); } } /// <summary> /// Maintains metadata about <see cref="DocDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> DocDateProperty = RegisterProperty<SmartDate>(p => p.DocDate, "Doc Date"); /// <summary> /// Gets or sets the Doc Date. /// </summary> /// <value>The Doc Date.</value> [DateNotInFutureAttr("Please pay attention: {0} can't be in the future.")] public string DocDate { get { return GetPropertyConvert<SmartDate, string>(DocDateProperty); } set { SetPropertyConvert<SmartDate, string>(DocDateProperty, value); } } /// <summary> /// Maintains metadata about <see cref="Subject"/> property. /// </summary> public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject, "Subject"); /// <summary> /// Gets or sets the Subject. /// </summary> /// <value>The Subject.</value> public string Subject { get { return GetProperty(SubjectProperty); } set { SetProperty(SubjectProperty, value); } } /// <summary> /// Maintains metadata about <see cref="DocStatusID"/> property. /// </summary> public static readonly PropertyInfo<int> DocStatusIDProperty = RegisterProperty<int>(p => p.DocStatusID, "Doc Status ID"); /// <summary> /// Gets or sets the Doc Status ID. /// </summary> /// <value>The Doc Status ID.</value> public int DocStatusID { get { return GetProperty(DocStatusIDProperty); } set { SetProperty(DocStatusIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="Secret"/> property. /// </summary> public static readonly PropertyInfo<string> SecretProperty = RegisterProperty<string>(p => p.Secret, "Secret"); /// <summary> /// Gets or sets the Secret. /// </summary> /// <value>The Secret.</value> public string Secret { get { return GetProperty(SecretProperty); } set { SetProperty(SecretProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CreateDate"/> property. /// </summary> public static readonly PropertyInfo<DateTime> CreateDateProperty = RegisterProperty<DateTime>(p => p.CreateDate, "Create Date"); /// <summary> /// Gets or sets the Create Date. /// </summary> /// <value>The Create Date.</value> public DateTime CreateDate { get { return GetProperty(CreateDateProperty); } private set { SetProperty(CreateDateProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CreateUserID"/> property. /// </summary> public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID"); /// <summary> /// Gets or sets the Create User ID. /// </summary> /// <value>The Create User ID.</value> public int CreateUserID { get { return GetProperty(CreateUserIDProperty); } private set { SetProperty(CreateUserIDProperty, value); OnPropertyChanged("CreateUserName"); } } /// <summary> /// Maintains metadata about <see cref="ChangeDate"/> property. /// </summary> public static readonly PropertyInfo<DateTime> ChangeDateProperty = RegisterProperty<DateTime>(p => p.ChangeDate, "Change Date"); /// <summary> /// Gets or sets the Change Date. /// </summary> /// <value>The Change Date.</value> public DateTime ChangeDate { get { return GetProperty(ChangeDateProperty); } private set { SetProperty(ChangeDateProperty, value); } } /// <summary> /// Maintains metadata about <see cref="ChangeUserID"/> property. /// </summary> public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID"); /// <summary> /// Gets or sets the Change User ID. /// </summary> /// <value>The Change User ID.</value> public int ChangeUserID { get { return GetProperty(ChangeUserIDProperty); } private set { SetProperty(ChangeUserIDProperty, value); OnPropertyChanged("ChangeUserName"); } } /// <summary> /// Maintains metadata about <see cref="RowVersion"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version"); /// <summary> /// Gets the Row Version. /// </summary> /// <value>The Row Version.</value> public byte[] RowVersion { get { return GetProperty(RowVersionProperty); } } /// <summary> /// Gets the Create User Name. /// </summary> /// <value>The Create User Name.</value> public string CreateUserName { get { var result = string.Empty; if (Admin.UserNVL.GetUserNVL().ContainsKey(CreateUserID)) result = Admin.UserNVL.GetUserNVL().GetItemByKey(CreateUserID).Value; return result; } } /// <summary> /// Gets the Change User Name. /// </summary> /// <value>The Change User Name.</value> public string ChangeUserName { get { var result = string.Empty; if (Admin.UserNVL.GetUserNVL().ContainsKey(ChangeUserID)) result = Admin.UserNVL.GetUserNVL().GetItemByKey(ChangeUserID).Value; return result; } } /// <summary> /// Maintains metadata about child <see cref="ViewContent"/> property. /// </summary> public static readonly PropertyInfo<DocContentRO> ViewContentProperty = RegisterProperty<DocContentRO>(p => p.ViewContent, "View Content", RelationshipTypes.Child); /// <summary> /// Gets the View Content ("parent load" child property). /// </summary> /// <value>The View Content.</value> public DocContentRO ViewContent { get { return GetProperty(ViewContentProperty); } private set { LoadProperty(ViewContentProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="EditContent"/> property. /// </summary> public static readonly PropertyInfo<DocContent> EditContentProperty = RegisterProperty<DocContent>(p => p.EditContent, "Edit Content", RelationshipTypes.Child); /// <summary> /// Gets the Edit Content ("parent load" child property). /// </summary> /// <value>The Edit Content.</value> public DocContent EditContent { get { return GetProperty(EditContentProperty); } set { SetProperty(EditContentProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="Folders"/> property. /// </summary> public static readonly PropertyInfo<DocFolderColl> FoldersProperty = RegisterProperty<DocFolderColl>(p => p.Folders, "Folders", RelationshipTypes.Child); /// <summary> /// Gets the Folders ("parent load" child property). /// </summary> /// <value>The Folders.</value> public DocFolderColl Folders { get { return GetProperty(FoldersProperty); } private set { LoadProperty(FoldersProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="Circulations"/> property. /// </summary> public static readonly PropertyInfo<DocCircColl> CirculationsProperty = RegisterProperty<DocCircColl>(p => p.Circulations, "Circulations", RelationshipTypes.Child); /// <summary> /// Gets the Circulations ("parent load" child property). /// </summary> /// <value>The Circulations.</value> public DocCircColl Circulations { get { return GetProperty(CirculationsProperty); } private set { LoadProperty(CirculationsProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="Contents"/> property. /// </summary> public static readonly PropertyInfo<DocContentList> ContentsProperty = RegisterProperty<DocContentList>(p => p.Contents, "Contents", RelationshipTypes.Child); /// <summary> /// Gets the Contents ("parent load" child property). /// </summary> /// <value>The Contents.</value> public DocContentList Contents { get { return GetProperty(ContentsProperty); } private set { LoadProperty(ContentsProperty, value); } } #endregion #region BusinessBase<T> overrides /// <summary> /// Returns a string that represents the current <see cref="Doc"/> /// </summary> /// <returns>A <see cref="System.String"/> that represents this instance.</returns> public override string ToString() { // Return the Primary Key as a string return DocID.ToString() + ", " + DocRef.ToString(); } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="Doc"/> object. /// </summary> /// <returns>A reference to the created <see cref="Doc"/> object.</returns> public static Doc NewDoc() { return DataPortal.Create<Doc>(); } /// <summary> /// Factory method. Loads a <see cref="Doc"/> object, based on given parameters. /// </summary> /// <param name="docID">The DocID parameter of the Doc to fetch.</param> /// <returns>A reference to the fetched <see cref="Doc"/> object.</returns> public static Doc GetDoc(int docID) { return DataPortal.Fetch<Doc>(docID); } /// <summary> /// Factory method. Asynchronously creates a new <see cref="Doc"/> object. /// </summary> /// <param name="callback">The completion callback method.</param> public static void NewDoc(EventHandler<DataPortalResult<Doc>> callback) { DocEditGetter.NewDocEditGetter((o, e) => { callback(o, new DataPortalResult<Doc>(e.Object.Doc, e.Error, null)); }); } /// <summary> /// Factory method. Asynchronously loads a <see cref="Doc"/> object, based on given parameters. /// </summary> /// <param name="docID">The DocID parameter of the Doc to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetDoc(int docID, EventHandler<DataPortalResult<Doc>> callback) { DocEditGetter.GetDocEditGetter(docID, (o, e) => { callback(o, new DataPortalResult<Doc>(e.Object.Doc, e.Error, null)); }); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="Doc"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public Doc() { // Use factory methods and do not use direct creation. Saved += OnDocSaved; } #endregion #region Object Authorization /// <summary> /// Adds the object authorization rules. /// </summary> protected static void AddObjectAuthorizationRules() { BusinessRules.AddRule(typeof (Doc), new IsInRole(AuthorizationActions.CreateObject, "Author")); BusinessRules.AddRule(typeof (Doc), new IsInRole(AuthorizationActions.GetObject, "User")); BusinessRules.AddRule(typeof (Doc), new IsInRole(AuthorizationActions.EditObject, "Author")); AddObjectAuthorizationRulesExtend(); } /// <summary> /// Allows the set up of custom object authorization rules. /// </summary> static partial void AddObjectAuthorizationRulesExtend(); /// <summary> /// Checks if the current user can create a new Doc object. /// </summary> /// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns> public static bool CanAddObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(Doc)); } /// <summary> /// Checks if the current user can retrieve Doc's properties. /// </summary> /// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns> public static bool CanGetObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(Doc)); } /// <summary> /// Checks if the current user can change Doc's properties. /// </summary> /// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns> public static bool CanEditObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(Doc)); } /// <summary> /// Checks if the current user can delete a Doc object. /// </summary> /// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns> public static bool CanDeleteObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(Doc)); } #endregion #region Business Rules and Property Authorization /// <summary> /// Override this method in your business class to be notified when you need to set up shared business rules. /// </summary> /// <remarks> /// This method is automatically called by CSLA.NET when your object should associate /// per-type validation rules with its properties. /// </remarks> protected override void AddBusinessRules() { base.AddBusinessRules(); // Property Business Rules // DocClassID BusinessRules.AddRule(new Required(DocClassIDProperty)); // DocTypeID BusinessRules.AddRule(new Required(DocTypeIDProperty)); // SenderID BusinessRules.AddRule(new Required(SenderIDProperty)); // RecipientID BusinessRules.AddRule(new Required(RecipientIDProperty)); // DocRef BusinessRules.AddRule(new CollapseWhiteSpace(DocRefProperty) { Priority = -1 }); BusinessRules.AddRule(new MaxLength(DocRefProperty, 35)); // DocDate BusinessRules.AddRule(new Required(DocDateProperty)); // Subject BusinessRules.AddRule(new CollapseWhiteSpace(SubjectProperty) { Priority = -1 }); BusinessRules.AddRule(new Required(SubjectProperty)); BusinessRules.AddRule(new MaxLength(SubjectProperty, 255)); // DocStatusID BusinessRules.AddRule(new Required(DocStatusIDProperty)); // Authorization Rules // DocClassID BusinessRules.AddRule(new RestrictByStatusOrIsInRole(AuthorizationActions.WriteProperty, DocClassIDProperty, "DocStatusID", new List<int> {4}, "Admin")); // DocTypeID BusinessRules.AddRule(new IsNewOrIsInRole(AuthorizationActions.WriteProperty, DocTypeIDProperty, "Admin")); // SenderID BusinessRules.AddRule(new IsNewOrIsInRole(AuthorizationActions.WriteProperty, SenderIDProperty, "Admin")); // RecipientID BusinessRules.AddRule(new IsNewOrIsInRole(AuthorizationActions.WriteProperty, RecipientIDProperty, "Admin")); // DocRef BusinessRules.AddRule(new IsEmptyOrIsInRole(AuthorizationActions.WriteProperty, DocRefProperty, "Admin")); // DocDate BusinessRules.AddRule(new IsNewOrIsInRole(AuthorizationActions.WriteProperty, DocDateProperty, "Admin")); // Subject BusinessRules.AddRule(new RestrictByStatusOrIsInRole(AuthorizationActions.WriteProperty, SubjectProperty, "DocStatusID", new List<int> {3, 4}, "Admin")); // DocStatusID BusinessRules.AddRule(new RestrictByStatusOrIsInRole(AuthorizationActions.WriteProperty, DocStatusIDProperty, "DocStatusID", new List<int> {4}, "Admin")); // Secret BusinessRules.AddRule(new IsOwnerOrIsInRole(AuthorizationActions.ReadProperty, SecretProperty, "CreateUserID", () => UserInformation.UserId, "Admin", "Manager")); BusinessRules.AddRule(new IsOwner(AuthorizationActions.WriteProperty, SecretProperty, "CreateUserID", () => UserInformation.UserId)); AddBusinessRulesExtend(); } /// <summary> /// Allows the set up of custom shared business rules. /// </summary> partial void AddBusinessRulesExtend(); #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="Doc"/> object properties. /// </summary> [RunLocal] protected override void DataPortal_Create() { LoadProperty(DocIDProperty, System.Threading.Interlocked.Decrement(ref _lastId)); LoadProperty(DocClassIDProperty, -1); LoadProperty(DocTypeIDProperty, -1); LoadProperty(SenderIDProperty, -1); LoadProperty(DocRefProperty, null); LoadProperty(DocDateProperty, new SmartDate(DateTime.Today)); LoadProperty(DocStatusIDProperty, -1); LoadProperty(SecretProperty, null); LoadProperty(CreateDateProperty, DateTime.Now); LoadProperty(CreateUserIDProperty, UserInformation.UserId); LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty)); LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty)); LoadProperty(EditContentProperty, DataPortal.CreateChild<DocContent>()); LoadProperty(FoldersProperty, DataPortal.CreateChild<DocFolderColl>()); LoadProperty(CirculationsProperty, DataPortal.CreateChild<DocCircColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="Doc"/> object from the database, based on given criteria. /// </summary> /// <param name="docID">The Doc ID.</param> protected void DataPortal_Fetch(int docID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("GetDoc", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocID", docID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, docID); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); FetchChildren(dr); } } } /// <summary> /// Loads a <see cref="Doc"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(DocIDProperty, dr.GetInt32("DocID")); LoadProperty(DocClassIDProperty, dr.GetInt32("DocClassID")); LoadProperty(DocTypeIDProperty, dr.GetInt32("DocTypeID")); LoadProperty(SenderIDProperty, dr.GetInt32("SenderID")); LoadProperty(RecipientIDProperty, dr.GetInt32("RecipientID")); LoadProperty(DocRefProperty, dr.IsDBNull("DocRef") ? null : dr.GetString("DocRef")); LoadProperty(DocDateProperty, dr.GetSmartDate("DocDate", true)); LoadProperty(SubjectProperty, dr.GetString("Subject")); LoadProperty(DocStatusIDProperty, dr.GetInt32("DocStatusID")); LoadProperty(SecretProperty, dr.IsDBNull("Secret") ? null : dr.GetString("Secret")); LoadProperty(CreateDateProperty, dr.GetDateTime("CreateDate")); LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID")); LoadProperty(ChangeDateProperty, dr.GetDateTime("ChangeDate")); LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID")); LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void FetchChildren(SafeDataReader dr) { dr.NextResult(); if (dr.Read()) LoadProperty(ViewContentProperty, DocContentRO.GetDocContentRO(dr)); dr.NextResult(); if (dr.Read()) LoadProperty(EditContentProperty, DocContent.GetDocContent(dr)); dr.NextResult(); LoadProperty(FoldersProperty, DocFolderColl.GetDocFolderColl(dr)); dr.NextResult(); LoadProperty(CirculationsProperty, DocCircColl.GetDocCircColl(dr)); dr.NextResult(); LoadProperty(ContentsProperty, DocContentList.GetDocContentList(dr)); } /// <summary> /// Inserts a new <see cref="Doc"/> object in the database. /// </summary> protected override void DataPortal_Insert() { SimpleAuditTrail(); using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("AddDoc", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocID", ReadProperty(DocIDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@DocClassID", ReadProperty(DocClassIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SenderID", ReadProperty(SenderIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RecipientID", ReadProperty(RecipientIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@DocRef", ReadProperty(DocRefProperty) == null ? (object)DBNull.Value : ReadProperty(DocRefProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@DocDate", ReadProperty(DocDateProperty).DBValue).DbType = DbType.Date; cmd.Parameters.AddWithValue("@Subject", ReadProperty(SubjectProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@DocStatusID", ReadProperty(DocStatusIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Secret", ReadProperty(SecretProperty) == null ? (object)DBNull.Value : ReadProperty(SecretProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty)).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty)).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(DocIDProperty, (int) cmd.Parameters["@DocID"].Value); LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); ctx.Commit(); } } /// <summary> /// Updates in the database all changes made to the <see cref="Doc"/> object. /// </summary> protected override void DataPortal_Update() { SimpleAuditTrail(); using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("UpdateDoc", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocID", ReadProperty(DocIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@DocClassID", ReadProperty(DocClassIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SenderID", ReadProperty(SenderIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RecipientID", ReadProperty(RecipientIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@DocRef", ReadProperty(DocRefProperty) == null ? (object)DBNull.Value : ReadProperty(DocRefProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@DocDate", ReadProperty(DocDateProperty).DBValue).DbType = DbType.Date; cmd.Parameters.AddWithValue("@Subject", ReadProperty(SubjectProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@DocStatusID", ReadProperty(DocStatusIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Secret", ReadProperty(SecretProperty) == null ? (object)DBNull.Value : ReadProperty(SecretProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty)).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); ctx.Commit(); } } private void SimpleAuditTrail() { LoadProperty(ChangeDateProperty, DateTime.Now); LoadProperty(ChangeUserIDProperty, UserInformation.UserId); OnPropertyChanged("ChangeUserName"); if (IsNew) { LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty)); LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty)); OnPropertyChanged("CreateUserName"); } } #endregion #region Saved Event private void OnDocSaved(object sender, Csla.Core.SavedEventArgs e) { if (DocSaved != null) DocSaved(sender, e); } /// <summary> Use this event to signal a <see cref="Doc"/> object was saved.</summary> public static event EventHandler<Csla.Core.SavedEventArgs> DocSaved; #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; namespace Org.BouncyCastle.Crypto.Signers { /// <summary> RSA-PSS as described in Pkcs# 1 v 2.1. /// <p> /// Note: the usual value for the salt length is the number of /// bytes in the hash function.</p> /// </summary> public class PssSigner : ISigner { public const byte TrailerImplicit = (byte)0xBC; private readonly IDigest contentDigest1, contentDigest2; private readonly IDigest mgfDigest; private readonly IAsymmetricBlockCipher cipher; private SecureRandom random; private int hLen; private int mgfhLen; private int sLen; private int emBits; private byte[] salt; private byte[] mDash; private byte[] block; private byte trailer; public static PssSigner CreateRawSigner( IAsymmetricBlockCipher cipher, IDigest digest) { return new PssSigner(cipher, new NullDigest(), digest, digest, digest.GetDigestSize(), TrailerImplicit); } public static PssSigner CreateRawSigner( IAsymmetricBlockCipher cipher, IDigest contentDigest, IDigest mgfDigest, int saltLen, byte trailer) { return new PssSigner(cipher, new NullDigest(), contentDigest, mgfDigest, saltLen, trailer); } public PssSigner( IAsymmetricBlockCipher cipher, IDigest digest) : this(cipher, digest, digest.GetDigestSize()) { } /// <summary>Basic constructor</summary> /// <param name="cipher">the asymmetric cipher to use.</param> /// <param name="digest">the digest to use.</param> /// <param name="saltLen">the length of the salt to use (in bytes).</param> public PssSigner( IAsymmetricBlockCipher cipher, IDigest digest, int saltLen) : this(cipher, digest, saltLen, TrailerImplicit) { } public PssSigner( IAsymmetricBlockCipher cipher, IDigest contentDigest, IDigest mgfDigest, int saltLen) : this(cipher, contentDigest, mgfDigest, saltLen, TrailerImplicit) { } public PssSigner( IAsymmetricBlockCipher cipher, IDigest digest, int saltLen, byte trailer) : this(cipher, digest, digest, saltLen, TrailerImplicit) { } public PssSigner( IAsymmetricBlockCipher cipher, IDigest contentDigest, IDigest mgfDigest, int saltLen, byte trailer) : this(cipher, contentDigest, contentDigest, mgfDigest, saltLen, trailer) { } private PssSigner( IAsymmetricBlockCipher cipher, IDigest contentDigest1, IDigest contentDigest2, IDigest mgfDigest, int saltLen, byte trailer) { this.cipher = cipher; this.contentDigest1 = contentDigest1; this.contentDigest2 = contentDigest2; this.mgfDigest = mgfDigest; this.hLen = contentDigest2.GetDigestSize(); this.mgfhLen = mgfDigest.GetDigestSize(); this.sLen = saltLen; this.salt = new byte[saltLen]; this.mDash = new byte[8 + saltLen + hLen]; this.trailer = trailer; } public virtual string AlgorithmName { get { return mgfDigest.AlgorithmName + "withRSAandMGF1"; } } public virtual void Init( bool forSigning, ICipherParameters parameters) { if (parameters is ParametersWithRandom) { ParametersWithRandom p = (ParametersWithRandom) parameters; parameters = p.Parameters; random = p.Random; } else { if (forSigning) { random = new SecureRandom(); } } cipher.Init(forSigning, parameters); RsaKeyParameters kParam; if (parameters is RsaBlindingParameters) { kParam = ((RsaBlindingParameters) parameters).PublicKey; } else { kParam = (RsaKeyParameters) parameters; } emBits = kParam.Modulus.BitLength - 1; if (emBits < (8 * hLen + 8 * sLen + 9)) throw new ArgumentException("key too small for specified hash and salt lengths"); block = new byte[(emBits + 7) / 8]; } /// <summary> clear possible sensitive data</summary> private void ClearBlock( byte[] block) { Array.Clear(block, 0, block.Length); } /// <summary> update the internal digest with the byte b</summary> public virtual void Update( byte input) { contentDigest1.Update(input); } /// <summary> update the internal digest with the byte array in</summary> public virtual void BlockUpdate( byte[] input, int inOff, int length) { contentDigest1.BlockUpdate(input, inOff, length); } /// <summary> reset the internal state</summary> public virtual void Reset() { contentDigest1.Reset(); } /// <summary> Generate a signature for the message we've been loaded with using /// the key we were initialised with. /// </summary> public virtual byte[] GenerateSignature() { contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen); if (sLen != 0) { random.NextBytes(salt); salt.CopyTo(mDash, mDash.Length - sLen); } byte[] h = new byte[hLen]; contentDigest2.BlockUpdate(mDash, 0, mDash.Length); contentDigest2.DoFinal(h, 0); block[block.Length - sLen - 1 - hLen - 1] = (byte) (0x01); salt.CopyTo(block, block.Length - sLen - hLen - 1); byte[] dbMask = MaskGeneratorFunction1(h, 0, h.Length, block.Length - hLen - 1); for (int i = 0; i != dbMask.Length; i++) { block[i] ^= dbMask[i]; } block[0] &= (byte) ((0xff >> ((block.Length * 8) - emBits))); h.CopyTo(block, block.Length - hLen - 1); block[block.Length - 1] = trailer; byte[] b = cipher.ProcessBlock(block, 0, block.Length); ClearBlock(block); return b; } /// <summary> return true if the internal state represents the signature described /// in the passed in array. /// </summary> public virtual bool VerifySignature( byte[] signature) { contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen); byte[] b = cipher.ProcessBlock(signature, 0, signature.Length); b.CopyTo(block, block.Length - b.Length); if (block[block.Length - 1] != trailer) { ClearBlock(block); return false; } byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - 1, hLen, block.Length - hLen - 1); for (int i = 0; i != dbMask.Length; i++) { block[i] ^= dbMask[i]; } block[0] &= (byte) ((0xff >> ((block.Length * 8) - emBits))); for (int i = 0; i != block.Length - hLen - sLen - 2; i++) { if (block[i] != 0) { ClearBlock(block); return false; } } if (block[block.Length - hLen - sLen - 2] != 0x01) { ClearBlock(block); return false; } Array.Copy(block, block.Length - sLen - hLen - 1, mDash, mDash.Length - sLen, sLen); contentDigest2.BlockUpdate(mDash, 0, mDash.Length); contentDigest2.DoFinal(mDash, mDash.Length - hLen); for (int i = block.Length - hLen - 1, j = mDash.Length - hLen; j != mDash.Length; i++, j++) { if ((block[i] ^ mDash[j]) != 0) { ClearBlock(mDash); ClearBlock(block); return false; } } ClearBlock(mDash); ClearBlock(block); return true; } /// <summary> int to octet string.</summary> private void ItoOSP( int i, byte[] sp) { sp[0] = (byte)((uint) i >> 24); sp[1] = (byte)((uint) i >> 16); sp[2] = (byte)((uint) i >> 8); sp[3] = (byte)((uint) i >> 0); } /// <summary> mask generator function, as described in Pkcs1v2.</summary> private byte[] MaskGeneratorFunction1( byte[] Z, int zOff, int zLen, int length) { byte[] mask = new byte[length]; byte[] hashBuf = new byte[mgfhLen]; byte[] C = new byte[4]; int counter = 0; mgfDigest.Reset(); while (counter < (length / mgfhLen)) { ItoOSP(counter, C); mgfDigest.BlockUpdate(Z, zOff, zLen); mgfDigest.BlockUpdate(C, 0, C.Length); mgfDigest.DoFinal(hashBuf, 0); hashBuf.CopyTo(mask, counter * mgfhLen); ++counter; } if ((counter * mgfhLen) < length) { ItoOSP(counter, C); mgfDigest.BlockUpdate(Z, zOff, zLen); mgfDigest.BlockUpdate(C, 0, C.Length); mgfDigest.DoFinal(hashBuf, 0); Array.Copy(hashBuf, 0, mask, counter * mgfhLen, mask.Length - (counter * mgfhLen)); } return mask; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; namespace System.Collections { // A vector of bits. Use this to store bits efficiently, without having to do bit // shifting yourself. [System.Runtime.InteropServices.ComVisible(true)] public sealed class BitArray : ICollection { private BitArray() { } /*========================================================================= ** Allocates space to hold length bit values. All of the values in the bit ** array are set to false. ** ** Exceptions: ArgumentException if length < 0. =========================================================================*/ public BitArray(int length) : this(length, false) { } /*========================================================================= ** Allocates space to hold length bit values. All of the values in the bit ** array are set to defaultValue. ** ** Exceptions: ArgumentOutOfRangeException if length < 0. =========================================================================*/ public BitArray(int length, bool defaultValue) { if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), length, SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); m_array = new int[GetArrayLength(length, BitsPerInt32)]; m_length = length; int fillValue = defaultValue ? unchecked(((int)0xffffffff)) : 0; for (int i = 0; i < m_array.Length; i++) { m_array[i] = fillValue; } _version = 0; } /*========================================================================= ** Allocates space to hold the bit values in bytes. bytes[0] represents ** bits 0 - 7, bytes[1] represents bits 8 - 15, etc. The LSB of each byte ** represents the lowest index value; bytes[0] & 1 represents bit 0, ** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc. ** ** Exceptions: ArgumentException if bytes == null. =========================================================================*/ public BitArray(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } Contract.EndContractBlock(); // this value is chosen to prevent overflow when computing m_length. // m_length is of type int32 and is exposed as a property, so // type of m_length can't be changed to accommodate. if (bytes.Length > Int32.MaxValue / BitsPerByte) { throw new ArgumentException(SR.Format(SR.Argument_ArrayTooLarge, BitsPerByte), nameof(bytes)); } m_array = new int[GetArrayLength(bytes.Length, BytesPerInt32)]; m_length = bytes.Length * BitsPerByte; int i = 0; int j = 0; while (bytes.Length - j >= 4) { m_array[i++] = (bytes[j] & 0xff) | ((bytes[j + 1] & 0xff) << 8) | ((bytes[j + 2] & 0xff) << 16) | ((bytes[j + 3] & 0xff) << 24); j += 4; } Contract.Assert(bytes.Length - j >= 0, "BitArray byteLength problem"); Contract.Assert(bytes.Length - j < 4, "BitArray byteLength problem #2"); switch (bytes.Length - j) { case 3: m_array[i] = ((bytes[j + 2] & 0xff) << 16); goto case 2; // fall through case 2: m_array[i] |= ((bytes[j + 1] & 0xff) << 8); goto case 1; // fall through case 1: m_array[i] |= (bytes[j] & 0xff); break; } _version = 0; } public BitArray(bool[] values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } Contract.EndContractBlock(); m_array = new int[GetArrayLength(values.Length, BitsPerInt32)]; m_length = values.Length; for (int i = 0; i < values.Length; i++) { if (values[i]) m_array[i / 32] |= (1 << (i % 32)); } _version = 0; } /*========================================================================= ** Allocates space to hold the bit values in values. values[0] represents ** bits 0 - 31, values[1] represents bits 32 - 63, etc. The LSB of each ** integer represents the lowest index value; values[0] & 1 represents bit ** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc. ** ** Exceptions: ArgumentException if values == null. =========================================================================*/ public BitArray(int[] values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } Contract.EndContractBlock(); // this value is chosen to prevent overflow when computing m_length if (values.Length > Int32.MaxValue / BitsPerInt32) { throw new ArgumentException(SR.Format(SR.Argument_ArrayTooLarge, BitsPerInt32), nameof(values)); } m_array = new int[values.Length]; Array.Copy(values, 0, m_array, 0, values.Length); m_length = values.Length * BitsPerInt32; _version = 0; } /*========================================================================= ** Allocates a new BitArray with the same length and bit values as bits. ** ** Exceptions: ArgumentException if bits == null. =========================================================================*/ public BitArray(BitArray bits) { if (bits == null) { throw new ArgumentNullException(nameof(bits)); } Contract.EndContractBlock(); int arrayLength = GetArrayLength(bits.m_length, BitsPerInt32); m_array = new int[arrayLength]; Array.Copy(bits.m_array, 0, m_array, 0, arrayLength); m_length = bits.m_length; _version = bits._version; } public bool this[int index] { get { return Get(index); } set { Set(index, value); } } /*========================================================================= ** Returns the bit value at position index. ** ** Exceptions: ArgumentOutOfRangeException if index < 0 or ** index >= GetLength(). =========================================================================*/ public bool Get(int index) { if (index < 0 || index >= Length) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); return (m_array[index / 32] & (1 << (index % 32))) != 0; } /*========================================================================= ** Sets the bit value at position index to value. ** ** Exceptions: ArgumentOutOfRangeException if index < 0 or ** index >= GetLength(). =========================================================================*/ public void Set(int index, bool value) { if (index < 0 || index >= Length) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); if (value) { m_array[index / 32] |= (1 << (index % 32)); } else { m_array[index / 32] &= ~(1 << (index % 32)); } _version++; } /*========================================================================= ** Sets all the bit values to value. =========================================================================*/ public void SetAll(bool value) { int fillValue = value ? unchecked(((int)0xffffffff)) : 0; int ints = GetArrayLength(m_length, BitsPerInt32); for (int i = 0; i < ints; i++) { m_array[i] = fillValue; } _version++; } /*========================================================================= ** Returns a reference to the current instance ANDed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public BitArray And(BitArray value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (Length != value.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer); Contract.EndContractBlock(); int ints = GetArrayLength(m_length, BitsPerInt32); for (int i = 0; i < ints; i++) { m_array[i] &= value.m_array[i]; } _version++; return this; } /*========================================================================= ** Returns a reference to the current instance ORed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public BitArray Or(BitArray value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (Length != value.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer); Contract.EndContractBlock(); int ints = GetArrayLength(m_length, BitsPerInt32); for (int i = 0; i < ints; i++) { m_array[i] |= value.m_array[i]; } _version++; return this; } /*========================================================================= ** Returns a reference to the current instance XORed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public BitArray Xor(BitArray value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (Length != value.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer); Contract.EndContractBlock(); int ints = GetArrayLength(m_length, BitsPerInt32); for (int i = 0; i < ints; i++) { m_array[i] ^= value.m_array[i]; } _version++; return this; } /*========================================================================= ** Inverts all the bit values. On/true bit values are converted to ** off/false. Off/false bit values are turned on/true. The current instance ** is updated and returned. =========================================================================*/ public BitArray Not() { int ints = GetArrayLength(m_length, BitsPerInt32); for (int i = 0; i < ints; i++) { m_array[i] = ~m_array[i]; } _version++; return this; } public int Length { get { Contract.Ensures(Contract.Result<int>() >= 0); return m_length; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); int newints = GetArrayLength(value, BitsPerInt32); if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length) { // grow or shrink (if wasting more than _ShrinkThreshold ints) Array.Resize(ref m_array, newints); } if (value > m_length) { // clear high bit values in the last int int last = GetArrayLength(m_length, BitsPerInt32) - 1; int bits = m_length % 32; if (bits > 0) { m_array[last] &= (1 << bits) - 1; } // clear remaining int values Array.Clear(m_array, last + 1, newints - last - 1); } m_length = value; _version++; } } // ICollection implementation void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); Contract.EndContractBlock(); if (array is int[]) { Array.Copy(m_array, 0, array, index, GetArrayLength(m_length, BitsPerInt32)); } else if (array is byte[]) { int arrayLength = GetArrayLength(m_length, BitsPerByte); if ((array.Length - index) < arrayLength) throw new ArgumentException(SR.Argument_InvalidOffLen); byte[] b = (byte[])array; for (int i = 0; i < arrayLength; i++) b[index + i] = (byte)((m_array[i / 4] >> ((i % 4) * 8)) & 0x000000FF); // Shift to bring the required byte to LSB, then mask } else if (array is bool[]) { if (array.Length - index < m_length) throw new ArgumentException(SR.Argument_InvalidOffLen); bool[] b = (bool[])array; for (int i = 0; i < m_length; i++) b[index + i] = ((m_array[i / 32] >> (i % 32)) & 0x00000001) != 0; } else throw new ArgumentException(SR.Arg_BitArrayTypeUnsupported, nameof(array)); } int ICollection.Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return m_length; } } Object ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } bool ICollection.IsSynchronized { get { return false; } } public IEnumerator GetEnumerator() { return new BitArrayEnumeratorSimple(this); } // XPerY=n means that n Xs can be stored in 1 Y. private const int BitsPerInt32 = 32; private const int BytesPerInt32 = 4; private const int BitsPerByte = 8; /// <summary> /// Used for conversion between different representations of bit array. /// Returns (n+(div-1))/div, rearranged to avoid arithmetic overflow. /// For example, in the bit to int case, the straightforward calc would /// be (n+31)/32, but that would cause overflow. So instead it's /// rearranged to ((n-1)/32) + 1, with special casing for 0. /// /// Usage: /// GetArrayLength(77, BitsPerInt32): returns how many ints must be /// allocated to store 77 bits. /// </summary> /// <param name="n"></param> /// <param name="div">use a conversion constant, e.g. BytesPerInt32 to get /// how many ints are required to store n bytes</param> /// <returns></returns> private static int GetArrayLength(int n, int div) { Contract.Assert(div > 0, "GetArrayLength: div arg must be greater than 0"); return n > 0 ? (((n - 1) / div) + 1) : 0; } private class BitArrayEnumeratorSimple : IEnumerator { private BitArray bitarray; private int index; private int version; private bool currentElement; internal BitArrayEnumeratorSimple(BitArray bitarray) { this.bitarray = bitarray; this.index = -1; version = bitarray._version; } public Object Clone() { return MemberwiseClone(); } public virtual bool MoveNext() { ICollection bitarrayAsICollection = bitarray; if (version != bitarray._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (index < (bitarrayAsICollection.Count - 1)) { index++; currentElement = bitarray.Get(index); return true; } else index = bitarrayAsICollection.Count; return false; } public virtual Object Current { get { if (index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); if (index >= ((ICollection)bitarray).Count) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); return currentElement; } } public void Reset() { if (version != bitarray._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); index = -1; } } private int[] m_array; private int m_length; private int _version; private Object _syncRoot; private const int _ShrinkThreshold = 256; } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Diagnostics; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Threading; using Fluent.Extensions; using Fluent.Helpers; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents custom Fluent UI ComboBox /// </summary> [TemplatePart(Name = "PART_ToggleButton", Type = typeof(ToggleButton))] [TemplatePart(Name = "PART_MenuPanel", Type = typeof(Panel))] [TemplatePart(Name = "PART_SelectedImage", Type = typeof(Image))] [TemplatePart(Name = "PART_ContentSite", Type = typeof(ContentPresenter))] [TemplatePart(Name = "PART_ContentBorder", Type = typeof(Border))] [TemplatePart(Name = "PART_ScrollViewer", Type = typeof(ScrollViewer))] [DebuggerDisplay("class{GetType().FullName}: Header = {Header}, Items.Count = {Items.Count}, Size = {Size}, IsSimplified = {IsSimplified}")] public class ComboBox : System.Windows.Controls.ComboBox, IQuickAccessItemProvider, IRibbonControl, IDropDownControl, IMediumIconProvider, ISimplifiedRibbonControl { #region Fields private ToggleButton? dropDownButton; private IInputElement? focusedElement; private Border? contentBorder; private ContentPresenter? contentSite; // Freezed image (created during snapping) private Image? snappedImage; // Is visual currently snapped private bool isSnapped; private ScrollViewer? scrollViewer; #endregion #region Properties #region Size /// <inheritdoc /> public RibbonControlSize Size { get { return (RibbonControlSize)this.GetValue(SizeProperty); } set { this.SetValue(SizeProperty, value); } } /// <summary>Identifies the <see cref="Size"/> dependency property.</summary> public static readonly DependencyProperty SizeProperty = RibbonProperties.SizeProperty.AddOwner(typeof(ComboBox)); #endregion #region SizeDefinition /// <inheritdoc /> public RibbonControlSizeDefinition SizeDefinition { get { return (RibbonControlSizeDefinition)this.GetValue(SizeDefinitionProperty); } set { this.SetValue(SizeDefinitionProperty, value); } } /// <summary>Identifies the <see cref="SizeDefinition"/> dependency property.</summary> public static readonly DependencyProperty SizeDefinitionProperty = RibbonProperties.SizeDefinitionProperty.AddOwner(typeof(ComboBox)); #endregion #region SimplifiedSizeDefinition /// <inheritdoc /> public RibbonControlSizeDefinition SimplifiedSizeDefinition { get { return (RibbonControlSizeDefinition)this.GetValue(SimplifiedSizeDefinitionProperty); } set { this.SetValue(SimplifiedSizeDefinitionProperty, value); } } /// <summary>Identifies the <see cref="SimplifiedSizeDefinition"/> dependency property.</summary> public static readonly DependencyProperty SimplifiedSizeDefinitionProperty = RibbonProperties.SimplifiedSizeDefinitionProperty.AddOwner(typeof(ComboBox)); #endregion #region KeyTip /// <inheritdoc /> public string? KeyTip { get { return (string?)this.GetValue(KeyTipProperty); } set { this.SetValue(KeyTipProperty, value); } } /// <summary>Identifies the <see cref="KeyTip"/> dependency property.</summary> public static readonly DependencyProperty KeyTipProperty = Fluent.KeyTip.KeysProperty.AddOwner(typeof(ComboBox)); #endregion /// <inheritdoc /> public Popup? DropDownPopup { get; private set; } /// <inheritdoc /> public bool IsContextMenuOpened { get; set; } #region Header /// <inheritdoc /> public object? Header { get { return this.GetValue(HeaderProperty); } set { this.SetValue(HeaderProperty, value); } } /// <summary>Identifies the <see cref="Header"/> dependency property.</summary> public static readonly DependencyProperty HeaderProperty = RibbonControl.HeaderProperty.AddOwner(typeof(ComboBox), new PropertyMetadata(LogicalChildSupportHelper.OnLogicalChildPropertyChanged)); #endregion #region Icon /// <inheritdoc /> public object? Icon { get { return this.GetValue(IconProperty); } set { this.SetValue(IconProperty, value); } } /// <summary>Identifies the <see cref="Icon"/> dependency property.</summary> public static readonly DependencyProperty IconProperty = RibbonControl.IconProperty.AddOwner(typeof(ComboBox), new PropertyMetadata(LogicalChildSupportHelper.OnLogicalChildPropertyChanged)); #endregion #region MediumIcon /// <inheritdoc /> public object? MediumIcon { get { return this.GetValue(MediumIconProperty); } set { this.SetValue(MediumIconProperty, value); } } /// <summary>Identifies the <see cref="MediumIcon"/> dependency property.</summary> public static readonly DependencyProperty MediumIconProperty = MediumIconProviderProperties.MediumIconProperty.AddOwner(typeof(ComboBox), new PropertyMetadata(LogicalChildSupportHelper.OnLogicalChildPropertyChanged)); #endregion #region TopPopupContent /// <summary> /// Gets or sets content to show on the top side of the Popup. /// </summary> public object? TopPopupContent { get { return (object?)this.GetValue(TopPopupContentProperty); } set { this.SetValue(TopPopupContentProperty, value); } } /// <summary>Identifies the <see cref="TopPopupContent"/> dependency property.</summary> public static readonly DependencyProperty TopPopupContentProperty = DependencyProperty.Register(nameof(TopPopupContent), typeof(object), typeof(ComboBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure, LogicalChildSupportHelper.OnLogicalChildPropertyChanged)); /// <summary> /// Gets or sets top content template. /// </summary> public DataTemplate? TopPopupContentTemplate { get { return (DataTemplate?)this.GetValue(TopPopupContentTemplateProperty); } set { this.SetValue(TopPopupContentTemplateProperty, value); } } /// <summary>Identifies the <see cref="TopPopupContentTemplate"/> dependency property.</summary> public static readonly DependencyProperty TopPopupContentTemplateProperty = DependencyProperty.Register(nameof(TopPopupContentTemplate), typeof(DataTemplate), typeof(ComboBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// Gets or sets top content template selector. /// </summary> public DataTemplateSelector? TopPopupContentTemplateSelector { get { return (DataTemplateSelector?)this.GetValue(TopPopupContentTemplateSelectorProperty); } set { this.SetValue(TopPopupContentTemplateSelectorProperty, value); } } /// <summary>Identifies the <see cref="TopPopupContentTemplateSelector"/> dependency property.</summary> public static readonly DependencyProperty TopPopupContentTemplateSelectorProperty = DependencyProperty.Register(nameof(TopPopupContentTemplateSelector), typeof(DataTemplateSelector), typeof(ComboBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// Gets or sets top content template string format. /// </summary> public string? TopPopupContentStringFormat { get { return (string?)this.GetValue(TopPopupContentStringFormatProperty); } set { this.SetValue(TopPopupContentStringFormatProperty, value); } } /// <summary>Identifies the <see cref="TopPopupContentStringFormat"/> dependency property.</summary> public static readonly DependencyProperty TopPopupContentStringFormatProperty = DependencyProperty.Register(nameof(TopPopupContentStringFormat), typeof(string), typeof(ComboBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure)); #endregion #region Menu /// <summary> /// Gets or sets menu to show in combo box bottom /// </summary> public RibbonMenu? Menu { get { return (RibbonMenu?)this.GetValue(MenuProperty); } set { this.SetValue(MenuProperty, value); } } /// <summary>Identifies the <see cref="Menu"/> dependency property.</summary> public static readonly DependencyProperty MenuProperty = DependencyProperty.Register(nameof(Menu), typeof(RibbonMenu), typeof(ComboBox), new PropertyMetadata()); #endregion #region InputWidth /// <summary> /// Gets or sets width of the value input part of combobox /// </summary> public double InputWidth { get { return (double)this.GetValue(InputWidthProperty); } set { this.SetValue(InputWidthProperty, value); } } /// <summary>Identifies the <see cref="InputWidth"/> dependency property.</summary> public static readonly DependencyProperty InputWidthProperty = DependencyProperty.Register(nameof(InputWidth), typeof(double), typeof(ComboBox), new PropertyMetadata(DoubleBoxes.NaN)); #endregion #region ResizeMode /// <summary> /// Gets or sets context menu resize mode /// </summary> public ContextMenuResizeMode ResizeMode { get { return (ContextMenuResizeMode)this.GetValue(ResizeModeProperty); } set { this.SetValue(ResizeModeProperty, value); } } /// <summary>Identifies the <see cref="ResizeMode"/> dependency property.</summary> public static readonly DependencyProperty ResizeModeProperty = DependencyProperty.Register(nameof(ResizeMode), typeof(ContextMenuResizeMode), typeof(ComboBox), new PropertyMetadata(ContextMenuResizeMode.None)); #endregion #region Snapping /// <summary> /// Snaps / Unsnaps the Visual /// (remove visuals and substitute with freezed image) /// </summary> private bool IsSnapped { get { return this.isSnapped; } set { if (value == this.isSnapped) { return; } if (this.snappedImage is null || this.contentSite is null) { return; } if (value && ((int)this.contentSite.ActualWidth > 0) && ((int)this.contentSite.ActualHeight > 0)) { // Render the freezed image RenderOptions.SetBitmapScalingMode(this.snappedImage, BitmapScalingMode.NearestNeighbor); var renderTargetBitmap = new RenderTargetBitmap((int)this.contentSite.ActualWidth + (int)this.contentSite.Margin.Left + (int)this.contentSite.Margin.Right, (int)this.contentSite.ActualHeight + (int)this.contentSite.Margin.Top + (int)this.contentSite.Margin.Bottom, 96, 96, PixelFormats.Pbgra32); renderTargetBitmap.Render(this.contentSite); this.snappedImage.Source = renderTargetBitmap; this.snappedImage.FlowDirection = this.FlowDirection; /*snappedImage.Width = contentSite.ActualWidth; snappedImage.Height = contentSite.ActualHeight;*/ this.snappedImage.Visibility = Visibility.Visible; this.contentSite.Visibility = Visibility.Hidden; this.isSnapped = value; } else { this.snappedImage.Visibility = Visibility.Collapsed; this.contentSite.Visibility = Visibility.Visible; this.isSnapped = value; } this.InvalidateVisual(); } } #endregion #region DropDownHeight /// <summary> /// Gets or sets initial dropdown height /// </summary> public double DropDownHeight { get { return (double)this.GetValue(DropDownHeightProperty); } set { this.SetValue(DropDownHeightProperty, value); } } /// <summary>Identifies the <see cref="DropDownHeight"/> dependency property.</summary> public static readonly DependencyProperty DropDownHeightProperty = DependencyProperty.Register(nameof(DropDownHeight), typeof(double), typeof(ComboBox), new PropertyMetadata(DoubleBoxes.NaN)); #endregion #region IsSimplified /// <summary> /// Gets or sets whether or not the ribbon is in Simplified mode /// </summary> public bool IsSimplified { get { return (bool)this.GetValue(IsSimplifiedProperty); } private set { this.SetValue(IsSimplifiedPropertyKey, BooleanBoxes.Box(value)); } } private static readonly DependencyPropertyKey IsSimplifiedPropertyKey = DependencyProperty.RegisterReadOnly(nameof(IsSimplified), typeof(bool), typeof(ComboBox), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary>Identifies the <see cref="IsSimplified"/> dependency property.</summary> public static readonly DependencyProperty IsSimplifiedProperty = IsSimplifiedPropertyKey.DependencyProperty; #endregion #endregion Properties #region Constructors /// <summary> /// Static constructor /// </summary> static ComboBox() { var type = typeof(ComboBox); DefaultStyleKeyProperty.OverrideMetadata(type, new FrameworkPropertyMetadata(type)); SelectedItemProperty.OverrideMetadata(type, new FrameworkPropertyMetadata(OnSelectedItemChanged, CoerceSelectedItem)); ToolTipService.Attach(type); PopupService.Attach(type); ContextMenuService.Attach(type); } private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var combo = (ComboBox)d; if (combo.isQuickAccessOpened == false && combo.isQuickAccessFocused == false && combo.quickAccessCombo is not null) { combo.UpdateQuickAccessCombo(); } } private static object? CoerceSelectedItem(DependencyObject d, object? basevalue) { var combo = (ComboBox)d; if (combo.isQuickAccessOpened || combo.isQuickAccessFocused) { return combo.selectedItem; } return basevalue; } /// <summary> /// Default Constructor /// </summary> public ComboBox() { ContextMenuService.Coerce(this); } #endregion #region QuickAccess /// <inheritdoc /> public virtual FrameworkElement CreateQuickAccessItem() { var combo = new ComboBox(); RibbonControl.BindQuickAccessItem(this, combo); RibbonControl.Bind(this, combo, nameof(this.ActualWidth), MaxWidthProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.InputWidth), InputWidthProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.IsEditable), IsEditableProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.IsReadOnly), IsReadOnlyProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.ResizeMode), ResizeModeProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.Text), TextProperty, BindingMode.TwoWay); RibbonControl.Bind(this, combo, nameof(this.DisplayMemberPath), DisplayMemberPathProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.GroupStyleSelector), GroupStyleSelectorProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.ItemContainerStyle), ItemContainerStyleProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.ItemsPanel), ItemsPanelProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.ItemStringFormat), ItemStringFormatProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.ItemTemplate), ItemTemplateProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.SelectedValuePath), SelectedValuePathProperty, BindingMode.OneWay); RibbonControl.Bind(this, combo, nameof(this.MaxDropDownHeight), MaxDropDownHeightProperty, BindingMode.OneWay); combo.DropDownOpened += this.OnQuickAccessOpened; if (this.IsEditable) { combo.GotFocus += this.OnQuickAccessTextBoxGetFocus; } this.quickAccessCombo = combo; this.UpdateQuickAccessCombo(); return combo; } private void OnQuickAccessTextBoxGetFocus(object? sender, RoutedEventArgs e) { if (this.quickAccessCombo is null) { return; } this.isQuickAccessFocused = true; if (!this.isQuickAccessOpened) { this.Freeze(); } this.quickAccessCombo.LostFocus += this.OnQuickAccessTextBoxLostFocus; } private void OnQuickAccessTextBoxLostFocus(object? sender, RoutedEventArgs e) { if (this.quickAccessCombo is null) { return; } this.quickAccessCombo.LostFocus -= this.OnQuickAccessTextBoxLostFocus; if (!this.isQuickAccessOpened) { this.Unfreeze(); } this.isQuickAccessFocused = false; } private bool isQuickAccessFocused; private bool isQuickAccessOpened; private object? selectedItem; private ComboBox? quickAccessCombo; private void OnQuickAccessOpened(object? sender, EventArgs e) { if (this.quickAccessCombo is null) { return; } this.isQuickAccessOpened = true; this.quickAccessCombo.DropDownClosed += this.OnQuickAccessMenuClosed; this.quickAccessCombo.UpdateLayout(); if (this.isQuickAccessFocused == false) { this.RunInDispatcherAsync(this.FreezeAnBringSelectedItemIntoView); } } private void FreezeAnBringSelectedItemIntoView() { this.Freeze(); this.RunInDispatcherAsync(this.BringSelectedItemIntoView, DispatcherPriority.Input); } private void BringSelectedItemIntoView() { if (this.quickAccessCombo?.SelectedItem is null) { return; } var containerFromItem = this.quickAccessCombo.ItemContainerGenerator.ContainerOrContainerContentFromItem<FrameworkElement>(this.quickAccessCombo.SelectedItem); containerFromItem?.BringIntoView(); } private void OnQuickAccessMenuClosed(object? sender, EventArgs e) { if (this.quickAccessCombo is not null) { this.quickAccessCombo.DropDownClosed -= this.OnQuickAccessMenuClosed; } if (!this.isQuickAccessFocused) { this.Unfreeze(); } this.isQuickAccessOpened = false; } private void Freeze() { if (this.quickAccessCombo is null) { return; } this.IsSnapped = true; this.selectedItem = this.SelectedItem; ItemsControlHelper.MoveItemsToDifferentControl(this, this.quickAccessCombo); this.SelectedItem = null; this.quickAccessCombo.SelectedItem = this.selectedItem; this.quickAccessCombo.Menu = this.Menu; this.Menu = null; this.quickAccessCombo.IsSnapped = false; } private void Unfreeze() { if (this.quickAccessCombo is null) { return; } var text = this.quickAccessCombo.Text; this.selectedItem = this.quickAccessCombo.SelectedItem; this.quickAccessCombo.IsSnapped = true; ItemsControlHelper.MoveItemsToDifferentControl(this.quickAccessCombo, this); this.quickAccessCombo.SelectedItem = null; this.SelectedItem = this.selectedItem; this.Menu = this.quickAccessCombo.Menu; this.quickAccessCombo.Menu = null; this.IsSnapped = false; this.Text = text; this.UpdateLayout(); } private void UpdateQuickAccessCombo() { if (this.IsLoaded == false) { this.Loaded += this.OnFirstLoaded; } if (this.quickAccessCombo is null) { return; } if (this.IsEditable == false) { this.RunInDispatcherAsync(() => { this.quickAccessCombo.IsSnapped = true; this.IsSnapped = true; if (this.snappedImage is not null && this.quickAccessCombo.snappedImage is not null) { this.quickAccessCombo.snappedImage.Source = this.snappedImage.Source; this.quickAccessCombo.snappedImage.Visibility = Visibility.Visible; if (this.quickAccessCombo.IsSnapped == false) { this.quickAccessCombo.isSnapped = true; } } this.IsSnapped = false; }, DispatcherPriority.ApplicationIdle); } } private void OnFirstLoaded(object? sender, RoutedEventArgs e) { this.Loaded -= this.OnFirstLoaded; this.UpdateQuickAccessCombo(); } /// <inheritdoc /> public bool CanAddToQuickAccessToolBar { get { return (bool)this.GetValue(CanAddToQuickAccessToolBarProperty); } set { this.SetValue(CanAddToQuickAccessToolBarProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="CanAddToQuickAccessToolBar"/> dependency property.</summary> public static readonly DependencyProperty CanAddToQuickAccessToolBarProperty = RibbonControl.CanAddToQuickAccessToolBarProperty.AddOwner(typeof(ComboBox), new PropertyMetadata(BooleanBoxes.TrueBox, RibbonControl.OnCanAddToQuickAccessToolBarChanged)); #endregion #region Overrides /// <inheritdoc /> public override void OnApplyTemplate() { this.dropDownButton = this.GetTemplateChild("PART_ToggleButton") as ToggleButton; if (this.dropDownButton is ISimplifiedStateControl control) { control.UpdateSimplifiedState(this.IsSimplified); } this.DropDownPopup = this.GetTemplateChild("PART_Popup") as Popup; this.snappedImage = this.GetTemplateChild("PART_SelectedImage") as Image; this.contentSite = this.GetTemplateChild("PART_ContentSite") as ContentPresenter; if (this.contentBorder is not null) { this.contentBorder.PreviewMouseDown -= this.OnContentBorderPreviewMouseDown; } this.contentBorder = this.GetTemplateChild("PART_ContentBorder") as Border; if (this.contentBorder is not null) { this.contentBorder.PreviewMouseDown += this.OnContentBorderPreviewMouseDown; } this.scrollViewer = this.GetTemplateChild("PART_ScrollViewer") as ScrollViewer; base.OnApplyTemplate(); } /// <inheritdoc /> protected override void OnDropDownOpened(EventArgs e) { base.OnDropDownOpened(e); Mouse.Capture(this, CaptureMode.SubTree); if (this.SelectedItem is not null) { Keyboard.Focus(this.ItemContainerGenerator.ContainerOrContainerContentFromItem<IInputElement>(this.SelectedItem)); } this.focusedElement = Keyboard.FocusedElement; if (this.focusedElement is not null) { this.focusedElement.LostKeyboardFocus += this.OnFocusedElementLostKeyboardFocus; } if (this.scrollViewer is not null) { this.scrollViewer.Width = double.NaN; this.scrollViewer.Height = double.NaN; } var popupChild = this.DropDownPopup?.Child as FrameworkElement; var initialHeight = Math.Min(RibbonControl.GetControlWorkArea(this).Height * 2 / 3, this.MaxDropDownHeight); if (double.IsNaN(this.DropDownHeight) == false) { initialHeight = Math.Min(this.DropDownHeight, this.MaxDropDownHeight); } if (this.scrollViewer?.DesiredSize.Height > initialHeight) { this.scrollViewer.Height = initialHeight; } popupChild?.UpdateLayout(); } /// <inheritdoc /> protected override void OnDropDownClosed(EventArgs e) { base.OnDropDownClosed(e); if (ReferenceEquals(Mouse.Captured, this)) { Mouse.Capture(null); } if (this.focusedElement is not null) { this.focusedElement.LostKeyboardFocus -= this.OnFocusedElementLostKeyboardFocus; } this.focusedElement = null; if (this.scrollViewer is not null) { this.scrollViewer.Width = double.NaN; this.scrollViewer.Height = double.NaN; } } private void OnFocusedElementLostKeyboardFocus(object? sender, KeyboardFocusChangedEventArgs e) { if (this.focusedElement is not null) { this.focusedElement.LostKeyboardFocus -= this.OnFocusedElementLostKeyboardFocus; } this.focusedElement = Keyboard.FocusedElement; if (this.focusedElement is not null) { this.focusedElement.LostKeyboardFocus += this.OnFocusedElementLostKeyboardFocus; if (this.IsEditable && this.Items.Contains(this.ItemContainerGenerator.ItemFromContainerOrContainerContent((DependencyObject)Keyboard.FocusedElement))) { this.SelectedItem = this.ItemContainerGenerator.ItemFromContainerOrContainerContent((DependencyObject)Keyboard.FocusedElement); } } } /// <inheritdoc /> protected override void OnPreviewKeyDown(KeyEventArgs e) { if (this.IsEditable && ((e.Key == Key.Down) || (e.Key == Key.Up)) && !this.IsDropDownOpen) { this.IsDropDownOpen = true; e.Handled = true; return; } base.OnPreviewKeyDown(e); } /// <inheritdoc /> protected override void OnKeyDown(KeyEventArgs e) { var baseKeyDownCalled = false; if ((this.Menu is not null && this.Menu.IsKeyboardFocusWithin == false) && e.Key != Key.Tab) { base.OnKeyDown(e); baseKeyDownCalled = true; if (e.Handled) { return; } } if (this.Menu is not null && this.Menu.Items.IsEmpty == false) { if (e.Key == Key.Tab) { if (this.Menu.IsKeyboardFocusWithin) { Keyboard.Focus(this.ItemContainerGenerator.ContainerOrContainerContentFromIndex<IInputElement>(0)); } else { Keyboard.Focus(this.Menu.ItemContainerGenerator.ContainerOrContainerContentFromIndex<IInputElement>(0)); } e.Handled = true; return; } if (this.Menu.Items.Contains(this.Menu.ItemContainerGenerator.ItemFromContainerOrContainerContent((DependencyObject)Keyboard.FocusedElement))) { if (e.Key == Key.Down) { var indexOfMenuSelectedItem = this.Menu.ItemContainerGenerator.IndexFromContainer((DependencyObject)Keyboard.FocusedElement); if (indexOfMenuSelectedItem != this.Menu.Items.Count - 1) { Keyboard.Focus(this.Menu.ItemContainerGenerator.ContainerOrContainerContentFromIndex<IInputElement>(indexOfMenuSelectedItem + 1)); } else { Keyboard.Focus(this.Menu.ItemContainerGenerator.ContainerOrContainerContentFromIndex<IInputElement>(0)); } e.Handled = true; return; } if (e.Key == Key.Up) { var indexOfMenuSelectedItem = this.Menu.ItemContainerGenerator.IndexFromContainer((DependencyObject)Keyboard.FocusedElement); if (indexOfMenuSelectedItem != 0) { Keyboard.Focus(this.Menu.ItemContainerGenerator.ContainerOrContainerContentFromIndex<IInputElement>(indexOfMenuSelectedItem - 1)); } else { Keyboard.Focus(this.Menu.ItemContainerGenerator.ContainerOrContainerContentFromIndex<IInputElement>(this.Menu.Items.Count - 1)); } e.Handled = true; return; } } } if (baseKeyDownCalled == false && e.Handled == false) { base.OnKeyDown(e); } } #endregion #region Methods /// <inheritdoc /> public virtual KeyTipPressedResult OnKeyTipPressed() { // Edge case: Whole dropdown content is disabled if (this.IsKeyboardFocusWithin == false) { Keyboard.Focus(this); } if (this.IsEditable == false) { this.IsDropDownOpen = true; return new KeyTipPressedResult(true, true); } return new KeyTipPressedResult(true, false); } /// <inheritdoc /> public void OnKeyTipBack() { } #endregion #region Private methods // Prevent reopenning of the dropdown menu (popup) private void OnContentBorderPreviewMouseDown(object? sender, MouseButtonEventArgs e) { if (this.IsDropDownOpen) { this.IsDropDownOpen = false; e.Handled = true; } } #endregion /// <inheritdoc /> void ISimplifiedStateControl.UpdateSimplifiedState(bool isSimplified) { this.IsSimplified = isSimplified; if (this.dropDownButton is ISimplifiedStateControl control) { control.UpdateSimplifiedState(isSimplified); } } /// <inheritdoc /> void ILogicalChildSupport.AddLogicalChild(object child) { this.AddLogicalChild(child); } /// <inheritdoc /> void ILogicalChildSupport.RemoveLogicalChild(object child) { this.RemoveLogicalChild(child); } /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var baseEnumerator = base.LogicalChildren; while (baseEnumerator?.MoveNext() == true) { yield return baseEnumerator.Current; } if (this.Icon is not null) { yield return this.Icon; } if (this.MediumIcon is not null) { yield return this.MediumIcon; } if (this.Header is not null) { yield return this.Header; } if (this.TopPopupContent is not null) { yield return this.TopPopupContent; } } } /// <inheritdoc /> protected override AutomationPeer OnCreateAutomationPeer() => new Fluent.Automation.Peers.RibbonComboBoxAutomationPeer(this); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Globalization { using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // // List of calendar data // Note the we cache overrides. // Note that localized names (resource names) aren't available from here. // // NOTE: Calendars depend on the locale name that creates it. Only a few // properties are available without locales using CalendarData.GetCalendar(int) // StructLayout is needed here otherwise compiler can re-arrange the fields. // We have to keep this in-sync with the definition in calendardata.h // // WARNING WARNING WARNING // // WARNING: Anything changed here also needs to be updated on the native side (object.h see type CalendarDataBaseObject) // WARNING: The type loader will rearrange class member offsets so the mscorwks!CalendarDataBaseObject // WARNING: must be manually structured to match the true loaded class layout // internal class CalendarData { // Max calendars internal const int MAX_CALENDARS = 23; // Identity internal String sNativeName ; // Calendar Name for the locale // Formats internal String[] saShortDates ; // Short Data format, default first internal String[] saYearMonths ; // Year/Month Data format, default first internal String[] saLongDates ; // Long Data format, default first internal String sMonthDay ; // Month/Day format // Calendar Parts Names internal String[] saEraNames ; // Names of Eras internal String[] saAbbrevEraNames ; // Abbreviated Era Names internal String[] saAbbrevEnglishEraNames ; // Abbreviated Era Names in English internal String[] saDayNames ; // Day Names, null to use locale data, starts on Sunday internal String[] saAbbrevDayNames ; // Abbrev Day Names, null to use locale data, starts on Sunday internal String[] saSuperShortDayNames ; // Super short Day of week names internal String[] saMonthNames ; // Month Names (13) internal String[] saAbbrevMonthNames ; // Abbrev Month Names (13) internal String[] saMonthGenitiveNames ; // Genitive Month Names (13) internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13) internal String[] saLeapYearMonthNames ; // Multiple strings for the month names in a leap year. // Integers at end to make marshaller happier internal int iTwoDigitYearMax=2029 ; // Max 2 digit year (for Y2K bug data entry) internal int iCurrentEra=0 ; // current era # (usually 1) // Use overrides? internal bool bUseUserOverrides ; // True if we want user overrides. // Static invariant for the invariant locale internal static CalendarData Invariant; // Private constructor private CalendarData() {} // Invariant constructor static CalendarData() { // Set our default/gregorian US calendar data // Calendar IDs are 1-based, arrays are 0 based. CalendarData invariant = new CalendarData(); // Set default data for calendar // Note that we don't load resources since this IS NOT supposed to change (by definition) invariant.sNativeName = "Gregorian Calendar"; // Calendar Name // Year invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry) invariant.iCurrentEra = 1; // Current era # // Formats invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy"}; // long date format invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format invariant.sMonthDay = "MMMM dd"; // Month day pattern // Calendar Parts Names invariant.saEraNames = new String[] { "A.D." }; // Era names invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names invariant.saAbbrevEnglishEraNames=new String[] { "AD" }; // Abbreviated era names in English invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", String.Empty}; // month names invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant) invariant.saAbbrevMonthGenitiveNames=invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant) invariant.bUseUserOverrides = false; // Calendar was built, go ahead and assign it... Invariant = invariant; } // // Get a bunch of data for a calendar // internal CalendarData(String localeName, int calendarId, bool bUseUserOverrides) { // Call nativeGetCalendarData to populate the data this.bUseUserOverrides = bUseUserOverrides; if (!nativeGetCalendarData(this, localeName, calendarId)) { Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName); // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale. // Formats if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format // Calendar Parts Names if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13) if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13) // Genitive and Leap names can follow the fallback below } // Clean up the escaping of the formats this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates); this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates); this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths); this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay); if ((CalendarId)calendarId == CalendarId.TAIWAN) { if (CultureInfo.IsTaiwanSku) { // We got the month/day names from the OS (same as gregorian), but the native name is wrong this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6"; } else { this.sNativeName = String.Empty; } } // Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc) if (this.saMonthGenitiveNames == null || String.IsNullOrEmpty(this.saMonthGenitiveNames[0])) this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant) if (this.saAbbrevMonthGenitiveNames == null || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0])) this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) if (this.saLeapYearMonthNames == null || String.IsNullOrEmpty(this.saLeapYearMonthNames[0])) this.saLeapYearMonthNames = this.saMonthNames; InitializeEraNames(localeName, calendarId); InitializeAbbreviatedEraNames(localeName, calendarId); // Abbreviated English Era Names are only used for the Japanese calendar. if (calendarId == (int)CalendarId.JAPAN) { this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames(); } else { // For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars) this.saAbbrevEnglishEraNames = new String[] { "" }; } // Japanese is the only thing with > 1 era. Its current era # is how many ever // eras are in the array. (And the others all have 1 string in the array) this.iCurrentEra = this.saEraNames.Length; } private void InitializeEraNames(string localeName, int calendarId) { // Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows switch ((CalendarId)calendarId) { // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new String[] { "A.D." }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: this.saEraNames = new String[] { "A.D." }; break; case CalendarId.HEBREW: this.saEraNames = new String[] { "C.E." }; break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" }; } else { this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" }; } break; case CalendarId.GREGORIAN_ARABIC: case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: // These are all the same: this.saEraNames = new String[] { "\x0645" }; break; case CalendarId.GREGORIAN_ME_FRENCH: this.saEraNames = new String[] { "ap. J.-C." }; break; case CalendarId.TAIWAN: if (CultureInfo.IsTaiwanSku) { this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" }; } else { this.saEraNames = new String[] { String.Empty }; } break; case CalendarId.KOREA: this.saEraNames = new String[] { "\xb2e8\xae30" }; break; case CalendarId.THAI: this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: this.saEraNames = JapaneseCalendar.EraNames(); break; case CalendarId.PERSIAN: if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new String[] { "\x0647\x002e\x0634" }; } break; default: // Most calendars are just "A.D." this.saEraNames = Invariant.saEraNames; break; } } private void InitializeAbbreviatedEraNames(string localeName, int calendarId) { // Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows switch ((CalendarId)calendarId) { // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for culture.dll missing if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = new String[] { "AD" }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: this.saAbbrevEraNames = new String[] { "AD" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames(); break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi this.saAbbrevEraNames = new String[] { "\x0780\x002e" }; } else { this.saAbbrevEraNames = new String[] { "\x0647\x0640" }; } break; case CalendarId.TAIWAN: // Get era name and abbreviate it this.saAbbrevEraNames = new String[1]; if (this.saEraNames[0].Length == 4) { this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2,2); } else { this.saAbbrevEraNames[0] = this.saEraNames[0]; } break; case CalendarId.PERSIAN: if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = this.saEraNames; } break; default: // Most calendars just use the full name this.saAbbrevEraNames = this.saEraNames; break; } } internal static CalendarData GetCalendarData(int calendarId) { // // Get a calendar. // Unfortunately we depend on the locale in the OS, so we need a locale // no matter what. So just get the appropriate calendar from the // appropriate locale here // // Get a culture name String culture = CalendarIdToCultureName(calendarId); // Return our calendar return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId); } // // Helper methods // private static String CalendarIdToCultureName(int calendarId) { // note that this doesn't handle the new calendars (lunisolar, etc) switch (calendarId) { case Calendar.CAL_GREGORIAN_US: return "fa-IR"; // "fa-IR" Iran case Calendar.CAL_JAPAN: return "ja-JP"; // "ja-JP" Japan case Calendar.CAL_TAIWAN: // zh-TW Taiwan return "zh-TW"; case Calendar.CAL_KOREA: return "ko-KR"; // "ko-KR" Korea case Calendar.CAL_HIJRI: case Calendar.CAL_GREGORIAN_ARABIC: case Calendar.CAL_UMALQURA: return "ar-SA"; // "ar-SA" Saudi Arabia case Calendar.CAL_THAI: return "th-TH"; // "th-TH" Thailand case Calendar.CAL_HEBREW: return "he-IL"; // "he-IL" Israel case Calendar.CAL_GREGORIAN_ME_FRENCH: return "ar-DZ"; // "ar-DZ" Algeria case Calendar.CAL_GREGORIAN_XLIT_ENGLISH: case Calendar.CAL_GREGORIAN_XLIT_FRENCH: return "ar-IQ"; // "ar-IQ"; Iraq default: // Default to gregorian en-US break; } return "en-US"; } internal void FixupWin7MonthDaySemicolonBug() { int unescapedCharacterIndex = FindUnescapedCharacter(sMonthDay, ';'); if (unescapedCharacterIndex > 0) { sMonthDay = sMonthDay.Substring(0, unescapedCharacterIndex); } } private static int FindUnescapedCharacter(string s, char charToFind) { bool inComment = false; int length = s.Length; for (int i = 0; i < length; i++) { char c = s[i]; switch (c) { case '\'': inComment = !inComment; break; case '\\': i++; // escape sequence -- skip next character break; default: if (!inComment && charToFind == c) { return i; } break; } } return -1; } // Get native two digit year max [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int nativeGetTwoDigitYearMax(int calID); // Call native side to load our calendar data [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool nativeGetCalendarData(CalendarData data, String localeName, int calendar); // Call native side to figure out which calendars are allowed [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int nativeGetCalendars(String localeName, bool useUserOverride, [In, Out] int[] calendars); } }
namespace EasyVet.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.Addresses", c => new { Id = c.Int(nullable: false, identity: true), StreetType = c.String(nullable: false), StreetName = c.String(nullable: false), Number = c.Int(nullable: false), Complement = c.String(), Neighbourhood = c.String(nullable: false), Municipality = c.String(nullable: false), State = c.String(nullable: false), ZipCode = c.String(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Animals", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), Type = c.Int(nullable: false), Gender = c.String(nullable: false), Age = c.Int(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), Breed = c.String(), Discriminator = c.String(nullable: false, maxLength: 128), Owner_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Costumers", t => t.Owner_Id) .Index(t => t.Owner_Id); CreateTable( "dbo.Users", c => new { Id = c.Int(nullable: false, identity: true), Cpf = c.String(nullable: false), Name = c.String(nullable: false), Password = c.String(nullable: false), BirdhDate = c.DateTime(nullable: false), PhoneNumber = c.String(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), Salary = c.Decimal(precision: 18, scale: 2), Discriminator = c.String(maxLength: 128), Address_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Addresses", t => t.Address_Id) .Index(t => t.Address_Id); CreateTable( "dbo.Appointments", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Description = c.String(), Date = c.DateTime(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), Veterinary_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Veterinaries", t => t.Veterinary_Id) .Index(t => t.Veterinary_Id); CreateTable( "dbo.Payments", c => new { Id = c.Int(nullable: false, identity: true), Method = c.Int(nullable: false), Status = c.Int(nullable: false), Date = c.DateTime(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Products", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), Description = c.String(), Price = c.Decimal(nullable: false, precision: 18, scale: 2), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SaleProducts", c => new { Id = c.Int(nullable: false, identity: true), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), Product_Id = c.Int(nullable: false), Sale_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Products", t => t.Product_Id, cascadeDelete: true) .ForeignKey("dbo.Sales", t => t.Sale_Id, cascadeDelete: true) .Index(t => t.Product_Id) .Index(t => t.Sale_Id); CreateTable( "dbo.Sales", c => new { Id = c.Int(nullable: false, identity: true), Value = c.Decimal(nullable: false, precision: 18, scale: 2), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Stocks", c => new { Id = c.Int(nullable: false, identity: true), Quantity = c.Int(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), Location_Id = c.Int(nullable: false), Product_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Addresses", t => t.Location_Id, cascadeDelete: true) .ForeignKey("dbo.Products", t => t.Product_Id, cascadeDelete: true) .Index(t => t.Location_Id) .Index(t => t.Product_Id); CreateTable( "dbo.Cashier", c => new { Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.Id) .Index(t => t.Id); CreateTable( "dbo.Costumers", c => new { Id = c.Int(nullable: false), Email = c.String(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.Id) .Index(t => t.Id); CreateTable( "dbo.SalesPeople", c => new { Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.Id) .Index(t => t.Id); CreateTable( "dbo.Veterinaries", c => new { Id = c.Int(nullable: false), Specialty = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.Id) .Index(t => t.Id); } public override void Down() { DropForeignKey("dbo.Veterinaries", "Id", "dbo.Users"); DropForeignKey("dbo.SalesPeople", "Id", "dbo.Users"); DropForeignKey("dbo.Costumers", "Id", "dbo.Users"); DropForeignKey("dbo.Cashier", "Id", "dbo.Users"); DropForeignKey("dbo.Users", "Address_Id", "dbo.Addresses"); DropForeignKey("dbo.Stocks", "Product_Id", "dbo.Products"); DropForeignKey("dbo.Stocks", "Location_Id", "dbo.Addresses"); DropForeignKey("dbo.SaleProducts", "Sale_Id", "dbo.Sales"); DropForeignKey("dbo.SaleProducts", "Product_Id", "dbo.Products"); DropForeignKey("dbo.Appointments", "Veterinary_Id", "dbo.Veterinaries"); DropForeignKey("dbo.Animals", "Owner_Id", "dbo.Costumers"); DropIndex("dbo.Veterinaries", new[] { "Id" }); DropIndex("dbo.SalesPeople", new[] { "Id" }); DropIndex("dbo.Costumers", new[] { "Id" }); DropIndex("dbo.Cashier", new[] { "Id" }); DropIndex("dbo.Stocks", new[] { "Product_Id" }); DropIndex("dbo.Stocks", new[] { "Location_Id" }); DropIndex("dbo.SaleProducts", new[] { "Sale_Id" }); DropIndex("dbo.SaleProducts", new[] { "Product_Id" }); DropIndex("dbo.Appointments", new[] { "Veterinary_Id" }); DropIndex("dbo.Users", new[] { "Address_Id" }); DropIndex("dbo.Animals", new[] { "Owner_Id" }); DropTable("dbo.Veterinaries"); DropTable("dbo.SalesPeople"); DropTable("dbo.Costumers"); DropTable("dbo.Cashier"); DropTable("dbo.Stocks"); DropTable("dbo.Sales"); DropTable("dbo.SaleProducts"); DropTable("dbo.Products"); DropTable("dbo.Payments"); DropTable("dbo.Appointments"); DropTable("dbo.Users"); DropTable("dbo.Animals"); DropTable("dbo.Addresses"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Tests { public class FileStream_ReadAsync : FileSystemTest { [Fact] public void NullBufferThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.ReadAsync(null, 0, 1))); } } [Fact] public void NegativeOffsetThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, 1))); // buffer is checked first Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, 1))); } } [Fact] public void NegativeCountThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<ArgumentOutOfRangeException>("count", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, -1))); // offset is checked before count Assert.Throws<ArgumentOutOfRangeException>("offset", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, -1))); // buffer is checked first Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, -1))); } } [Fact] public void BufferOutOfBoundsThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { // offset out of bounds Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 1, 1))); // offset out of bounds for 0 count ReadAsync Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 2, 0))); // offset out of bounds even for 0 length buffer Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], 1, 0))); // combination offset and count out of bounds Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2))); // edges Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], int.MaxValue, 0))); Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], int.MaxValue, int.MaxValue))); } } [Fact] public void ReadAsyncDisposedThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Dispose(); Assert.Throws<ObjectDisposedException>(() => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, 1))); // even for noop ReadAsync Assert.Throws<ObjectDisposedException>(() => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, 0))); // out of bounds checking happens first Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2))); // count is checked prior Assert.Throws<ArgumentOutOfRangeException>("count", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, -1))); // offset is checked prior Assert.Throws<ArgumentOutOfRangeException>("offset", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, -1))); // buffer is checked first Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, -1))); } } [Fact] public void WriteOnlyThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<NotSupportedException>(() => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, 1))); fs.Dispose(); // Disposed checking happens first Assert.Throws<ObjectDisposedException>(() => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, 1))); // out of bounds checking happens first Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2))); // count is checked prior Assert.Throws<ArgumentOutOfRangeException>("count", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, -1))); // offset is checked prior Assert.Throws<ArgumentOutOfRangeException>("offset", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, -1))); // buffer is checked first Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, -1))); } } [Fact] public void CancelledTokenFastPath() { CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); CancellationToken cancelledToken = cts.Token; using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { FSAssert.IsCancelled(fs.ReadAsync(new byte[1], 0, 1, cancelledToken), cancelledToken); } using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { // before write only check FSAssert.IsCancelled(fs.ReadAsync(new byte[1], 0, 1, cancelledToken), cancelledToken); fs.Dispose(); // before disposed check FSAssert.IsCancelled(fs.ReadAsync(new byte[1], 0, 1, cancelledToken), cancelledToken); // out of bounds checking happens first Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2, cancelledToken))); // count is checked prior Assert.Throws<ArgumentOutOfRangeException>("count", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 0, -1, cancelledToken))); // offset is checked prior Assert.Throws<ArgumentOutOfRangeException>("offset", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, -1, cancelledToken))); // buffer is checked first Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, -1, cancelledToken))); } } [Fact] public async Task NoopReadAsyncsSucceed() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { // note that these do not succeed synchronously even though they do nothing. Assert.Equal(0, await fs.ReadAsync(new byte[0], 0, 0)); Assert.Equal(0, await fs.ReadAsync(new byte[1], 0, 0)); // even though offset is out of bounds of buffer, this is still allowed // for the last element Assert.Equal(0, await fs.ReadAsync(new byte[1], 1, 0)); Assert.Equal(0, await fs.ReadAsync(new byte[2], 1, 0)); } } [Fact] public async Task EmptyFileReadAsyncSucceedSynchronously() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { byte[] buffer = new byte[TestBuffer.Length]; // use a recognizable pattern TestBuffer.CopyTo(buffer, 0); // note that these do not succeed synchronously even though they do nothing. Assert.Equal(0, await fs.ReadAsync(buffer, 0, 1)); Assert.Equal(TestBuffer, buffer); Assert.Equal(0, await fs.ReadAsync(buffer, 0, buffer.Length)); Assert.Equal(TestBuffer, buffer); Assert.Equal(0, await fs.ReadAsync(buffer, buffer.Length - 1, 1)); Assert.Equal(TestBuffer, buffer); Assert.Equal(0, await fs.ReadAsync(buffer, buffer.Length / 2, buffer.Length - buffer.Length / 2)); Assert.Equal(TestBuffer, buffer); } } [Fact] public async Task ReadAsyncBufferedCompletesSynchronously() { string fileName = GetTestFilePath(); using (var fs = new FileStream(fileName, FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); fs.Write(TestBuffer, 0, TestBuffer.Length); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, TestBuffer.Length * 2, useAsync: true)) { byte[] buffer = new byte[TestBuffer.Length]; // prime the internal buffer Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length)); Assert.Equal(TestBuffer, buffer); Array.Clear(buffer, 0, buffer.Length); // read should now complete synchronously since it is serviced by the read buffer filled in the first request Assert.Equal(TestBuffer.Length, FSAssert.CompletesSynchronously(fs.ReadAsync(buffer, 0, buffer.Length))); Assert.Equal(TestBuffer, buffer); } } [Fact] public async Task ReadAsyncExistingFile() { string fileName = GetTestFilePath(); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); } using (FileStream fs = new FileStream(fileName, FileMode.Open)) { byte[] buffer = new byte[TestBuffer.Length]; Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length)); Assert.Equal(TestBuffer, buffer); // ReadAsync with too large buffer at front of buffer fs.Position = 0; buffer = new byte[TestBuffer.Length * 2]; Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length)); Assert.Equal(TestBuffer, buffer.Take(TestBuffer.Length)); // Remainder of buffer should be untouched. Assert.Equal(new byte[buffer.Length - TestBuffer.Length], buffer.Skip(TestBuffer.Length)); // ReadAsync with too large buffer in middle of buffer fs.Position = 0; buffer = new byte[TestBuffer.Length * 2]; Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 2, buffer.Length - 2)); Assert.Equal(TestBuffer, buffer.Skip(2).Take(TestBuffer.Length)); // Remainder of buffer should be untouched. Assert.Equal(new byte[2], buffer.Take(2)); Assert.Equal(new byte[buffer.Length - TestBuffer.Length - 2], buffer.Skip(2 + TestBuffer.Length)); } } [Fact] public async Task ReadAsyncCancelledFile() { string fileName = GetTestFilePath(); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { while(fs.Length < 128 * 1024) fs.Write(TestBuffer, 0, TestBuffer.Length); } using (FileStream fs = new FileStream(fileName, FileMode.Open)) { byte[] buffer = new byte[fs.Length]; CancellationTokenSource cts = new CancellationTokenSource(); Task<int> readTask = fs.ReadAsync(buffer, 0, buffer.Length, cts.Token); cts.Cancel(); try { await readTask; // we may not have canceled before the task completed. } catch(OperationCanceledException oce) { // Ideally we'd be doing an Assert.Throws<OperationCanceledException> // but since cancellation is a race condition we accept either outcome Assert.Equal(cts.Token, oce.CancellationToken); } } } [Fact, OuterLoop] public async Task ReadAsyncMiniStress() { TimeSpan testRunTime = TimeSpan.FromSeconds(10); const int MaximumReadSize = 16 * 1024; const int NormalReadSize = 4 * 1024; Random rand = new Random(); DateTime testStartTime = DateTime.UtcNow; // Generate file data byte[] readableFileContents = new byte[MaximumReadSize * 16]; rand.NextBytes(readableFileContents); // Create and fill file string readableFilePath = GetTestFilePath(); using (var stream = new FileStream(readableFilePath, FileMode.CreateNew, FileAccess.Write)) { await stream.WriteAsync(readableFileContents, 0, readableFileContents.Length); } using (var stream = new FileStream(readableFilePath, FileMode.Open, FileAccess.Read)) { // Create a new token that expires between 100-1000ms CancellationTokenSource tokenSource = new CancellationTokenSource(); tokenSource.CancelAfter(rand.Next(100, 1000)); int currentPosition = 0; byte[] buffer = new byte[MaximumReadSize]; do { try { // 20%: random read size int bytesToRead = (rand.NextDouble() < 0.2 ? rand.Next(16, MaximumReadSize) : NormalReadSize); int bytesRead; if (rand.NextDouble() < 0.1) { // 10%: Sync read bytesRead = stream.Read(buffer, 0, bytesToRead); } else { // 90%: Async read bytesRead = await stream.ReadAsync(buffer, 0, bytesToRead, tokenSource.Token); } // 10%: Verify data (burns a lot of CPU time) if (rand.NextDouble() < 0.1) { // Validate data read Assert.True(bytesRead + currentPosition <= readableFileContents.Length, "Too many bytes read"); Assert.Equal(readableFileContents.Skip(currentPosition).Take(bytesRead), buffer.Take(bytesRead)); } // Advance position and reset if we are at the end currentPosition += bytesRead; if (currentPosition >= readableFileContents.Length) { currentPosition = 0; stream.Seek(0, SeekOrigin.Begin); } } catch (TaskCanceledException) { // Once the token has expired, generate a new one Assert.True(tokenSource.Token.IsCancellationRequested, "Received cancellation exception before token expired"); tokenSource = new CancellationTokenSource(); tokenSource.CancelAfter(rand.Next(100, 1000)); } } while (DateTime.UtcNow - testStartTime <= testRunTime); } } } }
using System.Diagnostics; using System; using System.Management; using System.Collections; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Web.UI.Design; using System.Data; using System.Collections.Generic; using System.Linq; using System.Runtime; using System.Globalization; using System.IO; using System.Net.Mail; using System.Net.Mime; using System.Text; // POP3 Email Client // ================= // // copyright by Peter Huber, Singapore, 2006 // this code is provided as is, bugs are probable, free for any use at own risk, no // responsibility accepted. All rights, title and interest in and to the accompanying content retained. :-) // // based on Standard for ARPA Internet Text Messages, http://rfc.net/rfc822.html // based on MIME Standard, Internet Message Bodies, http://rfc.net/rfc2045.html // based on MIME Standard, Media Types, http://rfc.net/rfc2046.html // based on QuotedPrintable Class from ASP emporium, http://www.aspemporium.com/classes.aspx?cid=6 // based on MIME Standard, E-mail Encapsulation of HTML (MHTML), http://rfc.net/rfc2110.html // based on MIME Standard, Multipart/Related Content-type, http://rfc.net/rfc2112.html // ?? RFC 2557 MIME Encapsulation of Aggregate Documents http://rfc.net/rfc2557.html namespace SoftLogik.Mail { namespace Mail { namespace Pop3 { // POP3 Client Email // ================= /// <summary> /// Reads POP3 / MIME based emails /// </summary> public class Pop3MimeClient : Pop3MailClient { //character array 'constants' used for analysing POP3 / MIME //---------------------------------------------------------- private static char[] BlankChars = {' '}; private static char[] BracketChars = {'(', ')'}; private static char[] ColonChars = {':'}; private static char[] CommaChars = {','}; private static char[] EqualChars = {'='}; private static char[] ForwardSlashChars = {'/'}; private static char[] SemiColonChars = {';'}; private static char[] WhiteSpaceChars = {' ', '\t'}; private static char[] NonValueChars = {'\"', '(', ')'}; //Help for debugging //------------------ /// <summary> /// used for debugging. Collects all unknown header lines for all (!) emails received /// </summary> public static bool isCollectUnknowHeaderLines = true; /// <summary> /// list of all unknown header lines received, for all (!) emails /// </summary> public static List<string> AllUnknowHeaderLines; /// <summary> /// Set this flag, if you would like to get also the email in the raw US-ASCII format /// as received. /// Good for debugging, but takes quiet some space. /// </summary> public bool IsCollectRawEmail { get { return isGetRawEmail; } set { isGetRawEmail = value; } } private bool isGetRawEmail = false; // Pop3MimeClient Constructor //--------------------------- /// <summary> /// constructor /// </summary> public Pop3MimeClient(string PopServer, int Port, bool useSSL, string Username, string Password) : base(PopServer, Port, useSSL, Username, Password) { AllUnknowHeaderLines = new List<string>(); } /// <summary> /// Gets 1 email from POP3 server and processes it. /// </summary> /// <param name="MessageNo">Email Id to be fetched from POP3 server</param> /// <param name="Message">decoded email</param> /// <returns>false: no email received or email not properly formatted</returns> public bool GetEmail(int MessageNo, ref RxMailMessage Message) { Message = null; //request email, send RETRieve command to POP3 server if (! SendRetrCommand(MessageNo)) { return false; } //prepare message, set defaults as specified in RFC 2046 //although they get normally overwritten, we have to make sure there are at least defaults Message = new RxMailMessage(); Message.ContentTransferEncoding = TransferEncoding.SevenBit; Message.TransferType = "7bit"; this.m_messageNo = MessageNo; //raw email tracing if (isGetRawEmail) { isTraceRawEmail = true; if (RawEmailSB == null) { RawEmailSB = new StringBuilder(100000); } else { RawEmailSB.Length = 0; } } //convert received email into RxMailMessage MimeEntityReturnCode MessageMimeReturnCode = ProcessMimeEntity(Message, ""); if (isGetRawEmail) { //add raw email version to message Message.RawContent = RawEmailSB.ToString(); isTraceRawEmail = false; } if (MessageMimeReturnCode == MimeEntityReturnCode.bodyComplete || MessageMimeReturnCode == MimeEntityReturnCode.parentBoundaryEndFound) { TraceFrom("email with {0} body chars received", Message.Body.Length); return true; } return false; } private int m_messageNo; private void callGetEmailWarning(string warningText, params object[] warningParameters) { string warningString; try { warningString = string.Format(warningText, warningParameters); } catch (System.Exception) { //some strange email address can give string.Format() a problem warningString = warningText; } CallWarning("GetEmail", "", "Problem EmailNo {0}: " + warningString, m_messageNo); } /// <summary> /// indicates the reason how a MIME entity processing has terminated /// </summary> private enum MimeEntityReturnCode { undefined = 0, //meaning like null bodyComplete, //end of message line found parentBoundaryStartFound, parentBoundaryEndFound, problem //received message doesn't follow MIME specification } //buffer used by every ProcessMimeEntity() to store MIME entity private StringBuilder MimeEntitySB = new StringBuilder(100000); /// <summary> /// Process a MIME entity /// /// A MIME entity consists of header and body. /// Separator lines in the body might mark children MIME entities /// </summary> private MimeEntityReturnCode ProcessMimeEntity(RxMailMessage message, string parentBoundaryStart) { bool hasParentBoundary = parentBoundaryStart.Length > 0; string parentBoundaryEnd = parentBoundaryStart + "--"; MimeEntityReturnCode boundaryMimeReturnCode = new MimeEntityReturnCode(); //some format fields are inherited from parent, only the default for //ContentType needs to be set here, otherwise the boundary parameter would be //inherited too ! message.SetContentTypeFields("text/plain; charset=us-ascii"); //get header //---------- string completeHeaderField = null; //consists of one start line and possibly several continuation lines string response = string.Empty; // read header lines until empty line is found (end of header) while (true) { if (! readMultiLine(ref response)) { //POP3 server has not send any more lines callGetEmailWarning("incomplete MIME entity header received", null); //empty this message while (readMultiLine(ref response)) { } System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this return MimeEntityReturnCode.problem; } if (response.Length < 1) { //empty line found => end of header if (completeHeaderField != null) { ProcessHeaderField(message, completeHeaderField); } else { //there was only an empty header. } break; } //check if there is a parent boundary in the header (wrong format!) if (hasParentBoundary && parentBoundaryFound(response, parentBoundaryStart, parentBoundaryEnd, ref boundaryMimeReturnCode)) { callGetEmailWarning("MIME entity header prematurely ended by parent boundary", null); //empty this message while (readMultiLine(ref response)) { } System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this return boundaryMimeReturnCode; } //read header field //one header field can extend over one start line and multiple continuation lines //a continuation line starts with at least 1 blank (' ') or tab if (response[0] == ' ' || response[0] == '\t') { //continuation line found. if (completeHeaderField == null) { callGetEmailWarning("Email header starts with continuation line", null); //empty this message while (readMultiLine(ref response)) { } System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this return MimeEntityReturnCode.problem; } else { // append space, if needed, and continuation line if (completeHeaderField[completeHeaderField.Length - 1] != ' ') { //previous line did not end with a whitespace //need to replace CRLF with a ' ' completeHeaderField += ' ' + response.TrimStart(WhiteSpaceChars); } else { //previous line did end with a whitespace completeHeaderField += response.TrimStart(WhiteSpaceChars); } } } else { //a new header field line found if (completeHeaderField == null) { //very first field, just copy it and then check for continuation lines completeHeaderField = response; } else { //new header line found ProcessHeaderField(message, completeHeaderField); //save the beginning of the next line completeHeaderField = response; } } } //end while read header lines //process body //------------ MimeEntitySB.Length = 0; //empty StringBuilder. For speed reasons, reuse StringBuilder defined as member of class string BoundaryDelimiterLineStart = null; bool isBoundaryDefined = false; if (message.ContentType.Boundary != null) { isBoundaryDefined = true; BoundaryDelimiterLineStart = "--" + message.ContentType.Boundary; } //prepare return code for the case there is no boundary in the body boundaryMimeReturnCode = MimeEntityReturnCode.bodyComplete; //read body lines while (readMultiLine(ref response)) { //check if there is a boundary line from this entity itself in the body if (isBoundaryDefined && response.TrimEnd(null) == BoundaryDelimiterLineStart) { //boundary line found. //stop the processing here and start a delimited body processing return ProcessDelimitedBody(message, BoundaryDelimiterLineStart, parentBoundaryStart, parentBoundaryEnd); } //check if there is a parent boundary in the body if (hasParentBoundary && parentBoundaryFound(response, parentBoundaryStart, parentBoundaryEnd, ref boundaryMimeReturnCode)) { //a parent boundary is found. Decode the content of the body received so far, then end this MIME entity //note that boundaryMimeReturnCode is set here, but used in the return statement break; } //process next line MimeEntitySB.Append(response + CRLF); } //a complete MIME body read //convert received US ASCII characters to .NET string (Unicode) string TransferEncodedMessage = MimeEntitySB.ToString(); bool isAttachmentSaved = false; switch (message.ContentTransferEncoding) { case TransferEncoding.SevenBit: //nothing to do saveMessageBody(message, TransferEncodedMessage); break; case TransferEncoding.Base64: //convert base 64 -> byte[] byte[] bodyBytes = System.Convert.FromBase64String(TransferEncodedMessage); message.ContentStream = new MemoryStream(bodyBytes, false); if (message.MediaMainType == "text") { //convert byte[] -> string message.Body = DecodeByteArryToString(bodyBytes, message.BodyEncoding); } else if (message.MediaMainType == "image" || message.MediaMainType == "application") { SaveAttachment(message); isAttachmentSaved = true; } break; case TransferEncoding.QuotedPrintable: saveMessageBody(message, QuotedPrintable.Decode(TransferEncodedMessage)); break; default: saveMessageBody(message, TransferEncodedMessage); break; //no need to raise a warning here, the warning was done when analising the header } if (message.ContentDisposition != null&& message.ContentDisposition.DispositionType.ToLowerInvariant() == "attachment" && (! isAttachmentSaved)) { SaveAttachment(message); isAttachmentSaved = true; } return boundaryMimeReturnCode; } /// <summary> /// Check if the response line received is a parent boundary /// </summary> private bool parentBoundaryFound(string response, string parentBoundaryStart, string parentBoundaryEnd, ref MimeEntityReturnCode boundaryMimeReturnCode) { boundaryMimeReturnCode = MimeEntityReturnCode.undefined; if (response == null || response.Length < 2 || response[0] != '-' || response[1] != '-') { //quick test: reponse doesn't start with "--", so cannot be a separator line return false; } if (response == parentBoundaryStart) { boundaryMimeReturnCode = MimeEntityReturnCode.parentBoundaryStartFound; return true; } else if (response == parentBoundaryEnd) { boundaryMimeReturnCode = MimeEntityReturnCode.parentBoundaryEndFound; return true; } return false; } /// <summary> /// Convert one MIME header field and update message accordingly /// </summary> private void ProcessHeaderField(RxMailMessage message, string headerField) { string headerLineType; string headerLineContent; int separatorPosition = headerField.IndexOf(':'); if (separatorPosition < 1) { // header field type not found, skip this line callGetEmailWarning("character \':\' missing in header format field: \'{0}\'", headerField); } else { //process header field type headerLineType = headerField.Substring(0, separatorPosition).ToLowerInvariant(); headerLineContent = headerField.Substring(separatorPosition + 1).Trim(WhiteSpaceChars); if (headerLineType == "" || headerLineContent == "") { //1 of the 2 parts missing, drop the line return; } // add header line to headers message.Headers.Add(headerLineType, headerLineContent); //interpret if possible switch (headerLineType) { case "bcc": AddMailAddresses(headerLineContent, message.Bcc); break; case "cc": AddMailAddresses(headerLineContent, message.CC); break; case "content-description": message.ContentDescription = headerLineContent; break; case "content-disposition": message.ContentDisposition = new ContentDisposition(headerLineContent); break; case "content-id": message.ContentId = headerLineContent; break; case "content-transfer-encoding": message.TransferType = headerLineContent; message.ContentTransferEncoding = ConvertToTransferEncoding(headerLineContent); break; case "content-type": message.SetContentTypeFields(headerLineContent); break; case "date": message.DeliveryDate = ConvertToDateTime(headerLineContent); break; case "delivered-to": message.DeliveredTo = ConvertToMailAddress(headerLineContent); break; case "from": MailAddress address = ConvertToMailAddress(headerLineContent); if (address != null) { message.From = address; } break; case "message-id": message.MessageId = headerLineContent; break; case "mime-version": message.MimeVersion = headerLineContent; break; //message.BodyEncoding = new Encoding(); case "sender": message.Sender = ConvertToMailAddress(headerLineContent); break; case "subject": message.Subject = headerLineContent; break; case "received": break; //throw mail routing information away case "reply-to": message.ReplyTo = ConvertToMailAddress(headerLineContent); break; case "return-path": message.ReturnPath = ConvertToMailAddress(headerLineContent); break; case "to": AddMailAddresses(headerLineContent, message.To); break; default: message.UnknowHeaderlines.Add(headerField); if (isCollectUnknowHeaderLines) { AllUnknowHeaderLines.Add(headerField); } break; } } } /// <summary> /// find individual addresses in the string and add it to address collection /// </summary> /// <param name="Addresses">string with possibly several email addresses</param> /// <param name="AddressCollection">parsed addresses</param> private void AddMailAddresses(string Addresses, MailAddressCollection AddressCollection) { MailAddress adr; try { string[] AddressSplit = Addresses.Split(','); foreach (string adrString in AddressSplit) { adr = ConvertToMailAddress(adrString); if (adr != null) { AddressCollection.Add(adr); } } } catch { System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this } } /// <summary> /// Tries to convert a string into an email address /// </summary> public MailAddress ConvertToMailAddress(string address) { address = address.Trim(); if (address == "<>") { //empty email address, not recognised a such by .NET return null; } try { return new MailAddress(address); } catch { callGetEmailWarning("address format not recognised: \'" + address.Trim() + "\'", null); } return null; } private IFormatProvider culture = new CultureInfo("en-US", true); /// <summary> /// Tries to convert string to date, following POP3 rules /// If there is a run time error, the smallest possible date is returned /// <example>Wed, 04 Jan 2006 07:58:08 -0800</example> /// </summary> public DateTime ConvertToDateTime(string dateTime) { DateTime ReturnDateTime; try { //sample; 'Wed, 04 Jan 2006 07:58:08 -0800 (PST)' //remove day of the week before ',' //remove date zone in '()', -800 indicates the zone already //remove day of week string cleanDateTime = dateTime; string[] DateSplit = cleanDateTime.Split(CommaChars, 2); if (DateSplit.Length > 1) { cleanDateTime = DateSplit[1]; } //remove time zone (PST) DateSplit = cleanDateTime.Split(BracketChars); if (DateSplit.Length > 1) { cleanDateTime = DateSplit[0]; } //convert to DateTime if (!DateTime.TryParse(cleanDateTime, culture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces, out ReturnDateTime)) { //try just to convert the date int DateLength = cleanDateTime.IndexOf(':') - 3; cleanDateTime = cleanDateTime.Substring(0, DateLength); if (DateTime.TryParse(cleanDateTime, culture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces, out ReturnDateTime)) { callGetEmailWarning("got only date, time format not recognised: \'" + dateTime + "\'", null); } else { callGetEmailWarning("date format not recognised: \'" + dateTime + "\'", null); System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this return DateTime.MinValue; } } } catch { callGetEmailWarning("date format not recognised: \'" + dateTime + "\'", null); return DateTime.MinValue; } return ReturnDateTime; } /// <summary> /// converts TransferEncoding as defined in the RFC into a .NET TransferEncoding /// /// .NET doesn't know the type "bit8". It is translated here into "bit7", which /// requires the same kind of processing (none). /// </summary> /// <param name="TransferEncodingString"></param> /// <returns></returns> private TransferEncoding ConvertToTransferEncoding(string TransferEncodingString) { // here, "bit8" is marked as "bit7" (i.e. no transfer encoding needed) // "binary" is illegal in SMTP // something like "7bit" / "8bit" / "binary" / "quoted-printable" / "base64" if ((TransferEncodingString.Trim().ToLowerInvariant() == "7bit") || (TransferEncodingString.Trim().ToLowerInvariant() == "8bit")) { return TransferEncoding.SevenBit; } else if (TransferEncodingString.Trim().ToLowerInvariant() == "quoted-printable") { return TransferEncoding.QuotedPrintable; } else if (TransferEncodingString.Trim().ToLowerInvariant() == "base64") { return TransferEncoding.Base64; } else if (TransferEncodingString.Trim().ToLowerInvariant() == "binary") { throw (new Pop3Exception("SMPT does not support binary transfer encoding")); } else { callGetEmailWarning("not supported content-transfer-encoding: " + TransferEncodingString, null); return TransferEncoding.Unknown; } } /// <summary> /// Copies the content found for the MIME entity to the RxMailMessage body and creates /// a stream which can be used to create attachements, alternative views, ... /// </summary> private void saveMessageBody(RxMailMessage message, string contentString) { message.Body = contentString; MemoryStream bodyStream = new MemoryStream(); StreamWriter bodyStreamWriter = new StreamWriter(bodyStream); bodyStreamWriter.Write(contentString); int l = contentString.Length; bodyStreamWriter.Flush(); message.ContentStream = bodyStream; } /// <summary> /// each attachement is stored in its own MIME entity and read into this entity's /// ContentStream. SaveAttachment creates an attachment out of the ContentStream /// and attaches it to the parent MIME entity. /// </summary> private void SaveAttachment(RxMailMessage message) { if (message.Parent == null) { System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this } else { Attachment thisAttachment = new Attachment(message.ContentStream, message.ContentType); //no idea why ContentDisposition is read only. on the other hand, it is anyway redundant if (message.ContentDisposition != null) { ContentDisposition messageContentDisposition = message.ContentDisposition; ContentDisposition AttachmentContentDisposition = thisAttachment.ContentDisposition; if (messageContentDisposition.CreationDate > DateTime.MinValue) { AttachmentContentDisposition.CreationDate = messageContentDisposition.CreationDate; } AttachmentContentDisposition.DispositionType = messageContentDisposition.DispositionType; AttachmentContentDisposition.FileName = messageContentDisposition.FileName; AttachmentContentDisposition.Inline = messageContentDisposition.Inline; if (messageContentDisposition.ModificationDate > DateTime.MinValue) { AttachmentContentDisposition.ModificationDate = messageContentDisposition.ModificationDate; } AttachmentContentDisposition.Parameters.Clear(); if (messageContentDisposition.ReadDate > DateTime.MinValue) { AttachmentContentDisposition.ReadDate = messageContentDisposition.ReadDate; } if (messageContentDisposition.Size > 0) { AttachmentContentDisposition.Size = messageContentDisposition.Size; } foreach (string key in messageContentDisposition.Parameters.Keys) { AttachmentContentDisposition.Parameters.Add(key, messageContentDisposition.Parameters[key]); } } //get ContentId string contentIdString = message.ContentId; if (contentIdString != null) { thisAttachment.ContentId = RemoveBrackets(contentIdString); } thisAttachment.TransferEncoding = message.ContentTransferEncoding; message.Parent.Attachments.Add(thisAttachment); } } /// <summary> /// removes leading '&lt;' and trailing '&gt;' if both exist /// </summary> /// <param name="parameterString"></param> /// <returns></returns> private string RemoveBrackets(string parameterString) { if (parameterString == null) { return null; } if (parameterString.Length < 1 || parameterString[0] != '<' || parameterString[parameterString.Length - 1] != '>') { System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this return parameterString; } else { return parameterString.Substring(1, parameterString.Length - 2); } } private MimeEntityReturnCode ProcessDelimitedBody(RxMailMessage message, string BoundaryStart, string parentBoundaryStart, string parentBoundaryEnd) { string response = string.Empty; if (BoundaryStart.Trim() == parentBoundaryStart.Trim()) { //Mime entity boundaries have to be unique callGetEmailWarning("new boundary same as parent boundary: \'{0}\'", parentBoundaryStart); //empty this message while (readMultiLine(ref response)) { } return MimeEntityReturnCode.problem; } // MimeEntityReturnCode ReturnCode = new MimeEntityReturnCode(); do { //empty StringBuilder MimeEntitySB.Length = 0; RxMailMessage ChildPart = message.CreateChildEntity(); //recursively call MIME part processing ReturnCode = ProcessMimeEntity(ChildPart, BoundaryStart); if (ReturnCode == MimeEntityReturnCode.problem) { //it seems the received email doesn't follow the MIME specification. Stop here return MimeEntityReturnCode.problem; } //add the newly found child MIME part to the parent AddChildPartsToParent(ChildPart, message); } while (ReturnCode != MimeEntityReturnCode.parentBoundaryEndFound); //disregard all future lines until parent boundary is found or end of complete message MimeEntityReturnCode boundaryMimeReturnCode = new MimeEntityReturnCode(); bool hasParentBoundary = parentBoundaryStart.Length > 0; while (readMultiLine(ref response)) { if (hasParentBoundary && parentBoundaryFound(response, parentBoundaryStart, parentBoundaryEnd, ref boundaryMimeReturnCode)) { return boundaryMimeReturnCode; } } return MimeEntityReturnCode.bodyComplete; } /// <summary> /// Add all attachments and alternative views from child to the parent /// </summary> private void AddChildPartsToParent(RxMailMessage child, RxMailMessage parent) { //add the child itself to the parent parent.Entities.Add(child); //add the alternative views of the child to the parent if (child.AlternateViews != null) { foreach (AlternateView childView in child.AlternateViews) { parent.AlternateViews.Add(childView); } } //add the body of the child as alternative view to parent //this should be the last view attached here, because the POP 3 MIME client //is supposed to display the last alternative view if (child.MediaMainType == "text" && child.ContentStream != null&& child.Parent.ContentType != null&& child.Parent.ContentType.MediaType.ToLowerInvariant() == "multipart/alternative") { AlternateView thisAlternateView = new AlternateView(child.ContentStream); thisAlternateView.ContentId = RemoveBrackets(child.ContentId); thisAlternateView.ContentType = child.ContentType; thisAlternateView.TransferEncoding = child.ContentTransferEncoding; parent.AlternateViews.Add(thisAlternateView); } //add the attachments of the child to the parent if (child.Attachments != null) { foreach (Attachment childAttachment in child.Attachments) { parent.Attachments.Add(childAttachment); } } } /// <summary> /// Converts byte array to string, using decoding as requested /// </summary> public string DecodeByteArryToString(byte[] ByteArry, Encoding ByteEncoding) { if (ByteArry == null) { //no bytes to convert return null; } Decoder byteArryDecoder; if (ByteEncoding == null) { //no encoding indicated. Let's try UTF7 System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this byteArryDecoder = Encoding.UTF7.GetDecoder(); } else { byteArryDecoder = ByteEncoding.GetDecoder(); } int charCount = byteArryDecoder.GetCharCount(ByteArry, 0, ByteArry.Length); char[] bodyChars = new char[charCount - 1+ 1]; int charsDecodedCount = byteArryDecoder.GetChars(ByteArry, 0, ByteArry.Length, bodyChars, 0); //convert char[] to string return new string(bodyChars); } } } } }
// 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. // // Exposes features of the Garbage Collector to managed code. // using System; using System.Threading; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using Internal.Runtime.Augments; namespace System { // !!!!!!!!!!!!!!!!!!!!!!! // Make sure you change the def in rtu\gc.h if you change this! public enum GCCollectionMode { Default = 0, Forced = 1, Optimized = 2 } public enum GCNotificationStatus { Succeeded = 0, Failed = 1, Canceled = 2, Timeout = 3, NotApplicable = 4 } internal enum InternalGCCollectionMode { NonBlocking = 0x00000001, Blocking = 0x00000002, Optimized = 0x00000004, Compacting = 0x00000008, } internal enum StartNoGCRegionStatus { Succeeded = 0, NotEnoughMemory = 1, AmountTooLarge = 2, AlreadyInProgress = 3 } internal enum EndNoGCRegionStatus { Succeeded = 0, NotInProgress = 1, GCInduced = 2, AllocationExceeded = 3 } public static class GC { public static int GetGeneration(Object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } return RuntimeImports.RhGetGeneration(obj); } /// <summary> /// Returns the current generation number of the target /// of a specified <see cref="System.WeakReference"/>. /// </summary> /// <param name="wr">The WeakReference whose target is the object /// whose generation will be returned</param> /// <returns>The generation of the target of the WeakReference</returns> /// <exception cref="ArgumentNullException">The target of the weak reference /// has already been garbage collected.</exception> public static int GetGeneration(WeakReference wr) { // note - this throws an NRE if given a null weak reference. This isn't // documented, but it's the behavior of Desktop and CoreCLR. Object handleRef = RuntimeImports.RhHandleGet(wr.m_handle); if (handleRef == null) { throw new ArgumentNullException(nameof(wr)); } int result = RuntimeImports.RhGetGeneration(handleRef); KeepAlive(wr); return result; } // Forces a collection of all generations from 0 through Generation. public static void Collect(int generation) { Collect(generation, GCCollectionMode.Default); } // Garbage collect all generations. public static void Collect() { //-1 says to GC all generations. RuntimeImports.RhCollect(-1, InternalGCCollectionMode.Blocking); } public static void Collect(int generation, GCCollectionMode mode) { Collect(generation, mode, true); } public static void Collect(int generation, GCCollectionMode mode, bool blocking) { Collect(generation, mode, blocking, false); } public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting) { if (generation < 0) { throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); } if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized)) { throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum); } int iInternalModes = 0; if (mode == GCCollectionMode.Optimized) { iInternalModes |= (int)InternalGCCollectionMode.Optimized; } if (compacting) { iInternalModes |= (int)InternalGCCollectionMode.Compacting; } if (blocking) { iInternalModes |= (int)InternalGCCollectionMode.Blocking; } else if (!compacting) { iInternalModes |= (int)InternalGCCollectionMode.NonBlocking; } RuntimeImports.RhCollect(generation, (InternalGCCollectionMode)iInternalModes); } /// <summary> /// Specifies that a garbage collection notification should be raised when conditions are favorable /// for a full garbage collection and when the collection has been completed. /// </summary> /// <param name="maxGenerationThreshold">A number between 1 and 99 that specifies when the notification /// should be raised based on the objects allocated in Gen 2.</param> /// <param name="largeObjectHeapThreshold">A number between 1 and 99 that specifies when the notification /// should be raised based on the objects allocated in the large object heap.</param> /// <exception cref="ArgumentOutOfRangeException">If either of the two arguments are not between 1 and 99</exception> /// <exception cref="InvalidOperationException">If Concurrent GC is enabled</exception>" public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold) { if (maxGenerationThreshold < 1 || maxGenerationThreshold > 99) { throw new ArgumentOutOfRangeException( nameof(maxGenerationThreshold), String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } if (largeObjectHeapThreshold < 1 || largeObjectHeapThreshold > 99) { throw new ArgumentOutOfRangeException( nameof(largeObjectHeapThreshold), String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } // This is not documented on MSDN, but CoreCLR throws when the GC's // RegisterForFullGCNotification returns false if (!RuntimeImports.RhRegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold)) { throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC); } } /// <summary> /// Returns the status of a registered notification about whether a blocking garbage collection /// is imminent. May wait indefinitely for a full collection. /// </summary> /// <returns>The status of a registered full GC notification</returns> public static GCNotificationStatus WaitForFullGCApproach() { return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCApproach(-1); } /// <summary> /// Returns the status of a registered notification about whether a blocking garbage collection /// is imminent. May wait up to a given timeout for a full collection. /// </summary> /// <param name="millisecondsTimeout">The timeout on waiting for a full collection</param> /// <returns>The status of a registered full GC notification</returns> public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCApproach(millisecondsTimeout); } /// <summary> /// Returns the status of a registered notification about whether a blocking garbage collection /// has completed. May wait indefinitely for a full collection. /// </summary> /// <returns>The status of a registered full GC notification</returns> public static GCNotificationStatus WaitForFullGCComplete() { return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCComplete(-1); } /// <summary> /// Returns the status of a registered notification about whether a blocking garbage collection /// has completed. May wait up to a specified timeout for a full collection. /// </summary> /// <param name="millisecondsTimeout">The timeout on waiting for a full collection</param> /// <returns></returns> public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCComplete(millisecondsTimeout); } /// <summary> /// Cancels an outstanding full GC notification. /// </summary> /// <exception cref="InvalidOperationException">Raised if called /// with concurrent GC enabled</exception> public static void CancelFullGCNotification() { if (!RuntimeImports.RhCancelFullGCNotification()) { throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC); } } /// <summary> /// Attempts to disallow garbage collection during execution of a critical path. /// </summary> /// <param name="totalSize">Disallows garbage collection if a specified amount of /// of memory is available.</param> /// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns> /// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested /// is too large for the GC to accomodate</exception> /// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception> public static bool TryStartNoGCRegion(long totalSize) { return StartNoGCRegionWorker(totalSize, false, 0, false); } /// <summary> /// Attempts to disallow garbage collection during execution of a critical path. /// </summary> /// <param name="totalSize">Disallows garbage collection if a specified amount of /// of memory is available.</param> /// <param name="lohSize">Disallows garbagte collection if a specified amount of /// large object heap space is available.</param> /// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns> /// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested /// is too large for the GC to accomodate</exception> /// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception> public static bool TryStartNoGCRegion(long totalSize, long lohSize) { return StartNoGCRegionWorker(totalSize, true, lohSize, false); } /// <summary> /// Attempts to disallow garbage collection during execution of a critical path. /// </summary> /// <param name="totalSize">Disallows garbage collection if a specified amount of /// of memory is available.</param> /// <param name="disallowFullBlockingGC">Controls whether or not a full blocking GC /// is performed if the requested amount of memory is not available</param> /// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns> /// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested /// is too large for the GC to accomodate</exception> /// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception> public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC) { return StartNoGCRegionWorker(totalSize, false, 0, disallowFullBlockingGC); } /// <summary> /// Attempts to disallow garbage collection during execution of a critical path. /// </summary> /// <param name="totalSize">Disallows garbage collection if a specified amount of /// of memory is available.</param> /// <param name="lohSize">Disallows garbagte collection if a specified amount of /// large object heap space is available.</param> /// <param name="disallowFullBlockingGC">Controls whether or not a full blocking GC /// is performed if the requested amount of memory is not available</param> /// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns> /// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested /// is too large for the GC to accomodate</exception> /// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception> public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC) { return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC); } private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) { StartNoGCRegionStatus status = (StartNoGCRegionStatus)RuntimeImports.RhStartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC); if (status == StartNoGCRegionStatus.AmountTooLarge) { throw new ArgumentOutOfRangeException( nameof(totalSize), SR.ArgumentOutOfRangeException_NoGCRegionSizeTooLarge); } else if (status == StartNoGCRegionStatus.AlreadyInProgress) { throw new InvalidOperationException( SR.InvalidOperationException_AlreadyInNoGCRegion); } else if (status == StartNoGCRegionStatus.NotEnoughMemory) { return false; } return true; } /// <summary> /// Exits the current no GC region. /// </summary> /// <exception cref="InvalidOperationException">If the GC is not in a no GC region</exception> /// <exception cref="InvalidOperationException">If the no GC region was exited due to an induced GC</exception> /// <exception cref="InvalidOperationException">If the no GC region was exited due to memory allocations /// exceeding the amount given to <see cref="TryStartNoGCRegion(long)"/></exception> public static void EndNoGCRegion() { EndNoGCRegionStatus status = (EndNoGCRegionStatus)RuntimeImports.RhEndNoGCRegion(); if (status == EndNoGCRegionStatus.NotInProgress) { throw new InvalidOperationException( SR.InvalidOperationException_NoGCRegionNotInProgress); } else if (status == EndNoGCRegionStatus.GCInduced) { throw new InvalidOperationException( SR.InvalidOperationException_NoGCRegionInduced); } else if (status == EndNoGCRegionStatus.AllocationExceeded) { throw new InvalidOperationException( SR.InvalidOperationException_NoGCRegionAllocationExceeded); } } // Block until the next finalization pass is complete. public static void WaitForPendingFinalizers() { RuntimeImports.RhWaitForPendingFinalizers(RuntimeThread.ReentrantWaitsEnabled); } public static void SuppressFinalize(Object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } RuntimeImports.RhSuppressFinalize(obj); } public static void ReRegisterForFinalize(Object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); RuntimeImports.RhReRegisterForFinalize(obj); } [Intrinsic] [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations public static void KeepAlive(Object obj) { } // Returns the maximum GC generation. Currently assumes only 1 heap. // public static int MaxGeneration { get { return RuntimeImports.RhGetMaxGcGeneration(); } } public static int CollectionCount(int generation) { if (generation < 0) throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); return RuntimeImports.RhGetGcCollectionCount(generation, false); } // Support for AddMemoryPressure and RemoveMemoryPressure below. private const uint PressureCount = 4; #if BIT64 private const uint MinGCMemoryPressureBudget = 4 * 1024 * 1024; #else private const uint MinGCMemoryPressureBudget = 3 * 1024 * 1024; #endif private const uint MaxGCMemoryPressureRatio = 10; private static int[] s_gcCounts = new int[] { 0, 0, 0 }; private static long[] s_addPressure = new long[] { 0, 0, 0, 0 }; private static long[] s_removePressure = new long[] { 0, 0, 0, 0 }; private static uint s_iteration = 0; /// <summary> /// Resets the pressure accounting after a gen2 GC has occured. /// </summary> private static void CheckCollectionCount() { if (s_gcCounts[2] != CollectionCount(2)) { for (int i = 0; i < 3; i++) { s_gcCounts[i] = CollectionCount(i); } s_iteration++; uint p = s_iteration % PressureCount; s_addPressure[p] = 0; s_removePressure[p] = 0; } } private static long InterlockedAddMemoryPressure(ref long pAugend, long addend) { long oldMemValue; long newMemValue; do { oldMemValue = pAugend; newMemValue = oldMemValue + addend; // check for overflow if (newMemValue < oldMemValue) { newMemValue = long.MaxValue; } } while (Interlocked.CompareExchange(ref pAugend, newMemValue, oldMemValue) != oldMemValue); return newMemValue; } /// <summary> /// New AddMemoryPressure implementation (used by RCW and the CLRServicesImpl class) /// 1. Less sensitive than the original implementation (start budget 3 MB) /// 2. Focuses more on newly added memory pressure /// 3. Budget adjusted by effectiveness of last 3 triggered GC (add / remove ratio, max 10x) /// 4. Budget maxed with 30% of current managed GC size /// 5. If Gen2 GC is happening naturally, ignore past pressure /// /// Here's a brief description of the ideal algorithm for Add/Remove memory pressure: /// Do a GC when (HeapStart is less than X * MemPressureGrowth) where /// - HeapStart is GC Heap size after doing the last GC /// - MemPressureGrowth is the net of Add and Remove since the last GC /// - X is proportional to our guess of the ummanaged memory death rate per GC interval, /// and would be calculated based on historic data using standard exponential approximation: /// Xnew = UMDeath/UMTotal * 0.5 + Xprev /// </summary> /// <param name="bytesAllocated"></param> public static void AddMemoryPressure(long bytesAllocated) { if (bytesAllocated <= 0) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_NeedPosNum); } #if !BIT64 if (bytesAllocated > Int32.MaxValue) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); } #endif CheckCollectionCount(); uint p = s_iteration % PressureCount; long newMemValue = InterlockedAddMemoryPressure(ref s_addPressure[p], bytesAllocated); Debug.Assert(PressureCount == 4, "GC.AddMemoryPressure contains unrolled loops which depend on the PressureCount"); if (newMemValue >= MinGCMemoryPressureBudget) { long add = s_addPressure[0] + s_addPressure[1] + s_addPressure[2] + s_addPressure[3] - s_addPressure[p]; long rem = s_removePressure[0] + s_removePressure[1] + s_removePressure[2] + s_removePressure[3] - s_removePressure[p]; long budget = MinGCMemoryPressureBudget; if (s_iteration >= PressureCount) // wait until we have enough data points { // Adjust according to effectiveness of GC // Scale budget according to past m_addPressure / m_remPressure ratio if (add >= rem * MaxGCMemoryPressureRatio) { budget = MinGCMemoryPressureBudget * MaxGCMemoryPressureRatio; } else if (add > rem) { Debug.Assert(rem != 0); // Avoid overflow by calculating addPressure / remPressure as fixed point (1 = 1024) budget = (add * 1024 / rem) * budget / 1024; } } // If still over budget, check current managed heap size if (newMemValue >= budget) { long heapOver3 = RuntimeImports.RhGetCurrentObjSize() / 3; if (budget < heapOver3) //Max { budget = heapOver3; } if (newMemValue >= budget) { // last check - if we would exceed 20% of GC "duty cycle", do not trigger GC at this time if ((RuntimeImports.RhGetGCNow() - RuntimeImports.RhGetLastGCStartTime(2)) > (RuntimeImports.RhGetLastGCDuration(2) * 5)) { RuntimeImports.RhCollect(2, InternalGCCollectionMode.NonBlocking); CheckCollectionCount(); } } } } } public static void RemoveMemoryPressure(long bytesAllocated) { if (bytesAllocated <= 0) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_NeedPosNum); } #if !BIT64 if (bytesAllocated > Int32.MaxValue) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); } #endif CheckCollectionCount(); uint p = s_iteration % PressureCount; InterlockedAddMemoryPressure(ref s_removePressure[p], bytesAllocated); } public static long GetTotalMemory(bool forceFullCollection) { long size = RuntimeImports.RhGetGcTotalMemory(); if (forceFullCollection) { // If we force a full collection, we will run the finalizers on all // existing objects and do a collection until the value stabilizes. // The value is "stable" when either the value is within 5% of the // previous call to GetTotalMemory, or if we have been sitting // here for more than x times (we don't want to loop forever here). int reps = 20; // Number of iterations long diff; do { GC.WaitForPendingFinalizers(); GC.Collect(); long newSize = RuntimeImports.RhGetGcTotalMemory(); diff = (newSize - size) * 100 / size; size = newSize; } while (reps-- > 0 && !(-5 < diff && diff < 5)); } return size; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Parser.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Threading; using System.Threading.Tasks; namespace WOptiPNG { [System.ComponentModel.DesignerCategory("Code")] public class OptimizationService : ServiceBase { private readonly ConcurrentDictionary<FileSystemWatcher, WatchedDirectory> _watchers = new ConcurrentDictionary<FileSystemWatcher, WatchedDirectory>(); private Settings _settings; private readonly FileSystemWatcher _settingsWatcher; private readonly ThrottledMethodCall _settingsReloader; public OptimizationService() { LoadSettings(); var path = Settings.SettingsPath; _settingsWatcher = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path)); _settingsReloader = new ThrottledMethodCall(ReloadSettings, 500); _settingsWatcher.Changed += (sender, e) => _settingsReloader.Call(); _settingsWatcher.EnableRaisingEvents = true; } private void LoadSettings() { _settings = Settings.ReadFromFile(); if (!_settings.SettingsValid()) { var names = string.Join(", ", _settings.GetBrokenSettingsNames()); Program.WriteWindowsLog(string.Format("Some settings are broken ({0}), using defaults", names), EventLogEntryType.Warning); _settings.ResetBrokenSettings(); } } void ReloadSettings() { Program.WriteWindowsLog("Reloading settings",EventLogEntryType.Information); LoadSettings(); KillWatchers(); CreateWatchers(); KillThreads(); CreateThreads(_settings.ServiceThreads); } private void CreateWatchers() { if (_settings.WatchedFolders == null || _settings.WatchedFolders.Count == 0) { return; } foreach (var folder in _settings.WatchedFolders) { if (!Directory.Exists(folder.Path)) { Program.WriteWindowsLog(string.Format("Folder {0} not found", folder.Path), EventLogEntryType.Warning); continue; } //we assume that there won't be too many folders so this won't be too slow var canonicalPath = ToCanonicalPath(folder.Path); var alreadyWatched = _settings.WatchedFolders .Any(other => { if (other == folder) { return false; } var otherPath = ToCanonicalPath(other.Path); return canonicalPath == otherPath || (canonicalPath.StartsWith(otherPath) && other.WatchSubfolders); }); if (alreadyWatched) { var message = string.Format("Watching folder {0} from some other broader location", folder.Path); Program.WriteWindowsLog(message, EventLogEntryType.Warning); continue; } _watchers[CreatePngWatcher(folder.Path, folder.WatchSubfolders)] = folder; } } private void KillWatchers() { foreach (var watcher in _watchers.Keys) { watcher.Dispose(); } _watchers.Clear(); } protected override void OnStart(string[] args) { CreateWatchers(); CreateThreads(_settings.ServiceThreads); base.OnStart(args); } private readonly List<Thread> _backgroundThreads = new List<Thread>(); private void CreateThreads(int count) { for (int i = 0; i < count; i++) { var thread = new Thread(() => { while (true) { Monitor.Enter(_filesToProcess); string path = null; try { while (_filesQueue.Count == 0) Monitor.Wait(_filesToProcess); path = _filesQueue.Dequeue(); Monitor.Exit(_filesToProcess); int timeToWait; do { timeToWait = 500 - (int)(DateTime.UtcNow - File.GetLastWriteTimeUtc(path)).TotalMilliseconds; if (timeToWait <= 0 && IsFileLocked(path)) timeToWait = 500; if (timeToWait > 0) Thread.Sleep(timeToWait); } while (timeToWait > 0); try { ProcessFile(path, _settings); Trace.WriteLine(string.Format("Successfully optimized file {0}", path)); } catch (Exception e) { var message = string.Format("Error while processing files: {0}", e.Message); Program.WriteWindowsLog(message, EventLogEntryType.Error); } } finally { if (Monitor.IsEntered(_filesToProcess)) { if (path != null) _filesToProcess.Remove(path); Monitor.Exit(_filesToProcess); } else if (path != null) { lock (_filesToProcess) _filesToProcess.Remove(path); } } } }); _backgroundThreads.Add(thread); thread.Start(); } } protected virtual bool IsFileLocked(string path) { FileStream stream = null; try { stream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { return true; } finally { if (stream != null) stream.Close(); } return false; } private void KillThreads() { foreach (var thread in _backgroundThreads) { thread.Abort(); } _backgroundThreads.Clear(); } private static string ToCanonicalPath(string path) { return Path.GetFullPath(path).Replace('\\', '/').ToLowerInvariant(); } protected override void OnStop() { KillThreads(); KillWatchers(); _settingsWatcher.Dispose(); base.OnStop(); } private FileSystemWatcher CreatePngWatcher(string path, bool includeSubfolders) { var watcher = new FileSystemWatcher(path, "*.png"); watcher.Created += PngFileCreated; watcher.Error += FileWatcherError; watcher.IncludeSubdirectories = includeSubfolders; watcher.EnableRaisingEvents = true; return watcher; } private void FileWatcherError(object sender, ErrorEventArgs e) { var watcher = (FileSystemWatcher)sender; watcher.Dispose(); WatchedDirectory folder; if (_watchers.TryRemove(watcher, out folder)) { _watchers[CreatePngWatcher(folder.Path, folder.WatchSubfolders)] = folder; Trace.WriteLine(string.Format("Watcher error on folder {0}. Error: {1}", folder.Path, e.GetException().Message)); } else { Trace.WriteLine(string.Format("Couldn't remove watcher, error: {0}", e.GetException().Message)); } } private readonly Queue<string> _filesQueue = new Queue<string>(); private readonly HashSet<string> _filesToProcess = new HashSet<string>(); private void PngFileCreated(object sender, FileSystemEventArgs e) { lock (_filesToProcess) { if (_filesToProcess.Contains(e.FullPath)) return; _filesToProcess.Add(e.FullPath); _filesQueue.Enqueue(e.FullPath); Monitor.Pulse(_filesToProcess); } } private static void ProcessFile(string inputPath, Settings settings) { var tempFile = Path.GetTempFileName(); var sizeBefore = new FileInfo(inputPath).Length; try { File.Copy(inputPath, tempFile, true); var result = OptiPngWrapper.Optimize(tempFile, settings.ServiceOptLevel, settings.ServiceProcessPriority, null); if (result != 0) { return; } var newSize = new FileInfo(tempFile).Length; if (newSize >= sizeBefore) { return; } if (settings.OverwriteSource) { File.Copy(tempFile, inputPath, true); } else { var oldName = Path.GetFileName(inputPath); var newPath = Path.Combine(settings.OutputDirectory, oldName); if (!File.Exists(newPath)) { File.Copy(tempFile, newPath, false); } } } finally { File.Delete(tempFile); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using UnityEngine.EventSystems; using System.Collections.Generic; using HoloToolkit.Unity.InputModule; namespace HoloToolkit.Unity.Receivers { /// <summary> /// An interaction receiver is simply a component that attached to a list of interactable objects and does something /// based on events from those interactable objects. This is the base abstract class to extend from. /// </summary> public abstract class InteractionReceiver : MonoBehaviour, IInputHandler, IHoldHandler, IInputClickHandler, IManipulationHandler { #region Public Members /// <summary> /// List of linked interactable objects to receive events for /// </summary> [Tooltip("Target interactable Object to receive events for")] public List<GameObject> interactables = new List<GameObject>(); /// <summary> /// List of linked targets that the receiver affects /// </summary> [Tooltip("Targets for the receiver to ")] public List<GameObject> Targets = new List<GameObject>(); /// <summary> /// Flag for locking focus while selected /// </summary> public bool LockFocus { get { return lockFocus; } set { lockFocus = value; CheckLockFocus(_selectingFocuser); } } #endregion #region Private and Protected Members [Tooltip("If true, this object will remain the prime focus while select is held")] [SerializeField] private bool lockFocus = false; /// <summary> /// Protected focuser for the current selecting focuser /// </summary> protected IPointingSource _selectingFocuser; #endregion /// <summary> /// On start subscribe to all interaction events on elements in the interactables list. /// </summary> public virtual void OnEnable() { InputManager.Instance.AddGlobalListener(gameObject); FocusManager.Instance.PointerSpecificFocusChanged += OnPointerSpecificFocusChanged; } /// <summary> /// On disable remove all linked interactables from the delegate functions /// </summary> public virtual void OnDisable() { if (InputManager.IsInitialized) { InputManager.Instance.RemoveGlobalListener(gameObject); } if (FocusManager.IsInitialized) { FocusManager.Instance.PointerSpecificFocusChanged -= OnPointerSpecificFocusChanged; } } /// <summary> /// Register an interactable with this receiver. /// </summary> /// <param name="interactable">takes a GameObject as the interactable to register.</param> public virtual void Registerinteractable(GameObject interactable) { if (interactable == null || interactables.Contains(interactable)) { return; } interactables.Add(interactable); } #if UNITY_EDITOR /// <summary> /// When selected draw lines to all linked interactables /// </summary> protected virtual void OnDrawGizmosSelected() { if (this.interactables.Count > 0) { GameObject[] bioList = this.interactables.ToArray(); for (int i = 0; i < bioList.Length; i++) { if (bioList[i] != null) { Gizmos.color = Color.green; Gizmos.DrawLine(this.transform.position, bioList[i].transform.position); } } } if (this.Targets.Count > 0) { GameObject[] targetList = this.Targets.ToArray(); for (int i = 0; i < targetList.Length; i++) { if (targetList[i] != null) { Gizmos.color = Color.red; Gizmos.DrawLine(this.transform.position, targetList[i].transform.position); } } } } #endif /// <summary> /// Function to remove an interactable from the linked list. /// </summary> /// <param name="interactable"></param> public virtual void Removeinteractable(GameObject interactable) { if (interactable != null && interactables.Contains(interactable)) { interactables.Remove(interactable); } } /// <summary> /// Clear the interactables list and unregister them /// </summary> public virtual void Clearinteractables() { GameObject[] _intList = interactables.ToArray(); for (int i = 0; i < _intList.Length; i++) { this.Removeinteractable(_intList[i]); } } /// <summary> /// Is the game object interactable in our list of interactables /// </summary> /// <param name="interactable"></param> /// <returns></returns> protected bool Isinteractable(GameObject interactable) { return (interactables != null && interactables.Contains(interactable)); } private void CheckLockFocus(IPointingSource focuser) { // If our previous selecting focuser isn't the same if (_selectingFocuser != null && _selectingFocuser != focuser) { // If our focus is currently locked, unlock it before moving on if (LockFocus) { _selectingFocuser.FocusLocked = false; } } // Set to the new focuser _selectingFocuser = focuser; if (_selectingFocuser != null) { _selectingFocuser.FocusLocked = LockFocus; } } private void LockFocuser(IPointingSource focuser) { if (focuser != null) { ReleaseFocuser(); _selectingFocuser = focuser; _selectingFocuser.FocusLocked = true; } } private void ReleaseFocuser() { if (_selectingFocuser != null) { _selectingFocuser.FocusLocked = false; _selectingFocuser = null; } } /// <summary> /// Handle the pointer specific changes to fire focus enter and exit events /// </summary> /// <param name="pointer">The pointer associated with this focus change.</param> /// <param name="oldFocusedObject">Object that was previously being focused.</param> /// <param name="newFocusedObject">New object being focused.</param> private void OnPointerSpecificFocusChanged(IPointingSource pointer, GameObject oldFocusedObject, GameObject newFocusedObject) { PointerSpecificEventData eventData = new PointerSpecificEventData(EventSystem.current); eventData.Initialize(pointer); if (newFocusedObject != null && Isinteractable(newFocusedObject)) { FocusEnter(newFocusedObject, eventData); } if (oldFocusedObject != null && Isinteractable(oldFocusedObject)) { FocusExit(oldFocusedObject, eventData); } CheckLockFocus(pointer); } #region Global Listener Callbacks public void OnInputDown(InputEventData eventData) { if (Isinteractable(eventData.selectedObject)) { InputDown(eventData.selectedObject, eventData); } } public void OnInputUp(InputEventData eventData) { if (Isinteractable(eventData.selectedObject)) { InputUp(eventData.selectedObject, eventData); } } public void OnInputClicked(InputClickedEventData eventData) { if (Isinteractable(eventData.selectedObject)) { InputClicked(eventData.selectedObject, eventData); } } public void OnHoldStarted(HoldEventData eventData) { if (Isinteractable(eventData.selectedObject)) { HoldStarted(eventData.selectedObject, eventData); } } public void OnHoldCompleted(HoldEventData eventData) { if (Isinteractable(eventData.selectedObject)) { HoldCompleted(eventData.selectedObject, eventData); } } public void OnHoldCanceled(HoldEventData eventData) { if (Isinteractable(eventData.selectedObject)) { HoldCanceled(eventData.selectedObject, eventData); } } public void OnManipulationStarted(ManipulationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { ManipulationStarted(eventData.selectedObject, eventData); } } public void OnManipulationUpdated(ManipulationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { ManipulationUpdated(eventData.selectedObject, eventData); } } public void OnManipulationCompleted(ManipulationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { ManipulationCompleted(eventData.selectedObject, eventData); } } public void OnManipulationCanceled(ManipulationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { ManipulationCanceled(eventData.selectedObject, eventData); } } public void OnNavigationStarted(NavigationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { NavigationStarted(eventData.selectedObject, eventData); } } public void OnNavigationUpdated(NavigationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { NavigationUpdated(eventData.selectedObject, eventData); } } public void OnNavigationCompleted(NavigationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { NavigationCompleted(eventData.selectedObject, eventData); } } public void OnNavigationCanceled(NavigationEventData eventData) { if (Isinteractable(eventData.selectedObject)) { NavigationCanceled(eventData.selectedObject, eventData); } } #endregion #region Protected Virtual Callback Functions protected virtual void FocusEnter(GameObject obj, PointerSpecificEventData eventData) { } protected virtual void FocusExit(GameObject obj, PointerSpecificEventData eventData) { } protected virtual void InputDown(GameObject obj, InputEventData eventData) { } protected virtual void InputUp(GameObject obj, InputEventData eventData) { } protected virtual void InputClicked(GameObject obj, InputClickedEventData eventData) { } protected virtual void HoldStarted(GameObject obj, HoldEventData eventData) { } protected virtual void HoldCompleted(GameObject obj, HoldEventData eventData) { } protected virtual void HoldCanceled(GameObject obj, HoldEventData eventData) { } protected virtual void ManipulationStarted(GameObject obj, ManipulationEventData eventData) { } protected virtual void ManipulationUpdated(GameObject obj, ManipulationEventData eventData) { } protected virtual void ManipulationCompleted(GameObject obj, ManipulationEventData eventData) { } protected virtual void ManipulationCanceled(GameObject obj, ManipulationEventData eventData) { } protected virtual void NavigationStarted(GameObject obj, NavigationEventData eventData) { } protected virtual void NavigationUpdated(GameObject obj, NavigationEventData eventData) { } protected virtual void NavigationCompleted(GameObject obj, NavigationEventData eventData) { } protected virtual void NavigationCanceled(GameObject obj, NavigationEventData eventData) { } #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.Text; namespace Internal.JitInterface { // CorInfoHelpFunc defines the set of helpers (accessed via the ICorDynamicInfo::getHelperFtn()) // These helpers can be called by native code which executes in the runtime. // Compilers can emit calls to these helpers. public enum CorInfoHelpFunc { CORINFO_HELP_UNDEF, // invalid value. This should never be used /* Arithmetic helpers */ CORINFO_HELP_DIV, // For the ARM 32-bit integer divide uses a helper call :-( CORINFO_HELP_MOD, CORINFO_HELP_UDIV, CORINFO_HELP_UMOD, CORINFO_HELP_LLSH, CORINFO_HELP_LRSH, CORINFO_HELP_LRSZ, CORINFO_HELP_LMUL, CORINFO_HELP_LMUL_OVF, CORINFO_HELP_ULMUL_OVF, CORINFO_HELP_LDIV, CORINFO_HELP_LMOD, CORINFO_HELP_ULDIV, CORINFO_HELP_ULMOD, CORINFO_HELP_LNG2DBL, // Convert a signed int64 to a double CORINFO_HELP_ULNG2DBL, // Convert a unsigned int64 to a double CORINFO_HELP_DBL2INT, CORINFO_HELP_DBL2INT_OVF, CORINFO_HELP_DBL2LNG, CORINFO_HELP_DBL2LNG_OVF, CORINFO_HELP_DBL2UINT, CORINFO_HELP_DBL2UINT_OVF, CORINFO_HELP_DBL2ULNG, CORINFO_HELP_DBL2ULNG_OVF, CORINFO_HELP_FLTREM, CORINFO_HELP_DBLREM, CORINFO_HELP_FLTROUND, CORINFO_HELP_DBLROUND, /* Allocating a new object. Always use ICorClassInfo::getNewHelper() to decide which is the right helper to use to allocate an object of a given type. */ CORINFO_HELP_NEW_CROSSCONTEXT, // cross context new object CORINFO_HELP_NEWFAST, CORINFO_HELP_NEWSFAST, // allocator for small, non-finalizer, non-array object CORINFO_HELP_NEWSFAST_ALIGN8, // allocator for small, non-finalizer, non-array object, 8 byte aligned CORINFO_HELP_NEW_MDARR, // multi-dim array helper (with or without lower bounds - dimensions passed in as vararg) CORINFO_HELP_NEW_MDARR_NONVARARG,// multi-dim array helper (with or without lower bounds - dimensions passed in as unmanaged array) CORINFO_HELP_NEWARR_1_DIRECT, // helper for any one dimensional array creation CORINFO_HELP_NEWARR_1_R2R_DIRECT, // wrapper for R2R direct call, which extracts method table from ArrayTypeDesc CORINFO_HELP_NEWARR_1_OBJ, // optimized 1-D object arrays CORINFO_HELP_NEWARR_1_VC, // optimized 1-D value class arrays CORINFO_HELP_NEWARR_1_ALIGN8, // like VC, but aligns the array start CORINFO_HELP_STRCNS, // create a new string literal CORINFO_HELP_STRCNS_CURRENT_MODULE, // create a new string literal from the current module (used by NGen code) /* Object model */ CORINFO_HELP_INITCLASS, // Initialize class if not already initialized CORINFO_HELP_INITINSTCLASS, // Initialize class for instantiated type // Use ICorClassInfo::getCastingHelper to determine // the right helper to use CORINFO_HELP_ISINSTANCEOFINTERFACE, // Optimized helper for interfaces CORINFO_HELP_ISINSTANCEOFARRAY, // Optimized helper for arrays CORINFO_HELP_ISINSTANCEOFCLASS, // Optimized helper for classes CORINFO_HELP_ISINSTANCEOFANY, // Slow helper for any type CORINFO_HELP_CHKCASTINTERFACE, CORINFO_HELP_CHKCASTARRAY, CORINFO_HELP_CHKCASTCLASS, CORINFO_HELP_CHKCASTANY, CORINFO_HELP_CHKCASTCLASS_SPECIAL, // Optimized helper for classes. Assumes that the trivial cases // has been taken care of by the inlined check CORINFO_HELP_BOX, CORINFO_HELP_BOX_NULLABLE, // special form of boxing for Nullable<T> CORINFO_HELP_UNBOX, CORINFO_HELP_UNBOX_NULLABLE, // special form of unboxing for Nullable<T> CORINFO_HELP_GETREFANY, // Extract the byref from a TypedReference, checking that it is the expected type CORINFO_HELP_ARRADDR_ST, // assign to element of object array with type-checking CORINFO_HELP_LDELEMA_REF, // does a precise type comparision and returns address /* Exceptions */ CORINFO_HELP_THROW, // Throw an exception object CORINFO_HELP_RETHROW, // Rethrow the currently active exception CORINFO_HELP_USER_BREAKPOINT, // For a user program to break to the debugger CORINFO_HELP_RNGCHKFAIL, // array bounds check failed CORINFO_HELP_OVERFLOW, // throw an overflow exception CORINFO_HELP_THROWDIVZERO, // throw a divide by zero exception CORINFO_HELP_THROWNULLREF, // throw a null reference exception CORINFO_HELP_INTERNALTHROW, // Support for really fast jit CORINFO_HELP_VERIFICATION, // Throw a VerificationException CORINFO_HELP_SEC_UNMGDCODE_EXCPT, // throw a security unmanaged code exception CORINFO_HELP_FAIL_FAST, // Kill the process avoiding any exceptions or stack and data dependencies (use for GuardStack unsafe buffer checks) CORINFO_HELP_METHOD_ACCESS_EXCEPTION,//Throw an access exception due to a failed member/class access check. CORINFO_HELP_FIELD_ACCESS_EXCEPTION, CORINFO_HELP_CLASS_ACCESS_EXCEPTION, CORINFO_HELP_ENDCATCH, // call back into the EE at the end of a catch block /* Synchronization */ CORINFO_HELP_MON_ENTER, CORINFO_HELP_MON_EXIT, CORINFO_HELP_MON_ENTER_STATIC, CORINFO_HELP_MON_EXIT_STATIC, CORINFO_HELP_GETCLASSFROMMETHODPARAM, // Given a generics method handle, returns a class handle CORINFO_HELP_GETSYNCFROMCLASSHANDLE, // Given a generics class handle, returns the sync monitor // in its ManagedClassObject /* Security callout support */ CORINFO_HELP_SECURITY_PROLOG, // Required if CORINFO_FLG_SECURITYCHECK is set, or CORINFO_FLG_NOSECURITYWRAP is not set CORINFO_HELP_SECURITY_PROLOG_FRAMED, // Slow version of CORINFO_HELP_SECURITY_PROLOG. Used for instrumentation. CORINFO_HELP_METHOD_ACCESS_CHECK, // Callouts to runtime security access checks CORINFO_HELP_FIELD_ACCESS_CHECK, CORINFO_HELP_CLASS_ACCESS_CHECK, CORINFO_HELP_DELEGATE_SECURITY_CHECK, // Callout to delegate security transparency check /* Verification runtime callout support */ CORINFO_HELP_VERIFICATION_RUNTIME_CHECK, // Do a Demand for UnmanagedCode permission at runtime /* GC support */ CORINFO_HELP_STOP_FOR_GC, // Call GC (force a GC) CORINFO_HELP_POLL_GC, // Ask GC if it wants to collect CORINFO_HELP_STRESS_GC, // Force a GC, but then update the JITTED code to be a noop call CORINFO_HELP_CHECK_OBJ, // confirm that ECX is a valid object pointer (debugging only) /* GC Write barrier support */ CORINFO_HELP_ASSIGN_REF, // universal helpers with F_CALL_CONV calling convention CORINFO_HELP_CHECKED_ASSIGN_REF, CORINFO_HELP_ASSIGN_REF_ENSURE_NONHEAP, // Do the store, and ensure that the target was not in the heap. CORINFO_HELP_ASSIGN_BYREF, CORINFO_HELP_ASSIGN_STRUCT, /* Accessing fields */ // For COM object support (using COM get/set routines to update object) // and EnC and cross-context support CORINFO_HELP_GETFIELD8, CORINFO_HELP_SETFIELD8, CORINFO_HELP_GETFIELD16, CORINFO_HELP_SETFIELD16, CORINFO_HELP_GETFIELD32, CORINFO_HELP_SETFIELD32, CORINFO_HELP_GETFIELD64, CORINFO_HELP_SETFIELD64, CORINFO_HELP_GETFIELDOBJ, CORINFO_HELP_SETFIELDOBJ, CORINFO_HELP_GETFIELDSTRUCT, CORINFO_HELP_SETFIELDSTRUCT, CORINFO_HELP_GETFIELDFLOAT, CORINFO_HELP_SETFIELDFLOAT, CORINFO_HELP_GETFIELDDOUBLE, CORINFO_HELP_SETFIELDDOUBLE, CORINFO_HELP_GETFIELDADDR, CORINFO_HELP_GETSTATICFIELDADDR_CONTEXT, // Helper for context-static fields CORINFO_HELP_GETSTATICFIELDADDR_TLS, // Helper for PE TLS fields // There are a variety of specialized helpers for accessing static fields. The JIT should use // ICorClassInfo::getSharedStaticsOrCCtorHelper to determine which helper to use // Helpers for regular statics CORINFO_HELP_GETGENERICS_GCSTATIC_BASE, CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE, CORINFO_HELP_GETSHARED_GCSTATIC_BASE, CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE, CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR, CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR, CORINFO_HELP_GETSHARED_GCSTATIC_BASE_DYNAMICCLASS, CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_DYNAMICCLASS, // Helper to class initialize shared generic with dynamicclass, but not get static field address CORINFO_HELP_CLASSINIT_SHARED_DYNAMICCLASS, // Helpers for thread statics CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE, CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE, CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE, CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE, CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_NOCTOR, CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_NOCTOR, CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_DYNAMICCLASS, CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_DYNAMICCLASS, /* Debugger */ CORINFO_HELP_DBG_IS_JUST_MY_CODE, // Check if this is "JustMyCode" and needs to be stepped through. /* Profiling enter/leave probe addresses */ CORINFO_HELP_PROF_FCN_ENTER, // record the entry to a method (caller) CORINFO_HELP_PROF_FCN_LEAVE, // record the completion of current method (caller) CORINFO_HELP_PROF_FCN_TAILCALL, // record the completionof current method through tailcall (caller) /* Miscellaneous */ CORINFO_HELP_BBT_FCN_ENTER, // record the entry to a method for collecting Tuning data CORINFO_HELP_PINVOKE_CALLI, // Indirect pinvoke call CORINFO_HELP_TAILCALL, // Perform a tail call CORINFO_HELP_GETCURRENTMANAGEDTHREADID, CORINFO_HELP_INIT_PINVOKE_FRAME, // initialize an inlined PInvoke Frame for the JIT-compiler CORINFO_HELP_MEMSET, // Init block of memory CORINFO_HELP_MEMCPY, // Copy block of memory CORINFO_HELP_RUNTIMEHANDLE_METHOD, // determine a type/field/method handle at run-time CORINFO_HELP_RUNTIMEHANDLE_METHOD_LOG,// determine a type/field/method handle at run-time, with IBC logging CORINFO_HELP_RUNTIMEHANDLE_CLASS, // determine a type/field/method handle at run-time CORINFO_HELP_RUNTIMEHANDLE_CLASS_LOG,// determine a type/field/method handle at run-time, with IBC logging // These helpers are required for MDIL backward compatibility only. They are not used by current JITed code. CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPEHANDLE_OBSOLETE, // Convert from a TypeHandle (native structure pointer) to RuntimeTypeHandle at run-time CORINFO_HELP_METHODDESC_TO_RUNTIMEMETHODHANDLE_OBSOLETE, // Convert from a MethodDesc (native structure pointer) to RuntimeMethodHandle at run-time CORINFO_HELP_FIELDDESC_TO_RUNTIMEFIELDHANDLE_OBSOLETE, // Convert from a FieldDesc (native structure pointer) to RuntimeFieldHandle at run-time CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE_MAYBENULL, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time, the type may be null CORINFO_HELP_METHODDESC_TO_STUBRUNTIMEMETHOD, // Convert from a MethodDesc (native structure pointer) to RuntimeMethodHandle at run-time CORINFO_HELP_FIELDDESC_TO_STUBRUNTIMEFIELD, // Convert from a FieldDesc (native structure pointer) to RuntimeFieldHandle at run-time CORINFO_HELP_VIRTUAL_FUNC_PTR, // look up a virtual method at run-time //CORINFO_HELP_VIRTUAL_FUNC_PTR_LOG, // look up a virtual method at run-time, with IBC logging // Not a real helpers. Instead of taking handle arguments, these helpers point to a small stub that loads the handle argument and calls the static helper. CORINFO_HELP_READYTORUN_NEW, CORINFO_HELP_READYTORUN_NEWARR_1, CORINFO_HELP_READYTORUN_ISINSTANCEOF, CORINFO_HELP_READYTORUN_CHKCAST, CORINFO_HELP_READYTORUN_STATIC_BASE, CORINFO_HELP_READYTORUN_VIRTUAL_FUNC_PTR, CORINFO_HELP_READYTORUN_GENERIC_HANDLE, CORINFO_HELP_READYTORUN_DELEGATE_CTOR, CORINFO_HELP_READYTORUN_GENERIC_STATIC_BASE, CORINFO_HELP_EE_PRESTUB, // Not real JIT helper. Used in native images. CORINFO_HELP_EE_PRECODE_FIXUP, // Not real JIT helper. Used for Precode fixup in native images. CORINFO_HELP_EE_PINVOKE_FIXUP, // Not real JIT helper. Used for PInvoke target fixup in native images. CORINFO_HELP_EE_VSD_FIXUP, // Not real JIT helper. Used for VSD cell fixup in native images. CORINFO_HELP_EE_EXTERNAL_FIXUP, // Not real JIT helper. Used for to fixup external method thunks in native images. CORINFO_HELP_EE_VTABLE_FIXUP, // Not real JIT helper. Used for inherited vtable slot fixup in native images. CORINFO_HELP_EE_REMOTING_THUNK, // Not real JIT helper. Used for remoting precode in native images. CORINFO_HELP_EE_PERSONALITY_ROUTINE,// Not real JIT helper. Used in native images. CORINFO_HELP_EE_PERSONALITY_ROUTINE_FILTER_FUNCLET,// Not real JIT helper. Used in native images to detect filter funclets. // ASSIGN_REF_EAX - CHECKED_ASSIGN_REF_EBP: NOGC_WRITE_BARRIERS JIT helper calls // // For unchecked versions EDX is required to point into GC heap. // // NOTE: these helpers are only used for x86. CORINFO_HELP_ASSIGN_REF_EAX, // EAX holds GC ptr, do a 'mov [EDX], EAX' and inform GC CORINFO_HELP_ASSIGN_REF_EBX, // EBX holds GC ptr, do a 'mov [EDX], EBX' and inform GC CORINFO_HELP_ASSIGN_REF_ECX, // ECX holds GC ptr, do a 'mov [EDX], ECX' and inform GC CORINFO_HELP_ASSIGN_REF_ESI, // ESI holds GC ptr, do a 'mov [EDX], ESI' and inform GC CORINFO_HELP_ASSIGN_REF_EDI, // EDI holds GC ptr, do a 'mov [EDX], EDI' and inform GC CORINFO_HELP_ASSIGN_REF_EBP, // EBP holds GC ptr, do a 'mov [EDX], EBP' and inform GC CORINFO_HELP_CHECKED_ASSIGN_REF_EAX, // These are the same as ASSIGN_REF above ... CORINFO_HELP_CHECKED_ASSIGN_REF_EBX, // ... but also check if EDX points into heap. CORINFO_HELP_CHECKED_ASSIGN_REF_ECX, CORINFO_HELP_CHECKED_ASSIGN_REF_ESI, CORINFO_HELP_CHECKED_ASSIGN_REF_EDI, CORINFO_HELP_CHECKED_ASSIGN_REF_EBP, CORINFO_HELP_LOOP_CLONE_CHOICE_ADDR, // Return the reference to a counter to decide to take cloned path in debug stress. CORINFO_HELP_DEBUG_LOG_LOOP_CLONING, // Print a message that a loop cloning optimization has occurred in debug mode. CORINFO_HELP_THROW_ARGUMENTEXCEPTION, // throw ArgumentException CORINFO_HELP_THROW_ARGUMENTOUTOFRANGEEXCEPTION, // throw ArgumentOutOfRangeException CORINFO_HELP_THROW_PLATFORM_NOT_SUPPORTED, // throw PlatformNotSupportedException CORINFO_HELP_THROW_TYPE_NOT_SUPPORTED, // throw TypeNotSupportedException CORINFO_HELP_JIT_PINVOKE_BEGIN, // Transition to preemptive mode before a P/Invoke, frame is the first argument CORINFO_HELP_JIT_PINVOKE_END, // Transition to cooperative mode after a P/Invoke, frame is the first argument CORINFO_HELP_JIT_REVERSE_PINVOKE_ENTER, // Transition to cooperative mode in reverse P/Invoke prolog, frame is the first argument CORINFO_HELP_JIT_REVERSE_PINVOKE_EXIT, // Transition to preemptive mode in reverse P/Invoke epilog, frame is the first argument CORINFO_HELP_GVMLOOKUP_FOR_SLOT, // Resolve a generic virtual method target from this pointer and runtime method handle CORINFO_HELP_COUNT, } }
// 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 Microsoft.CodeDom; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Security; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.Text; using Microsoft.Xml; namespace Microsoft.Tools.ServiceModel.Svcutil { internal class MethodCreationHelper { public MethodCreationHelper(CodeTypeDeclaration clientType) { this.ClientType = clientType; this.GetEndpointAddress = new CodeMemberMethod { Name = ConfigToCodeConstants.GetEndpointAddressMethod, Attributes = MemberAttributes.Private | MemberAttributes.Static, ReturnType = new CodeTypeReference(typeof(EndpointAddress)), }; this.GetEndpointAddress.Parameters.Add(new CodeParameterDeclarationExpression(ConfigToCodeConstants.EndpointConfigurationEnumTypeName, ConfigToCodeConstants.EndpointConfigurationParameter)); this.GetBinding = new CodeMemberMethod { Name = ConfigToCodeConstants.GetBindingMethod, Attributes = MemberAttributes.Private | MemberAttributes.Static, ReturnType = new CodeTypeReference(typeof(Binding)), }; this.GetBinding.Parameters.Add(new CodeParameterDeclarationExpression(ConfigToCodeConstants.EndpointConfigurationEnumTypeName, ConfigToCodeConstants.EndpointConfigurationParameter)); } private CodeTypeDeclaration ClientType { get; set; } private CodeMemberMethod GetEndpointAddress { get; set; } private CodeMemberMethod GetBinding { get; set; } private CodeMemberMethod GetDefaultEndpointAddress { get; set; } private CodeMemberMethod GetDefaultBinding { get; set; } public bool AddClientEndpoint(ServiceEndpoint endpoint) { string endpointAddress = endpoint?.Address?.ToString(); if (!string.IsNullOrEmpty(endpointAddress)) { this.AddNewEndpointAddress(endpoint.Name, endpointAddress, endpoint); this.AddNewBinding(endpoint.Name, endpoint.Binding); return true; } return false; } public void AddConfigurationEnum(List<string> endpointNames) { CodeTypeDeclaration configurationsEnum = new CodeTypeDeclaration(ConfigToCodeConstants.EndpointConfigurationEnumTypeName); configurationsEnum.IsEnum = true; foreach (string endpointName in endpointNames) { configurationsEnum.Members.Add(new CodeMemberField(ConfigToCodeConstants.EndpointConfigurationEnumTypeName, CodeDomHelpers.EscapeName(endpointName))); } this.ClientType.Members.Add(configurationsEnum); } public void AddMethods(List<string> endpointNames, bool isVB) { this.AddFinalThrowStatement(); this.ClientType.Members.Add(this.GetBinding); this.ClientType.Members.Add(this.GetEndpointAddress); // Only single endpoint support getting default binding and endpoint address. if (endpointNames.Count == 1) { this.CreateDefaultEndpointMethods(this.ClientType.Name, endpointNames); this.ClientType.Members.Add(this.GetDefaultBinding); this.ClientType.Members.Add(this.GetDefaultEndpointAddress); } this.AddConfigureEndpoint(isVB); } private void AddConfigureEndpoint(bool isVB) { string indent = " "; if (this.ClientType.UserData.Contains("Namespace")) { CodeNamespace ns = this.ClientType.UserData["Namespace"] as CodeNamespace; if (!string.IsNullOrEmpty(ns?.Name)) { indent += indent; } } CodeSnippetTypeMember snippet; string comment = indent + "{0} <summary>" + Environment.NewLine + indent + "{0} " + SR.ConfigureEndpointCommentSummary + Environment.NewLine + indent + "{0} </summary>" + Environment.NewLine + indent + "{0} <param name=\"serviceEndpoint\">" + SR.ServiceEndpointComment + "</param>" + Environment.NewLine + indent + "{0} <param name=\"clientCredentials\">" + SR.ClientCredentialsComment + "</param>" + Environment.NewLine; if (!isVB) { snippet = new CodeSnippetTypeMember( string.Format(CultureInfo.InvariantCulture, comment, "///") + indent + "static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials);"); } else { snippet = new CodeSnippetTypeMember( string.Format(CultureInfo.InvariantCulture, comment, "'''") + indent + "Partial Private Shared Sub ConfigureEndpoint(ByVal serviceEndpoint As System.ServiceModel.Description.ServiceEndpoint, ByVal clientCredentials As System.ServiceModel.Description.ClientCredentials)" + Environment.NewLine + indent + "End Sub"); } this.ClientType.Members.Add(snippet); } private void AddNewBinding(string endpointConfigurationName, Binding binding) { CodeConditionStatement condition = new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeArgumentReferenceExpression(ConfigToCodeConstants.EndpointConfigurationParameter), CodeBinaryOperatorType.ValueEquality, new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(ConfigToCodeConstants.EndpointConfigurationEnumTypeName), endpointConfigurationName))); this.GetBinding.Statements.Add(condition); AddBindingConfiguration(condition.TrueStatements, binding); } private static void AddBindingConfiguration(CodeStatementCollection statements, Binding binding) { BasicHttpBinding basicHttp = binding as BasicHttpBinding; if (basicHttp != null) { AddBasicHttpBindingConfiguration(statements, basicHttp); return; } NetHttpBinding netHttp = binding as NetHttpBinding; if (netHttp != null) { AddNetHttpBindingConfiguration(statements, netHttp); return; } NetTcpBinding netTcp = binding as NetTcpBinding; if (netTcp != null) { AddNetTcpBindingConfiguration(statements, netTcp); return; } CustomBinding custom = binding as CustomBinding; if (custom != null) { AddCustomBindingConfiguration(statements, custom); return; } WSHttpBinding httpBinding = binding as WSHttpBinding; if (httpBinding != null) { AddCustomBindingConfiguration(statements, new CustomBinding(httpBinding)); return; } throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ErrBindingTypeNotSupportedFormat, binding.GetType().FullName)); } private static void AddCustomBindingConfiguration(CodeStatementCollection statements, CustomBinding custom) { const string ResultVarName = "result"; statements.Add( new CodeVariableDeclarationStatement( typeof(CustomBinding), ResultVarName, new CodeObjectCreateExpression(typeof(CustomBinding)))); CodeVariableReferenceExpression resultVar = new CodeVariableReferenceExpression(ResultVarName); foreach (BindingElement bindingElement in custom.Elements) { bool handled = false; TextMessageEncodingBindingElement textBE = bindingElement as TextMessageEncodingBindingElement; if (textBE != null) { AddTextBindingElement(statements, resultVar, textBE); handled = true; } if (!handled) { BinaryMessageEncodingBindingElement binaryBE = bindingElement as BinaryMessageEncodingBindingElement; if (binaryBE != null) { AddBinaryBindingElement(statements, resultVar); handled = true; } } if (!handled) { HttpTransportBindingElement httpTE = bindingElement as HttpTransportBindingElement; if (httpTE != null) { AddHttpBindingElement(statements, resultVar, httpTE); handled = true; } } if (!handled) { TcpTransportBindingElement tcpTE = bindingElement as TcpTransportBindingElement; if (tcpTE != null) { AddTcpBindingElement(statements, resultVar, tcpTE); handled = true; } } if (!handled) { TransportSecurityBindingElement transportSE = bindingElement as TransportSecurityBindingElement; if (transportSE != null) { AddTransportSecurityBindingElement(statements, resultVar, transportSE); handled = true; } } if (!handled) { TransactionFlowBindingElement transactionBE = bindingElement as TransactionFlowBindingElement; if (transactionBE != null) { // if transaction is enabled, the binding should have been filtered before. Nothing to do here. handled = true; } } if (!handled) { SslStreamSecurityBindingElement sslStreamSE = bindingElement as SslStreamSecurityBindingElement; if (sslStreamSE != null) { AddSslStreamSecurityBindingElement(statements, resultVar); handled = true; } } if (!handled) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ErrBindingElementNotSupportedFormat, bindingElement.GetType().FullName)); } } statements.Add(new CodeMethodReturnStatement(resultVar)); } private static void AddSslStreamSecurityBindingElement(CodeStatementCollection statements, CodeVariableReferenceExpression customBinding) { statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( customBinding, "Elements"), "Add", new CodeObjectCreateExpression(typeof(SslStreamSecurityBindingElement)))); } private static void AddTransportSecurityBindingElement(CodeStatementCollection statements, CodeVariableReferenceExpression customBinding, TransportSecurityBindingElement bindingElement) { // Security binding validation is done in EndpointSelector.cs - Add UserNameOverTransportBindingElement TransportSecurityBindingElement defaultBindingElement = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); CodeVariableDeclarationStatement userNameOverTransportSecurityBindingElement = new CodeVariableDeclarationStatement( typeof(TransportSecurityBindingElement), "userNameOverTransportSecurityBindingElement", new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(SecurityBindingElement)), "CreateUserNameOverTransportBindingElement")); statements.Add(userNameOverTransportSecurityBindingElement); CodeVariableReferenceExpression bindingElementRef = new CodeVariableReferenceExpression(userNameOverTransportSecurityBindingElement.Name); if (defaultBindingElement.IncludeTimestamp != bindingElement.IncludeTimestamp) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "IncludeTimestamp"), new CodePrimitiveExpression(bindingElement.IncludeTimestamp))); } if (defaultBindingElement.LocalClientSettings.MaxClockSkew != bindingElement.LocalClientSettings.MaxClockSkew) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(bindingElementRef, "LocalClientSettings"), "MaxClockSkew"), CreateTimeSpanExpression(bindingElement.LocalClientSettings.MaxClockSkew))); } if (defaultBindingElement.LocalClientSettings.ReplayWindow != bindingElement.LocalClientSettings.ReplayWindow) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(bindingElementRef, "LocalClientSettings"), "ReplayWindow"), CreateTimeSpanExpression(bindingElement.LocalClientSettings.ReplayWindow))); } if (defaultBindingElement.LocalClientSettings.TimestampValidityDuration != bindingElement.LocalClientSettings.TimestampValidityDuration) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(bindingElementRef, "LocalClientSettings"), "TimestampValidityDuration"), CreateTimeSpanExpression(bindingElement.LocalClientSettings.TimestampValidityDuration))); } if (defaultBindingElement.MessageSecurityVersion != bindingElement.MessageSecurityVersion) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(bindingElementRef, "MessageSecurityVersion"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(MessageSecurityVersion)), bindingElement.MessageSecurityVersion.ToString()))); } if (defaultBindingElement.SecurityHeaderLayout != bindingElement.SecurityHeaderLayout) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(bindingElementRef, "SecurityHeaderLayout"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(SecurityHeaderLayout)), bindingElement.SecurityHeaderLayout.ToString()))); } statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( customBinding, "Elements"), "Add", bindingElementRef)); } private static void AddTcpBindingElement(CodeStatementCollection statements, CodeVariableReferenceExpression customBinding, TcpTransportBindingElement bindingElement) { TcpTransportBindingElement defaultBindingElement = new TcpTransportBindingElement(); CodeVariableDeclarationStatement tcpBindingElement = new CodeVariableDeclarationStatement( typeof(TcpTransportBindingElement), "tcpBindingElement", new CodeObjectCreateExpression(typeof(TcpTransportBindingElement))); statements.Add(tcpBindingElement); CodeVariableReferenceExpression bindingElementRef = new CodeVariableReferenceExpression(tcpBindingElement.Name); statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "MaxBufferSize"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(int)), "MaxValue"))); if (defaultBindingElement.TransferMode != bindingElement.TransferMode) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "TransferMode"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(TransferMode)), bindingElement.TransferMode.ToString()))); } statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "MaxReceivedMessageSize"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(int)), "MaxValue"))); if (defaultBindingElement.ConnectionBufferSize != bindingElement.ConnectionBufferSize) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "ConnectionBufferSize"), new CodePrimitiveExpression(bindingElement.ConnectionBufferSize))); } if (defaultBindingElement.ConnectionPoolSettings.GroupName != bindingElement.ConnectionPoolSettings.GroupName) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(bindingElementRef, "ConnectionPoolSettings"), "GroupName"), new CodePrimitiveExpression(bindingElement.ConnectionPoolSettings.GroupName))); } if (defaultBindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint != bindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(bindingElementRef, "ConnectionPoolSettings"), "MaxOutboundConnectionsPerEndpoint"), new CodePrimitiveExpression(bindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint))); } if (defaultBindingElement.ConnectionPoolSettings.IdleTimeout != bindingElement.ConnectionPoolSettings.IdleTimeout) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(bindingElementRef, "ConnectionPoolSettings"), "IdleTimeout"), CreateTimeSpanExpression(bindingElement.ConnectionPoolSettings.IdleTimeout))); } if (defaultBindingElement.ConnectionPoolSettings.LeaseTimeout != bindingElement.ConnectionPoolSettings.LeaseTimeout) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(bindingElementRef, "ConnectionPoolSettings"), "LeaseTimeout"), CreateTimeSpanExpression(bindingElement.ConnectionPoolSettings.LeaseTimeout))); } statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( customBinding, "Elements"), "Add", bindingElementRef)); } private static CodeExpression CreateTimeSpanExpression(TimeSpan value) { return new CodeObjectCreateExpression(typeof(TimeSpan), new CodePrimitiveExpression(value.Ticks)); } private static void AddHttpBindingElement(CodeStatementCollection statements, CodeVariableReferenceExpression customBinding, HttpTransportBindingElement bindingElement) { bool isHttps = bindingElement is HttpsTransportBindingElement; Type bindingElementType = isHttps ? typeof(HttpsTransportBindingElement) : typeof(HttpTransportBindingElement); HttpTransportBindingElement defaultBindingElement = isHttps ? new HttpsTransportBindingElement() : new HttpTransportBindingElement(); CodeVariableDeclarationStatement httpBindingElement = new CodeVariableDeclarationStatement( bindingElementType, isHttps ? "httpsBindingElement" : "httpBindingElement", new CodeObjectCreateExpression(bindingElementType)); statements.Add(httpBindingElement); CodeVariableReferenceExpression bindingElementRef = new CodeVariableReferenceExpression(httpBindingElement.Name); // Set AllowCookies's default value to true. statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "AllowCookies"), new CodePrimitiveExpression(true))); statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "MaxBufferSize"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(int)), "MaxValue"))); statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "MaxReceivedMessageSize"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(int)), "MaxValue"))); if (defaultBindingElement.TransferMode != bindingElement.TransferMode) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "TransferMode"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(TransferMode)), bindingElement.TransferMode.ToString()))); } if (defaultBindingElement.AuthenticationScheme != bindingElement.AuthenticationScheme) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "AuthenticationScheme"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(AuthenticationSchemes)), bindingElement.AuthenticationScheme.ToString()))); } statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( customBinding, "Elements"), "Add", bindingElementRef)); } private static void AddBinaryBindingElement(CodeStatementCollection statements, CodeVariableReferenceExpression customBinding) { statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( customBinding, "Elements"), "Add", new CodeObjectCreateExpression(typeof(BinaryMessageEncodingBindingElement)))); } private static void AddTextBindingElement(CodeStatementCollection statements, CodeVariableReferenceExpression customBinding, TextMessageEncodingBindingElement bindingElement) { TextMessageEncodingBindingElement defaultBindingElement = new TextMessageEncodingBindingElement(); CodeVariableDeclarationStatement textBindingElement = new CodeVariableDeclarationStatement( typeof(TextMessageEncodingBindingElement), "textBindingElement", new CodeObjectCreateExpression(typeof(TextMessageEncodingBindingElement))); statements.Add(textBindingElement); CodeVariableReferenceExpression bindingElementRef = new CodeVariableReferenceExpression(textBindingElement.Name); if (defaultBindingElement.MessageVersion != bindingElement.MessageVersion) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "MessageVersion"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(MessageVersion)), GetMessageVersionName(bindingElement.MessageVersion)))); } if (defaultBindingElement.WriteEncoding.WebName != bindingElement.WriteEncoding.WebName) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( bindingElementRef, "WriteEncoding"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(Encoding)), GetEncoding(bindingElement.WriteEncoding)))); } statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( customBinding, "Elements"), "Add", bindingElementRef)); } private static string GetEncoding(Encoding encoding) { if (encoding.WebName == Encoding.UTF8.WebName) { return "UTF8"; } else if (encoding.WebName == Encoding.Unicode.WebName) { return "Unicode"; } else if (encoding.WebName == Encoding.BigEndianUnicode.WebName) { return "BigEndianUnicode"; } throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ErrEncodingNotSupportedFormat, encoding.WebName)); } private static string GetMessageVersionName(MessageVersion messageVersion) { if (messageVersion == MessageVersion.None) { return "None"; } else if (messageVersion == MessageVersion.Soap11) { return "Soap11"; } else if (messageVersion == MessageVersion.Soap12) { return "CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, System.ServiceModel.Channels.AddressingVersion.None)"; } else if (messageVersion == MessageVersion.Soap11WSAddressing10) { return "CreateVersion(System.ServiceModel.EnvelopeVersion.Soap11, System.ServiceModel.Channels.AddressingVersion.WSAddressing10)"; } else if (messageVersion == MessageVersion.Soap12WSAddressing10) { return "Soap12WSAddressing10"; } throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ErrMessageVersionNotSupportedFormat, messageVersion)); } private static void AddNetTcpBindingConfiguration(CodeStatementCollection statements, NetTcpBinding netTcp) { const string ResultVarName = "result"; NetTcpBinding defaultBinding = new NetTcpBinding(); statements.Add( new CodeVariableDeclarationStatement( typeof(NetTcpBinding), ResultVarName, new CodeObjectCreateExpression(typeof(NetTcpBinding)))); CodeVariableReferenceExpression resultVar = new CodeVariableReferenceExpression(ResultVarName); MaxOutProperties(statements, resultVar); if (defaultBinding.TransferMode != netTcp.TransferMode) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "TransferMode"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(TransferMode)), netTcp.TransferMode.ToString()))); } if (defaultBinding.Security.Mode != netTcp.Security.Mode) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Mode"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(SecurityMode)), netTcp.Security.Mode.ToString()))); } if (defaultBinding.Security.Transport.ClientCredentialType != netTcp.Security.Transport.ClientCredentialType) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Transport"), "ClientCredentialType"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(TcpClientCredentialType)), netTcp.Security.Transport.ClientCredentialType.ToString()))); } if (defaultBinding.Security.Transport.ProtectionLevel != netTcp.Security.Transport.ProtectionLevel) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Transport"), "ProtectionLevel"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(ProtectionLevel)), netTcp.Security.Transport.ProtectionLevel.ToString()))); } if (defaultBinding.Security.Message.ClientCredentialType != netTcp.Security.Message.ClientCredentialType) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Message"), "ClientCredentialType"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(MessageCredentialType)), netTcp.Security.Message.ClientCredentialType.ToString()))); } statements.Add(new CodeMethodReturnStatement(resultVar)); } private static void AddBasicHttpBindingConfiguration(CodeStatementCollection statements, BasicHttpBinding basicHttp) { const string ResultVarName = "result"; BasicHttpBinding defaultBinding = new BasicHttpBinding(); statements.Add( new CodeVariableDeclarationStatement( typeof(BasicHttpBinding), ResultVarName, new CodeObjectCreateExpression(typeof(BasicHttpBinding)))); CodeVariableReferenceExpression resultVar = new CodeVariableReferenceExpression(ResultVarName); MaxOutProperties(statements, resultVar); // Set AllowCookies's default value to true. statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "AllowCookies"), new CodePrimitiveExpression(true))); if (defaultBinding.TransferMode != basicHttp.TransferMode) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "TransferMode"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(TransferMode)), basicHttp.TransferMode.ToString()))); } if (defaultBinding.Security.Mode != basicHttp.Security.Mode) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Mode"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(BasicHttpSecurityMode)), basicHttp.Security.Mode.ToString()))); } if (defaultBinding.Security.Transport.ClientCredentialType != basicHttp.Security.Transport.ClientCredentialType) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Transport"), "ClientCredentialType"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(HttpClientCredentialType)), basicHttp.Security.Transport.ClientCredentialType.ToString()))); } if (defaultBinding.Security.Message.ClientCredentialType != basicHttp.Security.Message.ClientCredentialType) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Message"), "ClientCredentialType"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(BasicHttpMessageCredentialType)), basicHttp.Security.Message.ClientCredentialType.ToString()))); } statements.Add(new CodeMethodReturnStatement(resultVar)); } private static void AddNetHttpBindingConfiguration(CodeStatementCollection statements, NetHttpBinding netHttp) { const string ResultVarName = "result"; NetHttpBinding defaultBinding = new NetHttpBinding(); statements.Add( new CodeVariableDeclarationStatement( typeof(NetHttpBinding), ResultVarName, new CodeObjectCreateExpression(typeof(NetHttpBinding)))); CodeVariableReferenceExpression resultVar = new CodeVariableReferenceExpression(ResultVarName); MaxOutProperties(statements, resultVar); // Set AllowCookies's default value to true. statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "AllowCookies"), new CodePrimitiveExpression(true))); if (defaultBinding.MessageEncoding != netHttp.MessageEncoding) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "MessageEncoding"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(NetHttpMessageEncoding)), netHttp.MessageEncoding.ToString()))); } if (defaultBinding.TransferMode != netHttp.TransferMode) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "TransferMode"), new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(TransferMode)), netHttp.TransferMode.ToString()))); } if (defaultBinding.Security.Mode != netHttp.Security.Mode) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Mode"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(BasicHttpSecurityMode)), netHttp.Security.Mode.ToString()))); } if (defaultBinding.Security.Transport.ClientCredentialType != netHttp.Security.Transport.ClientCredentialType) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Transport"), "ClientCredentialType"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(HttpClientCredentialType)), netHttp.Security.Transport.ClientCredentialType.ToString()))); } if (defaultBinding.Security.Message.ClientCredentialType != netHttp.Security.Message.ClientCredentialType) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(resultVar, "Security"), "Message"), "ClientCredentialType"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(BasicHttpMessageCredentialType)), netHttp.Security.Message.ClientCredentialType.ToString()))); } statements.Add(new CodeMethodReturnStatement(resultVar)); } private static void MaxOutProperties(CodeStatementCollection statements, CodeVariableReferenceExpression resultVar) { statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "MaxBufferSize"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(int)), "MaxValue"))); statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "ReaderQuotas"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(XmlDictionaryReaderQuotas)), "Max"))); statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( resultVar, "MaxReceivedMessageSize"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(int)), "MaxValue"))); } private void AddNewEndpointAddress(string endpointConfigurationName, string endpointAddress, ServiceEndpoint serviceEndpoint) { CodeExpression createIdentityExpression = null; EndpointIdentity identity = serviceEndpoint.Address.Identity; if (identity != null && (identity is DnsEndpointIdentity)) { createIdentityExpression = new CodeObjectCreateExpression(identity.GetType(), new CodePrimitiveExpression(identity.IdentityClaim.Resource)); } CodeExpression createEndpointAddressExpression = null; if (createIdentityExpression != null) { createEndpointAddressExpression = new CodeObjectCreateExpression( typeof(EndpointAddress), new CodeObjectCreateExpression( typeof(Uri), new CodePrimitiveExpression(endpointAddress)), createIdentityExpression); } else { createEndpointAddressExpression = new CodeObjectCreateExpression( typeof(EndpointAddress), new CodePrimitiveExpression(endpointAddress)); } this.GetEndpointAddress.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeArgumentReferenceExpression(ConfigToCodeConstants.EndpointConfigurationParameter), CodeBinaryOperatorType.ValueEquality, new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(ConfigToCodeConstants.EndpointConfigurationEnumTypeName), endpointConfigurationName)), new CodeMethodReturnStatement(createEndpointAddressExpression))); } private void CreateDefaultEndpointMethods(string clientTypeName, List<string> endpointNames) { System.Diagnostics.Debug.Assert(endpointNames.Count == 1, "have and only have on endpoint has to exist for a given client type"); this.GetDefaultBinding = new CodeMemberMethod { Attributes = MemberAttributes.Static | MemberAttributes.Private, Name = ConfigToCodeConstants.GetDefaultBindingMethod, ReturnType = new CodeTypeReference(typeof(Binding)), }; this.GetDefaultEndpointAddress = new CodeMemberMethod { Attributes = MemberAttributes.Static | MemberAttributes.Private, Name = ConfigToCodeConstants.GetDefaultEndpointAddressMethod, ReturnType = new CodeTypeReference(typeof(EndpointAddress)), }; this.GetDefaultBinding.Statements.Add( new CodeMethodReturnStatement( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(clientTypeName), ConfigToCodeConstants.GetBindingMethod, new CodeFieldReferenceExpression( new CodeTypeReferenceExpression( ConfigToCodeConstants.EndpointConfigurationEnumTypeName), endpointNames[0])))); this.GetDefaultEndpointAddress.Statements.Add( new CodeMethodReturnStatement( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(clientTypeName), ConfigToCodeConstants.GetEndpointAddressMethod, new CodeFieldReferenceExpression( new CodeTypeReferenceExpression( ConfigToCodeConstants.EndpointConfigurationEnumTypeName), endpointNames[0])))); } private void AddFinalThrowStatement() { this.GetBinding.Statements.Add( new CodeThrowExceptionStatement( new CodeObjectCreateExpression( typeof(InvalidOperationException), new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(string)), "Format", new CodePrimitiveExpression(SR.CodeExpressionCouldNotFindEndpoint), new CodeArgumentReferenceExpression(ConfigToCodeConstants.EndpointConfigurationParameter))))); this.GetEndpointAddress.Statements.Add( new CodeThrowExceptionStatement( new CodeObjectCreateExpression( typeof(InvalidOperationException), new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(string)), "Format", new CodePrimitiveExpression(SR.CodeExpressionCouldNotFindEndpoint), new CodeArgumentReferenceExpression(ConfigToCodeConstants.EndpointConfigurationParameter))))); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Snippets; using Microsoft.CSharp.RuntimeBinder; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { /// <summary> /// This service is created on the UI thread during package initialization, but it must not /// block the initialization process. /// </summary> internal abstract class AbstractSnippetInfoService : ForegroundThreadAffinitizedObject, ISnippetInfoService, IVsExpansionEvents { private readonly Guid _languageGuidForSnippets; private readonly IVsExpansionManager _expansionManager; /// <summary> /// Initialize these to empty values. When returning from <see cref="GetSnippetsIfAvailable "/> /// and <see cref="SnippetShortcutExists_NonBlocking"/>, we return the current set of known /// snippets rather than waiting for initial results. /// </summary> protected ImmutableArray<SnippetInfo> snippets = ImmutableArray.Create<SnippetInfo>(); protected IImmutableSet<string> snippetShortcuts = ImmutableHashSet.Create<string>(); // Guard the snippets and snippetShortcut fields so that returned result sets are always // complete. protected object cacheGuard = new object(); private readonly AggregateAsynchronousOperationListener _waiter; public AbstractSnippetInfoService( Shell.SVsServiceProvider serviceProvider, Guid languageGuidForSnippets, IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) { AssertIsForeground(); if (serviceProvider != null) { var textManager = (IVsTextManager2)serviceProvider.GetService(typeof(SVsTextManager)); if (textManager.GetExpansionManager(out _expansionManager) == VSConstants.S_OK) { ComEventSink.Advise<IVsExpansionEvents>(_expansionManager, this); _waiter = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.Snippets); _languageGuidForSnippets = languageGuidForSnippets; PopulateSnippetCaches(); } } } public int OnAfterSnippetsUpdate() { AssertIsForeground(); if (_expansionManager != null) { PopulateSnippetCaches(); } return VSConstants.S_OK; } public int OnAfterSnippetsKeyBindingChange([ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")]uint dwCmdGuid, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")]uint dwCmdId, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")]int fBound) { return VSConstants.S_OK; } public IEnumerable<SnippetInfo> GetSnippetsIfAvailable() { // Immediately return the known set of snippets, even if we're still in the process // of calculating a more up-to-date list. lock (cacheGuard) { return snippets; } } public bool SnippetShortcutExists_NonBlocking(string shortcut) { if (shortcut == null) { return false; } // Check against the known set of snippets, even if we're still in the process of // calculating a more up-to-date list. lock (cacheGuard) { return snippetShortcuts.Contains(shortcut); } } public virtual bool ShouldFormatSnippet(SnippetInfo snippetInfo) { return false; } private void PopulateSnippetCaches() { Debug.Assert(_expansionManager != null); // If the expansion manager is an IExpansionManager, then we can use the asynchronous // population mechanism it provides. Otherwise, getting snippet information from the // IVsExpansionManager must be done synchronously on the UI thread. // IExpansionManager was introduced in Visual Studio 2015 Update 1, but will be enabled // by default for the first time in Visual Studio 2015 Update 2. However, the platform // still supports returning the IVsExpansionManager if a major problem in the // IExpansionManager is discovered, so we must continue supporting the fallback. var token = _waiter.BeginAsyncOperation(GetType().Name + ".Start"); var asyncExpansionManager = _expansionManager as IExpansionManager; if (asyncExpansionManager != null) { // Call the asynchronous IExpansionManager API from a background thread Task.Factory.StartNew(async () => await PopulateSnippetCacheAsync(asyncExpansionManager).ConfigureAwait(false), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).CompletesAsyncOperation(token); } else { // Call the synchronous IVsExpansionManager API from the UI thread Task.Factory.StartNew(() => PopulateSnippetCacheOnForeground(_expansionManager), CancellationToken.None, TaskCreationOptions.None, ForegroundTaskScheduler).CompletesAsyncOperation(token); } } private async Task PopulateSnippetCacheAsync(IExpansionManager expansionManager) { AssertIsBackground(); var expansionEnumerator = await expansionManager.EnumerateExpansionsAsync( _languageGuidForSnippets, 0, // shortCutOnly Array.Empty<string>(), // types 0, // countTypes 1, // includeNULLTypes 1 // includeDulicates: Allows snippets with the same title but different shortcuts ).ConfigureAwait(false); // The rest of the process requires being on the UI thread, see the explanation on // PopulateSnippetCacheFromExpansionEnumeration for details await Task.Factory.StartNew(() => PopulateSnippetCacheFromExpansionEnumeration(expansionEnumerator), CancellationToken.None, TaskCreationOptions.None, ForegroundTaskScheduler).ConfigureAwait(false); } /// <remarks> /// Changes to the <see cref="IVsExpansionManager.EnumerateExpansions"/> invocation /// should also be made to the IExpansionManager.EnumerateExpansionsAsync /// invocation in <see cref="PopulateSnippetCacheAsync(IExpansionManager)"/>. /// </remarks> private void PopulateSnippetCacheOnForeground(IVsExpansionManager expansionManager) { AssertIsForeground(); IVsExpansionEnumeration expansionEnumerator = null; expansionManager.EnumerateExpansions( _languageGuidForSnippets, fShortCutOnly: 0, bstrTypes: null, iCountTypes: 0, fIncludeNULLType: 1, fIncludeDuplicates: 1, // Allows snippets with the same title but different shortcuts pEnum: out expansionEnumerator); PopulateSnippetCacheFromExpansionEnumeration(expansionEnumerator); } /// <remarks> /// This method must be called on the UI thread because it eventually calls into /// IVsExpansionEnumeration.Next, which must be called on the UI thread due to an issue /// with how the call is marshalled. /// /// The second parameter for IVsExpansionEnumeration.Next is defined like this: /// [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.VsExpansion")] IntPtr[] rgelt /// /// We pass a pointer for rgelt that we expect to be populated as the result. This /// eventually calls into the native CExpansionEnumeratorShim::Next method, which has the /// same contract of expecting a non-null rgelt that it can drop expansion data into. When /// we call from the UI thread, this transition from managed code to the /// CExpansionEnumeratorShim` goes smoothly and everything works. /// /// When we call from a background thread, the COM marshaller has to move execution to the /// UI thread, and as part of this process it uses the interface as defined in the idl to /// set up the appropriate arguments to pass. The same parameter from the idl is defined as /// [out, size_is(celt), length_is(*pceltFetched)] VsExpansion **rgelt /// /// Because rgelt is specified as an `out` parameter, the marshaller is discarding the /// pointer we passed and substituting the null reference. This then causes a null /// reference exception in the shim. Calling from the UI thread avoids this marshaller. /// </remarks> private void PopulateSnippetCacheFromExpansionEnumeration(IVsExpansionEnumeration expansionEnumerator) { AssertIsForeground(); var updatedSnippets = ExtractSnippetInfo(expansionEnumerator); var updatedSnippetShortcuts = GetShortcutsHashFromSnippets(updatedSnippets); lock (cacheGuard) { snippets = updatedSnippets; snippetShortcuts = updatedSnippetShortcuts; } } private ImmutableArray<SnippetInfo> ExtractSnippetInfo(IVsExpansionEnumeration expansionEnumerator) { AssertIsForeground(); var snippetListBuilder = ImmutableArray.CreateBuilder<SnippetInfo>(); uint count = 0; uint fetched = 0; VsExpansion snippetInfo = new VsExpansion(); IntPtr[] pSnippetInfo = new IntPtr[1]; try { // Allocate enough memory for one VSExpansion structure. This memory is filled in by the Next method. pSnippetInfo[0] = Marshal.AllocCoTaskMem(Marshal.SizeOf(snippetInfo)); expansionEnumerator.GetCount(out count); for (uint i = 0; i < count; i++) { expansionEnumerator.Next(1, pSnippetInfo, out fetched); if (fetched > 0) { // Convert the returned blob of data into a structure that can be read in managed code. snippetInfo = ConvertToVsExpansionAndFree(pSnippetInfo[0]); if (!string.IsNullOrEmpty(snippetInfo.shortcut)) { snippetListBuilder.Add(new SnippetInfo(snippetInfo.shortcut, snippetInfo.title, snippetInfo.description, snippetInfo.path)); } } } } finally { Marshal.FreeCoTaskMem(pSnippetInfo[0]); } return snippetListBuilder.ToImmutable(); } protected static IImmutableSet<string> GetShortcutsHashFromSnippets(ImmutableArray<SnippetInfo> updatedSnippets) { return new HashSet<string>(updatedSnippets.Select(s => s.Shortcut), StringComparer.OrdinalIgnoreCase) .ToImmutableHashSet(StringComparer.OrdinalIgnoreCase); } private static VsExpansion ConvertToVsExpansionAndFree(IntPtr expansionPtr) { var buffer = (VsExpansionWithIntPtrs)Marshal.PtrToStructure(expansionPtr, typeof(VsExpansionWithIntPtrs)); var expansion = new VsExpansion(); ConvertToStringAndFree(ref buffer.DescriptionPtr, ref expansion.description); ConvertToStringAndFree(ref buffer.PathPtr, ref expansion.path); ConvertToStringAndFree(ref buffer.ShortcutPtr, ref expansion.shortcut); ConvertToStringAndFree(ref buffer.TitlePtr, ref expansion.title); return expansion; } private static void ConvertToStringAndFree(ref IntPtr ptr, ref string str) { if (ptr != IntPtr.Zero) { str = Marshal.PtrToStringBSTR(ptr); Marshal.FreeBSTR(ptr); ptr = IntPtr.Zero; } } /// <summary> /// This structure is used to facilitate the interop calls with IVsExpansionEnumeration. /// </summary> [StructLayout(LayoutKind.Sequential)] private struct VsExpansionWithIntPtrs { public IntPtr PathPtr; public IntPtr TitlePtr; public IntPtr ShortcutPtr; public IntPtr DescriptionPtr; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Reflection; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Scripting.Hosting; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A class that represents a script that you can run. /// /// Create a script using a language specific script class such as CSharpScript or VisualBasicScript. /// </summary> public abstract class Script { internal readonly ScriptCompiler Compiler; internal readonly ScriptBuilder Builder; private Compilation _lazyCompilation; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) { Debug.Assert(code != null); Debug.Assert(options != null); Debug.Assert(compiler != null); Debug.Assert(builder != null); Compiler = compiler; Builder = builder; Previous = previousOpt; Code = code; Options = options; GlobalsType = globalsTypeOpt; } internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, string codeOpt, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt) { return new Script<T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), codeOpt ?? "", optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null); } /// <summary> /// A script that will run first when this script is run. /// Any declarations made in the previous script can be referenced in this script. /// The end state from running this script includes all declarations made by both scripts. /// </summary> public Script Previous { get; } /// <summary> /// The options used by this script. /// </summary> public ScriptOptions Options { get; } /// <summary> /// The source code of the script. /// </summary> public string Code { get; } /// <summary> /// The type of an object whose members can be accessed by the script as global variables. /// </summary> public Type GlobalsType { get; } /// <summary> /// The expected return type of the script. /// </summary> public abstract Type ReturnType { get; } /// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options); internal abstract Script WithOptionsInternal(ScriptOptions options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<object> ContinueWith(string code, ScriptOptions options = null) => ContinueWith<object>(code, options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<TResult> ContinueWith<TResult>(string code, ScriptOptions options = null) => new Script<TResult>(Compiler, Builder, code ?? "", options ?? InheritOptions(Options), GlobalsType, this); private static ScriptOptions InheritOptions(ScriptOptions previous) { // don't inherit references or imports, they have already been applied: return previous. WithReferences(ImmutableArray<MetadataReference>.Empty). WithImports(ImmutableArray<string>.Empty); } /// <summary> /// Get's the <see cref="Compilation"/> that represents the semantics of the script. /// </summary> public Compilation GetCompilation() { if (_lazyCompilation == null) { var compilation = Compiler.CreateSubmission(this); Interlocked.CompareExchange(ref _lazyCompilation, compilation, null); } return _lazyCompilation; } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal Task<object> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonEvaluateAsync(globals, cancellationToken); internal abstract Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunAsync(object globals, CancellationToken cancellationToken) => CommonRunAsync(globals, null, cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunAsync(object globals = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonRunAsync(globals, catchException, cancellationToken); internal abstract Task<ScriptState> CommonRunAsync(object globals, Func<Exception, bool> catchException, CancellationToken cancellationToken); /// <summary> /// Run the script from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunFromAsync(ScriptState previousState, CancellationToken cancellationToken) => CommonRunFromAsync(previousState, null, cancellationToken); /// <summary> /// Run the script from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunFromAsync(ScriptState previousState, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonRunFromAsync(previousState, catchException, cancellationToken); internal abstract Task<ScriptState> CommonRunFromAsync(ScriptState previousState, Func<Exception, bool> catchException, CancellationToken cancellationToken); /// <summary> /// Forces the script through the compilation step. /// If not called directly, the compilation step will occur on the first call to Run. /// </summary> public ImmutableArray<Diagnostic> Compile(CancellationToken cancellationToken = default(CancellationToken)) => CommonCompile(cancellationToken); internal abstract ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken); internal abstract Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken); // Apply recursive alias <host> to the host assembly reference, so that we hide its namespaces and global types behind it. internal static readonly MetadataReferenceProperties HostAssemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("<host>")).WithRecursiveAliases(true); /// <summary> /// Gets the references that need to be assigned to the compilation. /// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance. /// </summary> internal ImmutableArray<MetadataReference> GetReferencesForCompilation( CommonMessageProvider messageProvider, DiagnosticBag diagnostics, MetadataReference languageRuntimeReferenceOpt = null) { var resolver = Options.MetadataResolver; var references = ArrayBuilder<MetadataReference>.GetInstance(); try { if (Previous == null) { var corLib = MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly); references.Add(corLib); if (GlobalsType != null) { var globalsAssembly = GlobalsType.GetTypeInfo().Assembly; // If the assembly doesn't have metadata (it's an in-memory or dynamic assembly), // the host has to add reference to the metadata where globals type is located explicitly. if (MetadataReference.HasMetadata(globalsAssembly)) { references.Add(MetadataReference.CreateFromAssemblyInternal(globalsAssembly, HostAssemblyReferenceProperties)); } } if (languageRuntimeReferenceOpt != null) { references.Add(languageRuntimeReferenceOpt); } } // add new references: foreach (var reference in Options.MetadataReferences) { var unresolved = reference as UnresolvedMetadataReference; if (unresolved != null) { var resolved = resolver.ResolveReference(unresolved.Reference, null, unresolved.Properties); if (resolved.IsDefault) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataFileNotFound, Location.None, unresolved.Reference)); } else { references.AddRange(resolved); } } else { references.Add(reference); } } return references.ToImmutable(); } finally { references.Free(); } } // TODO: remove internal bool HasReturnValue() { return GetCompilation().HasSubmissionResult(); } } public sealed class Script<T> : Script { private ImmutableArray<Func<object[], Task>> _lazyPrecedingExecutors; private Func<object[], Task<T>> _lazyExecutor; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) : base(compiler, builder, code, options, globalsTypeOpt, previousOpt) { } public override Type ReturnType => typeof(T); public new Script<T> WithOptions(ScriptOptions options) { return (options == Options) ? this : new Script<T>(Compiler, Builder, Code, options, GlobalsType, Previous); } internal override Script WithOptionsInternal(ScriptOptions options) => WithOptions(options); internal override ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken) { // TODO: avoid throwing exception, report all diagnostics https://github.com/dotnet/roslyn/issues/5949 try { GetPrecedingExecutors(cancellationToken); GetExecutor(cancellationToken); return ImmutableArray.CreateRange(GetCompilation().GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Warning)); } catch (CompilationErrorException e) { return ImmutableArray.CreateRange(e.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning)); } } internal override Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken) => GetExecutor(cancellationToken); internal override Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken) => EvaluateAsync(globals, cancellationToken).CastAsync<T, object>(); internal override Task<ScriptState> CommonRunAsync(object globals, Func<Exception, bool> catchException, CancellationToken cancellationToken) => RunAsync(globals, catchException, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); internal override Task<ScriptState> CommonRunFromAsync(ScriptState previousState, Func<Exception, bool> catchException, CancellationToken cancellationToken) => RunFromAsync(previousState, catchException, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private Func<object[], Task<T>> GetExecutor(CancellationToken cancellationToken) { if (_lazyExecutor == null) { Interlocked.CompareExchange(ref _lazyExecutor, Builder.CreateExecutor<T>(Compiler, GetCompilation(), cancellationToken), null); } return _lazyExecutor; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> GetPrecedingExecutors(CancellationToken cancellationToken) { if (_lazyPrecedingExecutors.IsDefault) { var preceding = TryGetPrecedingExecutors(null, cancellationToken); Debug.Assert(!preceding.IsDefault); InterlockedOperations.Initialize(ref _lazyPrecedingExecutors, preceding); } return _lazyPrecedingExecutors; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> TryGetPrecedingExecutors(Script lastExecutedScriptInChainOpt, CancellationToken cancellationToken) { Script script = Previous; if (script == lastExecutedScriptInChainOpt) { return ImmutableArray<Func<object[], Task>>.Empty; } var scriptsReversed = ArrayBuilder<Script>.GetInstance(); while (script != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Add(script); script = script.Previous; } if (lastExecutedScriptInChainOpt != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Free(); return default(ImmutableArray<Func<object[], Task>>); } var executors = ArrayBuilder<Func<object[], Task>>.GetInstance(scriptsReversed.Count); // We need to build executors in the order in which they are chained, // so that assemblies created for the submissions are loaded in the correct order. for (int i = scriptsReversed.Count - 1; i >= 0; i--) { executors.Add(scriptsReversed[i].CommonGetExecutor(cancellationToken)); } return executors.ToImmutableAndFree(); } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal new Task<T> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => RunAsync(globals, cancellationToken).GetEvaluationResultAsync(); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="CompilationErrorException">Compilation has errors.</exception> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception> public new Task<ScriptState<T>> RunAsync(object globals, CancellationToken cancellationToken) => RunAsync(globals, null, cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="CompilationErrorException">Compilation has errors.</exception> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception> public new Task<ScriptState<T>> RunAsync(object globals = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor construction may throw; // do so synchronously so that the exception is not wrapped in the task. ValidateGlobals(globals, GlobalsType); var executionState = ScriptExecutionState.Create(globals); var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); return RunSubmissionsAsync(executionState, precedingExecutors, currentExecutor, catchException, cancellationToken); } /// <summary> /// Creates a delegate that will run this script from the beginning when invoked. /// </summary> /// <remarks> /// The delegate doesn't hold on this script or its compilation. /// </remarks> public ScriptRunner<T> CreateDelegate(CancellationToken cancellationToken = default(CancellationToken)) { var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); var globalsType = GlobalsType; return (globals, token) => { ValidateGlobals(globals, globalsType); return ScriptExecutionState.Create(globals).RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, null, null, token); }; } /// <summary> /// Run the script from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception> public new Task<ScriptState<T>> RunFromAsync(ScriptState previousState, CancellationToken cancellationToken) => RunFromAsync(previousState, null, cancellationToken); /// <summary> /// Run the script from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception> public new Task<ScriptState<T>> RunFromAsync(ScriptState previousState, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor construction may throw; // do so synchronously so that the exception is not wrapped in the task. if (previousState == null) { throw new ArgumentNullException(nameof(previousState)); } if (previousState.Script == this) { // this state is already the output of running this script. return Task.FromResult((ScriptState<T>)previousState); } var precedingExecutors = TryGetPrecedingExecutors(previousState.Script, cancellationToken); if (precedingExecutors.IsDefault) { throw new ArgumentException(ScriptingResources.StartingStateIncompatible, nameof(previousState)); } var currentExecutor = GetExecutor(cancellationToken); ScriptExecutionState newExecutionState = previousState.ExecutionState.FreezeAndClone(); return RunSubmissionsAsync(newExecutionState, precedingExecutors, currentExecutor, catchException, cancellationToken); } private async Task<ScriptState<T>> RunSubmissionsAsync( ScriptExecutionState executionState, ImmutableArray<Func<object[], Task>> precedingExecutors, Func<object[], Task> currentExecutor, Func<Exception, bool> catchExceptionOpt, CancellationToken cancellationToken) { var exceptionOpt = (catchExceptionOpt != null) ? new StrongBox<Exception>() : null; T result = await executionState.RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, exceptionOpt, catchExceptionOpt, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); return new ScriptState<T>(executionState, this, result, exceptionOpt?.Value); } private static void ValidateGlobals(object globals, Type globalsType) { if (globalsType != null) { if (globals == null) { throw new ArgumentException(ScriptingResources.ScriptRequiresGlobalVariables, nameof(globals)); } var runtimeType = globals.GetType().GetTypeInfo(); var globalsTypeInfo = globalsType.GetTypeInfo(); if (!globalsTypeInfo.IsAssignableFrom(runtimeType)) { throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsTypeInfo), nameof(globals)); } } else if (globals != null) { throw new ArgumentException(ScriptingResources.GlobalVariablesWithoutGlobalType, nameof(globals)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Kafka.Client.Clusters; using Kafka.Client.Common; using Kafka.Client.Extensions; using log4net; namespace Kafka.Client.Server { /// <summary> /// /// Note: original namespace: kafka.server /// </summary> internal abstract class AbstractFetcherManager { protected static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string Name { get; set; } public string MetricPrefix { get; protected set; } public int NumFetchers { get; protected set; } internal AbstractFetcherManager(string name, string metricPrefix, int numFetchers = 1) { this.Name = name; this.MetricPrefix = metricPrefix; this.NumFetchers = numFetchers; MetersFactory.NewGauge( metricPrefix + "-MaxLag", () => this.fetcherThreadMap.Aggregate( 0, (curMaxAll, fetcherThreadMapEntry) => fetcherThreadMapEntry.Value.FetcherLagStats.Stats.Aggregate( 0, (curMaxThread, fetcherLagStatsEntry) => (int)Math.Max(curMaxThread, fetcherLagStatsEntry.Value.Lag)))); MetersFactory.NewGauge( metricPrefix + "-MinFetchRate", () => { var headRate = fetcherThreadMap.Any() ? fetcherThreadMap.First().Value.FetcherStats.RequestRate.OneMinuteRate() : 0; return fetcherThreadMap.Aggregate( headRate, (curMinAll, fetcherThreadMapEntry) => Math.Min(curMinAll, fetcherThreadMapEntry.Value.FetcherStats.RequestRate.OneMinuteRate())); }); } private readonly Dictionary<BrokerAndFetcherId, AbstractFetcherThread> fetcherThreadMap = new Dictionary<BrokerAndFetcherId, AbstractFetcherThread>(); private readonly object mapLock = new object(); private int GetFetcherId(string topic, int partitionId) { return Math.Abs((31 * topic.GetHashCode()) + partitionId) % this.NumFetchers; } // to be defined in subclass to create a specific fetcher public abstract AbstractFetcherThread CreateFetcherThread(int fetcherId, Broker sourceBroker); public void AddFetcherForPartitions(IDictionary<TopicAndPartition, BrokerAndInitialOffset> partitionAndOffsets) { lock (this.mapLock) { var partitionsPerFetcher = partitionAndOffsets.GroupByScala( kvp => { var topicAndPartition = kvp.Key; var brokerAndInitialOffset = kvp.Value; return new BrokerAndFetcherId( brokerAndInitialOffset.Broker, this.GetFetcherId(topicAndPartition.Topic, topicAndPartition.Partiton)); }); foreach (var kvp in partitionsPerFetcher) { var brokerAndFetcherId = kvp.Key; var partitionAndOffset = kvp.Value; AbstractFetcherThread fetcherThread; if (this.fetcherThreadMap.TryGetValue(brokerAndFetcherId, out fetcherThread) == false) { fetcherThread = this.CreateFetcherThread( brokerAndFetcherId.FetcherId, brokerAndFetcherId.Broker); this.fetcherThreadMap[brokerAndFetcherId] = fetcherThread; fetcherThread.Start(); } this.fetcherThreadMap.Get(brokerAndFetcherId) .AddPartitions( partitionAndOffset.ToDictionary(x => x.Key, x => x.Value.InitOffset)); } } Logger.InfoFormat( "Added fetcher for partitons {0}", string.Join( ", ", partitionAndOffsets.Select( kvp => { var topicAndPartition = kvp.Key; var brokerAndInitialOffset = kvp.Value; return "[" + topicAndPartition + ", initOffset " + brokerAndInitialOffset.InitOffset + " to broker " + brokerAndInitialOffset.Broker + "]"; }).ToArray())); } public void RemoveFetcherForPartitions(HashSet<TopicAndPartition> partitions) { lock (this.mapLock) { foreach (var keyAndFetcher in this.fetcherThreadMap) { keyAndFetcher.Value.RemovePartitions(partitions); } } Logger.InfoFormat("Removed fetcher for partitions {0}", string.Join(",", partitions)); } public void ShutdownIdleFetcherThreads() { lock (this.mapLock) { var keysToBeRemoted = new HashSet<BrokerAndFetcherId>(); foreach (var keyAndFetcher in this.fetcherThreadMap) { var key = keyAndFetcher.Key; var fetcher = keyAndFetcher.Value; if (fetcher.PartitionCount() <= 0) { fetcher.Shutdown(); keysToBeRemoted.Add(key); } } foreach (var key in keysToBeRemoted) { this.fetcherThreadMap.Remove(key); } } } public void CloseAllFetchers() { lock (this.mapLock) { foreach (var fetcher in this.fetcherThreadMap.Values) { fetcher.Shutdown(); } this.fetcherThreadMap.Clear(); } } } public class BrokerAndFetcherId { public Broker Broker { get; private set; } public int FetcherId { get; private set; } public BrokerAndFetcherId(Broker broker, int fetcherId) { this.Broker = broker; this.FetcherId = fetcherId; } protected bool Equals(BrokerAndFetcherId other) { return Equals(this.Broker, other.Broker) && this.FetcherId == other.FetcherId; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return this.Equals((BrokerAndFetcherId)obj); } public override int GetHashCode() { unchecked { return ((this.Broker != null ? this.Broker.GetHashCode() : 0) * 397) ^ this.FetcherId; } } } public class BrokerAndInitialOffset { public Broker Broker { get; private set; } public long InitOffset { get; private set; } public BrokerAndInitialOffset(Broker broker, long initOffset) { this.Broker = broker; this.InitOffset = initOffset; } protected bool Equals(BrokerAndInitialOffset other) { return Equals(this.Broker, other.Broker) && this.InitOffset == other.InitOffset; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return this.Equals((BrokerAndInitialOffset)obj); } public override int GetHashCode() { unchecked { return ((this.Broker != null ? this.Broker.GetHashCode() : 0) * 397) ^ this.InitOffset.GetHashCode(); } } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using MatterHackers.VectorMath; namespace MatterHackers.Agg.Image { public abstract class ImageProxy : IImageByte { protected IImageByte linkedImage; public IImageByte LinkedImage { get { return linkedImage; } set { linkedImage = value; } } public ImageProxy(IImageByte linkedImage) { this.linkedImage = linkedImage; } public virtual void LinkToImage(IImageByte linkedImage) { this.linkedImage = linkedImage; } public virtual Vector2 OriginOffset { get { return linkedImage.OriginOffset; } set { linkedImage.OriginOffset = value; } } public virtual int Width { get { return linkedImage.Width; } } public virtual int Height { get { return linkedImage.Height; } } public virtual int StrideInBytes() { return linkedImage.StrideInBytes(); } public virtual int StrideInBytesAbs() { return linkedImage.StrideInBytesAbs(); } public virtual RectangleInt GetBounds() { return linkedImage.GetBounds(); } public Graphics2D NewGraphics2D() { return linkedImage.NewGraphics2D(); } public IRecieveBlenderByte GetRecieveBlender() { return linkedImage.GetRecieveBlender(); } public void SetRecieveBlender(IRecieveBlenderByte value) { linkedImage.SetRecieveBlender(value); } public virtual RGBA_Bytes GetPixel(int x, int y) { return linkedImage.GetPixel(x, y); } public virtual void copy_pixel(int x, int y, byte[] c, int ByteOffset) { linkedImage.copy_pixel(x, y, c, ByteOffset); } public virtual void CopyFrom(IImageByte sourceRaster) { linkedImage.CopyFrom(sourceRaster); } public virtual void CopyFrom(IImageByte sourceImage, RectangleInt sourceImageRect, int destXOffset, int destYOffset) { linkedImage.CopyFrom(sourceImage, sourceImageRect, destXOffset, destYOffset); } public virtual void SetPixel(int x, int y, RGBA_Bytes color) { linkedImage.SetPixel(x, y, color); } public virtual void BlendPixel(int x, int y, RGBA_Bytes sourceColor, byte cover) { linkedImage.BlendPixel(x, y, sourceColor, cover); } public virtual void copy_hline(int x, int y, int len, RGBA_Bytes sourceColor) { linkedImage.copy_hline(x, y, len, sourceColor); } public virtual void copy_vline(int x, int y, int len, RGBA_Bytes sourceColor) { linkedImage.copy_vline(x, y, len, sourceColor); } public virtual void blend_hline(int x1, int y, int x2, RGBA_Bytes sourceColor, byte cover) { linkedImage.blend_hline(x1, y, x2, sourceColor, cover); } public virtual void blend_vline(int x, int y1, int y2, RGBA_Bytes sourceColor, byte cover) { linkedImage.blend_vline(x, y1, y2, sourceColor, cover); } public virtual void blend_solid_hspan(int x, int y, int len, RGBA_Bytes c, byte[] covers, int coversIndex) { linkedImage.blend_solid_hspan(x, y, len, c, covers, coversIndex); } public virtual void copy_color_hspan(int x, int y, int len, RGBA_Bytes[] colors, int colorIndex) { linkedImage.copy_color_hspan(x, y, len, colors, colorIndex); } public virtual void copy_color_vspan(int x, int y, int len, RGBA_Bytes[] colors, int colorIndex) { linkedImage.copy_color_vspan(x, y, len, colors, colorIndex); } public virtual void blend_solid_vspan(int x, int y, int len, RGBA_Bytes c, byte[] covers, int coversIndex) { linkedImage.blend_solid_vspan(x, y, len, c, covers, coversIndex); } public virtual void blend_color_hspan(int x, int y, int len, RGBA_Bytes[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { linkedImage.blend_color_hspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll); } public virtual void blend_color_vspan(int x, int y, int len, RGBA_Bytes[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { linkedImage.blend_color_vspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll); } public byte[] GetBuffer() { return linkedImage.GetBuffer(); } public int GetBufferOffsetXY(int x, int y) { return linkedImage.GetBufferOffsetXY(x, y); } public int GetBufferOffsetY(int y) { return linkedImage.GetBufferOffsetY(y); } public virtual int GetBytesBetweenPixelsInclusive() { return linkedImage.GetBytesBetweenPixelsInclusive(); } public virtual int BitDepth { get { return linkedImage.BitDepth; } } public void MarkImageChanged() { linkedImage.MarkImageChanged(); } } public abstract class ImageProxyFloat : IImageFloat { protected IImageFloat linkedImage; public ImageProxyFloat(IImageFloat linkedImage) { this.linkedImage = linkedImage; } public virtual void LinkToImage(IImageFloat linkedImage) { this.linkedImage = linkedImage; } public virtual Vector2 OriginOffset { get { return linkedImage.OriginOffset; } set { linkedImage.OriginOffset = value; } } public virtual int Width { get { return linkedImage.Width; } } public virtual int Height { get { return linkedImage.Height; } } public virtual int StrideInFloats() { return linkedImage.StrideInFloats(); } public virtual int StrideInFloatsAbs() { return linkedImage.StrideInFloatsAbs(); } public virtual RectangleInt GetBounds() { return linkedImage.GetBounds(); } public Graphics2D NewGraphics2D() { return linkedImage.NewGraphics2D(); } public IRecieveBlenderFloat GetBlender() { return linkedImage.GetBlender(); } public void SetRecieveBlender(IRecieveBlenderFloat value) { linkedImage.SetRecieveBlender(value); } public virtual RGBA_Floats GetPixel(int x, int y) { return linkedImage.GetPixel(y, x); } public virtual void copy_pixel(int x, int y, float[] c, int FloatOffset) { linkedImage.copy_pixel(x, y, c, FloatOffset); } public virtual void CopyFrom(IImageFloat sourceRaster) { linkedImage.CopyFrom(sourceRaster); } public virtual void CopyFrom(IImageFloat sourceImage, RectangleInt sourceImageRect, int destXOffset, int destYOffset) { linkedImage.CopyFrom(sourceImage, sourceImageRect, destXOffset, destYOffset); } public virtual void SetPixel(int x, int y, RGBA_Floats color) { linkedImage.SetPixel(x, y, color); } public virtual void BlendPixel(int x, int y, RGBA_Floats sourceColor, byte cover) { linkedImage.BlendPixel(x, y, sourceColor, cover); } public virtual void copy_hline(int x, int y, int len, RGBA_Floats sourceColor) { linkedImage.copy_hline(x, y, len, sourceColor); } public virtual void copy_vline(int x, int y, int len, RGBA_Floats sourceColor) { linkedImage.copy_vline(x, y, len, sourceColor); } public virtual void blend_hline(int x1, int y, int x2, RGBA_Floats sourceColor, byte cover) { linkedImage.blend_hline(x1, y, x2, sourceColor, cover); } public virtual void blend_vline(int x, int y1, int y2, RGBA_Floats sourceColor, byte cover) { linkedImage.blend_vline(x, y1, y2, sourceColor, cover); } public virtual void blend_solid_hspan(int x, int y, int len, RGBA_Floats c, byte[] covers, int coversIndex) { linkedImage.blend_solid_hspan(x, y, len, c, covers, coversIndex); } public virtual void copy_color_hspan(int x, int y, int len, RGBA_Floats[] colors, int colorIndex) { linkedImage.copy_color_hspan(x, y, len, colors, colorIndex); } public virtual void copy_color_vspan(int x, int y, int len, RGBA_Floats[] colors, int colorIndex) { linkedImage.copy_color_vspan(x, y, len, colors, colorIndex); } public virtual void blend_solid_vspan(int x, int y, int len, RGBA_Floats c, byte[] covers, int coversIndex) { linkedImage.blend_solid_vspan(x, y, len, c, covers, coversIndex); } public virtual void blend_color_hspan(int x, int y, int len, RGBA_Floats[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { linkedImage.blend_color_hspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll); } public virtual void blend_color_vspan(int x, int y, int len, RGBA_Floats[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { linkedImage.blend_color_vspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll); } public float[] GetBuffer() { return linkedImage.GetBuffer(); } public int GetBufferOffsetY(int y) { return linkedImage.GetBufferOffsetY(y); } public int GetBufferOffsetXY(int x, int y) { return linkedImage.GetBufferOffsetXY(x, y); } public virtual int GetFloatsBetweenPixelsInclusive() { return linkedImage.GetFloatsBetweenPixelsInclusive(); } public virtual int BitDepth { get { return linkedImage.BitDepth; } } public void MarkImageChanged() { linkedImage.MarkImageChanged(); } } }
using System; using System.Text; namespace Org.BouncyCastle.Asn1.X509 { /** * Implementation of the RoleSyntax object as specified by the RFC3281. * * <pre> * RoleSyntax ::= SEQUENCE { * roleAuthority [0] GeneralNames OPTIONAL, * roleName [1] GeneralName * } * </pre> */ public class RoleSyntax : Asn1Encodable { private readonly GeneralNames roleAuthority; private readonly GeneralName roleName; /** * RoleSyntax factory method. * @param obj the object used to construct an instance of <code> * RoleSyntax</code>. It must be an instance of <code>RoleSyntax * </code> or <code>Asn1Sequence</code>. * @return the instance of <code>RoleSyntax</code> built from the * supplied object. * @throws java.lang.ArgumentException if the object passed * to the factory is not an instance of <code>RoleSyntax</code> or * <code>Asn1Sequence</code>. */ public static RoleSyntax GetInstance( object obj) { if (obj == null || obj is RoleSyntax) { return (RoleSyntax) obj; } if (obj is Asn1Sequence) { return new RoleSyntax((Asn1Sequence) obj); } throw new ArgumentException("unknown object in 'RoleSyntax' factory: " + obj.GetType().Name, "obj"); } /** * Constructor. * @param roleAuthority the role authority of this RoleSyntax. * @param roleName the role name of this RoleSyntax. */ public RoleSyntax( GeneralNames roleAuthority, GeneralName roleName) { if (roleName == null || roleName.TagNo != GeneralName.UniformResourceIdentifier || ((IAsn1String) roleName.Name).GetString().Equals("")) { throw new ArgumentException("the role name MUST be non empty and MUST " + "use the URI option of GeneralName"); } this.roleAuthority = roleAuthority; this.roleName = roleName; } /** * Constructor. Invoking this constructor is the same as invoking * <code>new RoleSyntax(null, roleName)</code>. * @param roleName the role name of this RoleSyntax. */ public RoleSyntax( GeneralName roleName) : this(null, roleName) { } /** * Utility constructor. Takes a <code>string</code> argument representing * the role name, builds a <code>GeneralName</code> to hold the role name * and calls the constructor that takes a <code>GeneralName</code>. * @param roleName */ public RoleSyntax( string roleName) : this(new GeneralName(GeneralName.UniformResourceIdentifier, (roleName == null)? "": roleName)) { } /** * Constructor that builds an instance of <code>RoleSyntax</code> by * extracting the encoded elements from the <code>Asn1Sequence</code> * object supplied. * @param seq an instance of <code>Asn1Sequence</code> that holds * the encoded elements used to build this <code>RoleSyntax</code>. */ private RoleSyntax( Asn1Sequence seq) { if (seq.Count < 1 || seq.Count > 2) { throw new ArgumentException("Bad sequence size: " + seq.Count); } for (int i = 0; i != seq.Count; i++) { Asn1TaggedObject taggedObject = Asn1TaggedObject.GetInstance(seq[i]); switch (taggedObject.TagNo) { case 0: roleAuthority = GeneralNames.GetInstance(taggedObject, false); break; case 1: roleName = GeneralName.GetInstance(taggedObject, true); break; default: throw new ArgumentException("Unknown tag in RoleSyntax"); } } } /** * Gets the role authority of this RoleSyntax. * @return an instance of <code>GeneralNames</code> holding the * role authority of this RoleSyntax. */ public GeneralNames RoleAuthority { get { return this.roleAuthority; } } /** * Gets the role name of this RoleSyntax. * @return an instance of <code>GeneralName</code> holding the * role name of this RoleSyntax. */ public GeneralName RoleName { get { return this.roleName; } } /** * Gets the role name as a <code>java.lang.string</code> object. * @return the role name of this RoleSyntax represented as a * <code>string</code> object. */ public string GetRoleNameAsString() { return ((IAsn1String) this.roleName.Name).GetString(); } /** * Gets the role authority as a <code>string[]</code> object. * @return the role authority of this RoleSyntax represented as a * <code>string[]</code> array. */ public string[] GetRoleAuthorityAsString() { if (roleAuthority == null) { return new string[0]; } GeneralName[] names = roleAuthority.GetNames(); string[] namesString = new string[names.Length]; for(int i = 0; i < names.Length; i++) { Asn1Encodable asn1Value = names[i].Name; if (asn1Value is IAsn1String) { namesString[i] = ((IAsn1String) asn1Value).GetString(); } else { namesString[i] = asn1Value.ToString(); } } return namesString; } /** * Implementation of the method <code>ToAsn1Object</code> as * required by the superclass <code>ASN1Encodable</code>. * * <pre> * RoleSyntax ::= SEQUENCE { * roleAuthority [0] GeneralNames OPTIONAL, * roleName [1] GeneralName * } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(); if (this.roleAuthority != null) { v.Add(new DerTaggedObject(false, 0, roleAuthority)); } v.Add(new DerTaggedObject(true, 1, roleName)); return new DerSequence(v); } public override string ToString() { StringBuilder buff = new StringBuilder("Name: " + this.GetRoleNameAsString() + " - Auth: "); if (this.roleAuthority == null || roleAuthority.GetNames().Length == 0) { buff.Append("N/A"); } else { string[] names = this.GetRoleAuthorityAsString(); buff.Append('[').Append(names[0]); for(int i = 1; i < names.Length; i++) { buff.Append(", ").Append(names[i]); } buff.Append(']'); } return buff.ToString(); } } }
using System; using System.Linq; using Moscrif.IDE.Editors; using Moscrif.IDE.Task; using System.Collections.Generic; using Moscrif.IDE.Workspace; using Moscrif.IDE.Iface.Entities; using Moscrif.IDE.Option; namespace Moscrif.IDE.Controls { public partial class FindReplaceControl : Gtk.Bin { private bool ignoreTextChange = false; List<string> textExtension = new List<string>(); public FindReplaceControl() { this.Build(); this.cbPlace.Active = 0; textExtension = MainClass.Tools.GetAllExtension(ExtensionSetting.OpenTyp.TEXT); } protected virtual void OnButton1Clicked(object sender, System.EventArgs e) { string expresion = this.entrExpresion.Text; if (!String.IsNullOrEmpty(expresion)) { SearchPattern sp = GetSearchPattern(); if(cbPlace.Active == 0){ MainClass.MainWindow.EditorNotebook.SearchNext(); } else { sp.ReplaceExpresion = null; StartFindReplaceInFiles(sp); } } } private SearchPattern GetSearchPattern(){ SearchPattern sp = new SearchPattern(); sp.CaseSensitive = this.chbCaseSensitive.Active; sp.WholeWorlds = this.chbWholeWords.Active; sp.Expresion = this.entrExpresion.Text; sp.CloseFiles = new List<string>(); sp.OpenFiles = new List<string>(); switch (cbPlace.Active) { case 0:{ sp.SearchTyp = SearchPattern.TypSearch.CurentDocument; break; } case 1:{ sp.SearchTyp = SearchPattern.TypSearch.AllOpenDocument; sp.OpenFiles = new List<string>(MainClass.MainWindow.EditorNotebook.OpenFiles.ToArray()); break; } case 2:{ sp.SearchTyp = SearchPattern.TypSearch.CurentProject; if(MainClass.Workspace.ActualProject == null) return sp; MainClass.Workspace.ActualProject.GetAllFiles(ref sp.CloseFiles,MainClass.Workspace.ActualProject.AbsolutProjectDir,textExtension,true); break; } case 3:{ sp.SearchTyp = SearchPattern.TypSearch.AllOpenProject; foreach (Project p in MainClass.Workspace.Projects) p.GetAllFiles(ref sp.CloseFiles,p.AbsolutProjectDir,textExtension,true); break; } } return sp; } private void SetSearch(){ string expresion = this.entrExpresion.Text; if (!String.IsNullOrEmpty(expresion)) { SearchPattern sp = GetSearchPattern(); if(cbPlace.Active == 0) MainClass.MainWindow.EditorNotebook.Search(sp); } } private void StartFindReplaceInFiles(SearchPattern sp){ MainClass.MainWindow.FindOutput.Clear(); // first - find/replace in open files List<string> notOpen = new List<string>(sp.CloseFiles); List<string> opened = new List<string>(sp.OpenFiles); List<string> allOpened = new List<string>(MainClass.MainWindow.EditorNotebook.OpenFiles); // files in not opened -vsetky subory rozdelime na otvorene a zavrete if(sp.CloseFiles.Count>0){ // Except(sp.CloseFiles,allOpened); notOpen =new List<string>(sp.CloseFiles.Except(allOpened,StringComparer.CurrentCultureIgnoreCase).ToList().ToArray()); opened = new List<string>(sp.CloseFiles.Except(notOpen,StringComparer.CurrentCultureIgnoreCase).ToList().ToArray()); sp.CloseFiles = new List<string>(notOpen); sp.OpenFiles = new List<string>(opened); } TaskList tl = new TaskList(); /*if(opened.Count>0){ SearchPattern spO = sp.Clone(); spO.OpenFiles = new List<string>(opened); FindInOpenFileTask rt = new FindInOpenFileTask(); rt.Initialize(spO); tl.TasksList.Clear(); tl.TasksList.Add(rt); sp.CloseFiles = new List<string>(notOpen); }*/ // find replace in closed files FindReplaceTask ft = new FindReplaceTask(); //ReplaceTask ft = new ReplaceTask(); ft.Initialize(sp); tl.TasksList.Add(ft); MainClass.MainWindow.RunSecondaryTaskList(tl, MainClass.MainWindow.FindOutputWritte,false); } public void SetFocus(){ entrExpresion.GrabFocus(); } public void SetFindText(string text){ if(!String.IsNullOrEmpty(text)){ ignoreTextChange = true; entrExpresion.Text = text; } } protected virtual void OnEntrExpresionChanged(object sender, System.EventArgs e) { if(cbPlace.Active != 0) return; string expresion = entrExpresion.Text; if (!String.IsNullOrEmpty(expresion)) { SearchPattern sp = GetSearchPattern(); if(cbPlace.Active == 0){ if(!ignoreTextChange){ MainClass.MainWindow.EditorNotebook.Search(sp); } else { MainClass.MainWindow.EditorNotebook.SetSearchExpresion(sp); ignoreTextChange = false; } } } } protected virtual void OnBtnReplaceClicked(object sender, System.EventArgs e) { string expresion = entrExpresion.Text; string replaceExpresion = entrReplaceText.Text; if (String.IsNullOrEmpty(expresion)) return; if (String.IsNullOrEmpty(replaceExpresion)) return; SearchPattern sp = GetSearchPattern(); sp.ReplaceExpresion = replaceExpresion; if(cbPlace.Active == 0){ MainClass.MainWindow.EditorNotebook.Replace(sp); }else { /* TaskList tl = new TaskList(); FindTask ft = new FindTask(); ft.Initialize(sp); tl.TasksList.Clear(); tl.TasksList.Add(ft); MainClass.MainWindow.RunSecondaryTaskList(tl, MainClass.MainWindow.FindOutputWritte);*/ } } protected virtual void OnBtnReplaceAllClicked(object sender, System.EventArgs e) { string expresion = entrExpresion.Text; string replaceExpresion = entrReplaceText.Text; if (String.IsNullOrEmpty(expresion)) return; if (String.IsNullOrEmpty(replaceExpresion)) return; SearchPattern sp = GetSearchPattern(); sp.ReplaceExpresion = replaceExpresion; if(cbPlace.Active == 0){ MainClass.MainWindow.EditorNotebook.ReplaceAll(sp); }else { StartFindReplaceInFiles(sp); } } protected virtual void OnEntrExpresionKeyReleaseEvent(object o, Gtk.KeyReleaseEventArgs args) { //if(cbPlace.Active != 0) return; if (args.Event.Key == Gdk.Key.Return) { string expresion = entrExpresion.Text; if (!String.IsNullOrEmpty(expresion)) { SearchPattern sp = GetSearchPattern(); if(cbPlace.Active == 0){ MainClass.MainWindow.EditorNotebook.SearchNext(); } else { sp.ReplaceExpresion = null; StartFindReplaceInFiles(sp); } } } } protected void OnEntrReplaceTextKeyReleaseEvent (object o, Gtk.KeyReleaseEventArgs args) { if (String.IsNullOrEmpty(entrExpresion.Text)) return; if (String.IsNullOrEmpty(entrReplaceText.Text)) return; //if(cbPlace.Active != 0) return; if (args.Event.Key == Gdk.Key.Return) { string expresion = entrExpresion.Text; if (!String.IsNullOrEmpty(expresion)) { SearchPattern sp = GetSearchPattern(); sp.ReplaceExpresion = entrReplaceText.Text; if(cbPlace.Active == 0){ MainClass.MainWindow.EditorNotebook.Replace(sp); } else { StartFindReplaceInFiles(sp); } } } } protected virtual void OnChbWholeWordsToggled (object sender, System.EventArgs e) { SetSearch(); } protected virtual void OnChbCaseSensitiveToggled (object sender, System.EventArgs e) { SetSearch(); } protected void OnCbPlaceChanged (object sender, System.EventArgs e) { if(cbPlace.Active!= 0){ btnReplace.Sensitive = false; } else { btnReplace.Sensitive = true; SetSearch(); } } } }
//#define ASTAR_NoTagPenalty using UnityEngine; using Pathfinding; using Pathfinding.Serialization; namespace Pathfinding { public interface INavmeshHolder { Int3 GetVertex (int i); int GetVertexArrayIndex(int index); void GetTileCoordinates (int tileIndex, out int x, out int z); } /** Node represented by a triangle */ public class TriangleMeshNode : MeshNode { public TriangleMeshNode (AstarPath astar) : base(astar) {} public int v0, v1, v2; protected static INavmeshHolder[] _navmeshHolders = new INavmeshHolder[0]; public static INavmeshHolder GetNavmeshHolder (uint graphIndex) { return _navmeshHolders[(int)graphIndex]; } public static void SetNavmeshHolder (int graphIndex, INavmeshHolder graph) { if (_navmeshHolders.Length <= graphIndex) { INavmeshHolder[] gg = new INavmeshHolder[graphIndex+1]; for (int i=0;i<_navmeshHolders.Length;i++) gg[i] = _navmeshHolders[i]; _navmeshHolders = gg; } _navmeshHolders[graphIndex] = graph; } public void UpdatePositionFromVertices () { INavmeshHolder g = GetNavmeshHolder(GraphIndex); position = (g.GetVertex(v0) + g.GetVertex(v1) + g.GetVertex(v2)) * 0.333333f; } /** Return a number identifying a vertex. * This number does not necessarily need to be a index in an array but two different vertices (in the same graph) should * not have the same vertex numbers. */ public int GetVertexIndex (int i) { return i == 0 ? v0 : (i == 1 ? v1 : v2); } /** Return a number specifying an index in the source vertex array. * The vertex array can for example be contained in a recast tile, or be a navmesh graph, that is graph dependant. * This is slower than GetVertexIndex, if you only need to compare vertices, use GetVertexIndex. */ public int GetVertexArrayIndex (int i) { return GetNavmeshHolder(GraphIndex).GetVertexArrayIndex (i == 0 ? v0 : (i == 1 ? v1 : v2)); } public override Int3 GetVertex (int i) { return GetNavmeshHolder(GraphIndex).GetVertex (GetVertexIndex(i)); } public override int GetVertexCount () { return 3; } public override Vector3 ClosestPointOnNode (Vector3 p) { INavmeshHolder g = GetNavmeshHolder(GraphIndex); return Pathfinding.Polygon.ClosestPointOnTriangle ((Vector3)g.GetVertex(v0), (Vector3)g.GetVertex(v1), (Vector3)g.GetVertex(v2), p); } public override Vector3 ClosestPointOnNodeXZ (Vector3 _p) { INavmeshHolder g = GetNavmeshHolder(GraphIndex); Int3 tp1 = g.GetVertex(v0); Int3 tp2 = g.GetVertex(v1); Int3 tp3 = g.GetVertex(v2); Int3 p = (Int3)_p; int oy = p.y; // Assumes the triangle vertices are laid out in (counter?)clockwise order tp1.y = 0; tp2.y = 0; tp3.y = 0; p.y = 0; if ((long)(tp2.x - tp1.x) * (long)(p.z - tp1.z) - (long)(p.x - tp1.x) * (long)(tp2.z - tp1.z) > 0) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp1, tp2, p)); return new Vector3(tp1.x + (tp2.x-tp1.x)*f, oy, tp1.z + (tp2.z-tp1.z)*f)*Int3.PrecisionFactor; } else if ((long)(tp3.x - tp2.x) * (long)(p.z - tp2.z) - (long)(p.x - tp2.x) * (long)(tp3.z - tp2.z) > 0) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp2, tp3, p)); return new Vector3(tp2.x + (tp3.x-tp2.x)*f, oy, tp2.z + (tp3.z-tp2.z)*f)*Int3.PrecisionFactor; } else if ((long)(tp1.x - tp3.x) * (long)(p.z - tp3.z) - (long)(p.x - tp3.x) * (long)(tp1.z - tp3.z) > 0) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp3, tp1, p)); return new Vector3(tp3.x + (tp1.x-tp3.x)*f, oy, tp3.z + (tp1.z-tp3.z)*f)*Int3.PrecisionFactor; } else { return _p; } /* * Equivalent to the above, but the above uses manual inlining if (!Polygon.Left (tp1, tp2, p)) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp1, tp2, p)); return new Vector3(tp1.x + (tp2.x-tp1.x)*f, oy, tp1.z + (tp2.z-tp1.z)*f)*Int3.PrecisionFactor; } else if (!Polygon.Left (tp2, tp3, p)) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp2, tp3, p)); return new Vector3(tp2.x + (tp3.x-tp2.x)*f, oy, tp2.z + (tp3.z-tp2.z)*f)*Int3.PrecisionFactor; } else if (!Polygon.Left (tp3, tp1, p)) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp3, tp1, p)); return new Vector3(tp3.x + (tp1.x-tp3.x)*f, oy, tp3.z + (tp1.z-tp3.z)*f)*Int3.PrecisionFactor; } else { return _p; }*/ /* Almost equivalent to the above, but this is slower Vector3 tp1 = (Vector3)g.GetVertex(v0); Vector3 tp2 = (Vector3)g.GetVertex(v1); Vector3 tp3 = (Vector3)g.GetVertex(v2); tp1.y = 0; tp2.y = 0; tp3.y = 0; _p.y = 0; return Pathfinding.Polygon.ClosestPointOnTriangle (tp1,tp2,tp3,_p);*/ } public override bool ContainsPoint (Int3 p) { INavmeshHolder g = GetNavmeshHolder(GraphIndex); Int3 a = g.GetVertex(v0); Int3 b = g.GetVertex(v1); Int3 c = g.GetVertex(v2); if ((long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) > 0) return false; if ((long)(c.x - b.x) * (long)(p.z - b.z) - (long)(p.x - b.x) * (long)(c.z - b.z) > 0) return false; if ((long)(a.x - c.x) * (long)(p.z - c.z) - (long)(p.x - c.x) * (long)(a.z - c.z) > 0) return false; return true; //return Polygon.IsClockwiseMargin (a,b, p) && Polygon.IsClockwiseMargin (b,c, p) && Polygon.IsClockwiseMargin (c,a, p); //return Polygon.ContainsPoint(g.GetVertex(v0),g.GetVertex(v1),g.GetVertex(v2),p); } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { UpdateG (path,pathNode); handler.PushNode (pathNode); if (connections == null) return; for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG (path, otherPN,handler); } } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; bool flag2 = pathNode.flag2; for (int i=connections.Length-1;i >= 0;i--) { GraphNode other = connections[i]; if (path.CanTraverse (other)) { PathNode pathOther = handler.GetPathNode (other); //Fast path out, worth it for triangle mesh nodes since they usually have degree 2 or 3 if (pathOther == pathNode.parent) { continue; } uint cost = connectionCosts[i]; if (flag2 || pathOther.flag2) { cost = path.GetConnectionSpecialCost (this,other,cost); } if (pathOther.pathID != handler.PathID) { //Might not be assigned pathOther.node = other; pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = cost; pathOther.H = path.CalculateHScore (other); other.UpdateG (path, pathOther); handler.PushNode (pathOther); } else { //If not we can test if the path from this node to the other one is a better one than the one already used if (pathNode.G + cost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = cost; pathOther.parent = pathNode; other.UpdateRecursiveG (path, pathOther,handler); //handler.PushNode (pathOther); } else if (pathOther.G+cost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) { //Or if the path from the other node to this one is better pathNode.parent = pathOther; pathNode.cost = cost; UpdateRecursiveG (path, pathNode,handler); //handler.PushNode (pathNode); } } } } } /** Returns the edge which is shared with \a other. * If no edge is shared, -1 is returned. * The edge is GetVertex(result) - GetVertex((result+1) % GetVertexCount()). * See GetPortal for the exact segment shared. * \note Might return that an edge is shared when the two nodes are in different tiles and adjacent on the XZ plane, but on the Y-axis. * Therefore it is recommended that you only test for neighbours of this node or do additional checking afterwards. */ public int SharedEdge (GraphNode other) { //Debug.Log ("SHARED"); int a, b; GetPortal(other, null, null, false, out a, out b); //Debug.Log ("/SHARED"); return a; } public override bool GetPortal (GraphNode _other, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards) { int aIndex, bIndex; return GetPortal (_other,left,right,backwards, out aIndex, out bIndex); } public bool GetPortal (GraphNode _other, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards, out int aIndex, out int bIndex) { aIndex = -1; bIndex = -1; //If the nodes are in different graphs, this function has no idea on how to find a shared edge. if (_other.GraphIndex != GraphIndex) return false; TriangleMeshNode other = _other as TriangleMeshNode; //Get tile indices int tileIndex = (GetVertexIndex(0) >> RecastGraph.TileIndexOffset) & RecastGraph.TileIndexMask; int tileIndex2 = (other.GetVertexIndex(0) >> RecastGraph.TileIndexOffset) & RecastGraph.TileIndexMask; //When the nodes are in different tiles, the edges might not be completely identical //so another technique is needed //Only do this on recast graphs if (tileIndex != tileIndex2 && ( GetNavmeshHolder(GraphIndex) is RecastGraph)) { for ( int i=0;i<connections.Length;i++) { if ( connections[i].GraphIndex != GraphIndex ) { #if !ASTAR_NO_POINT_GRAPH NodeLink3Node mid = connections[i] as NodeLink3Node; if ( mid != null && mid.GetOther (this) == other ) { // We have found a node which is connected through a NodeLink3Node if ( left != null ) { mid.GetPortal ( other, left, right, false ); return true; } } #endif } } //Get the tile coordinates, from them we can figure out which edge is going to be shared int x1, x2, z1, z2; int coord; INavmeshHolder nm = GetNavmeshHolder (GraphIndex); nm.GetTileCoordinates(tileIndex, out x1, out z1); nm.GetTileCoordinates(tileIndex2, out x2, out z2); if (System.Math.Abs(x1-x2) == 1) coord = 0; else if (System.Math.Abs(z1-z2) == 1) coord = 2; else throw new System.Exception ("Tiles not adjacent (" + x1+", " + z1 +") (" + x2 + ", " + z2+")"); int av = GetVertexCount (); int bv = other.GetVertexCount (); //Try the X and Z coordinate. For one of them the coordinates should be equal for one of the two nodes' edges //The midpoint between the tiles is the only place where they will be equal int first = -1, second = -1; //Find the shared edge for (int a=0;a<av;a++) { int va = GetVertex(a)[coord]; for (int b=0;b<bv;b++) { if (va == other.GetVertex((b+1)%bv)[coord] && GetVertex((a+1) % av)[coord] == other.GetVertex(b)[coord]) { first = a; second = b; a = av; break; } } } aIndex = first; bIndex = second; if (first != -1) { Int3 a = GetVertex(first); Int3 b = GetVertex((first+1)%av); //The coordinate which is not the same for the vertices int ocoord = coord == 2 ? 0 : 2; //When the nodes are in different tiles, they might not share exactly the same edge //so we clamp the portal to the segment of the edges which they both have. int mincoord = System.Math.Min(a[ocoord], b[ocoord]); int maxcoord = System.Math.Max(a[ocoord], b[ocoord]); mincoord = System.Math.Max (mincoord, System.Math.Min(other.GetVertex(second)[ocoord], other.GetVertex((second+1)%bv)[ocoord])); maxcoord = System.Math.Min (maxcoord, System.Math.Max(other.GetVertex(second)[ocoord], other.GetVertex((second+1)%bv)[ocoord])); if (a[ocoord] < b[ocoord]) { a[ocoord] = mincoord; b[ocoord] = maxcoord; } else { a[ocoord] = maxcoord; b[ocoord] = mincoord; } if (left != null) { //All triangles should be clockwise so second is the rightmost vertex (seen from this node) left.Add ((Vector3)a); right.Add ((Vector3)b); } return true; } } else if (!backwards) { int first = -1; int second = -1; int av = GetVertexCount (); int bv = other.GetVertexCount (); /** \todo Maybe optimize with pa=av-1 instead of modulus... */ for (int a=0;a<av;a++) { int va = GetVertexIndex(a); for (int b=0;b<bv;b++) { if (va == other.GetVertexIndex((b+1)%bv) && GetVertexIndex((a+1) % av) == other.GetVertexIndex(b)) { first = a; second = b; a = av; break; } } } aIndex = first; bIndex = second; if (first != -1) { if (left != null) { //All triangles should be clockwise so second is the rightmost vertex (seen from this node) left.Add ((Vector3)GetVertex(first)); right.Add ((Vector3)GetVertex((first+1)%av)); } } else { for ( int i=0;i<connections.Length;i++) { if ( connections[i].GraphIndex != GraphIndex ) { #if !ASTAR_NO_POINT_GRAPH NodeLink3Node mid = connections[i] as NodeLink3Node; if ( mid != null && mid.GetOther (this) == other ) { // We have found a node which is connected through a NodeLink3Node if ( left != null ) { mid.GetPortal ( other, left, right, false ); return true; } } #endif } } return false; } } return true; } public override void SerializeNode (GraphSerializationContext ctx) { base.SerializeNode (ctx); ctx.writer.Write(v0); ctx.writer.Write(v1); ctx.writer.Write(v2); } public override void DeserializeNode (GraphSerializationContext ctx) { base.DeserializeNode (ctx); v0 = ctx.reader.ReadInt32(); v1 = ctx.reader.ReadInt32(); v2 = ctx.reader.ReadInt32(); } } public class ConvexMeshNode : MeshNode { public ConvexMeshNode (AstarPath astar) : base(astar) { indices = new int[0];//\todo Set indices to some reasonable value } private int[] indices; //private new Int3 position; static ConvexMeshNode () { //Should register to a delegate to receive updates whenever graph lists are changed } protected static INavmeshHolder[] navmeshHolders = new INavmeshHolder[0]; protected static INavmeshHolder GetNavmeshHolder (uint graphIndex) { return navmeshHolders[(int)graphIndex]; } /*public override Int3 Position { get { return position; } }*/ public void SetPosition (Int3 p) { position = p; } public int GetVertexIndex (int i) { return indices[i]; } public override Int3 GetVertex (int i) { return GetNavmeshHolder(GraphIndex).GetVertex (GetVertexIndex(i)); } public override int GetVertexCount () { return indices.Length; } public override Vector3 ClosestPointOnNode (Vector3 p) { throw new System.NotImplementedException (); } public override Vector3 ClosestPointOnNodeXZ (Vector3 p) { throw new System.NotImplementedException (); } public override void GetConnections (GraphNodeDelegate del) { if (connections == null) return; for (int i=0;i<connections.Length;i++) del (connections[i]); } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; if (path.CanTraverse (other)) { PathNode pathOther = handler.GetPathNode (other); if (pathOther.pathID != handler.PathID) { pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = connectionCosts[i]; pathOther.H = path.CalculateHScore (other); other.UpdateG (path, pathOther); handler.PushNode (pathOther); } else { //If not we can test if the path from this node to the other one is a better one then the one already used uint tmpCost = connectionCosts[i]; if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = tmpCost; pathOther.parent = pathNode; other.UpdateRecursiveG (path, pathOther,handler); //handler.PushNode (pathOther); } else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) { //Or if the path from the other node to this one is better pathNode.parent = pathOther; pathNode.cost = tmpCost; UpdateRecursiveG (path, pathNode,handler); //handler.PushNode (pathNode); } } } } } } /*public class ConvexMeshNode : GraphNode { //Vertices public int v1; public int v2; public int v3; public int GetVertexIndex (int i) { if (i == 0) { return v1; } else if (i == 1) { return v2; } else if (i == 2) { return v3; } else { throw new System.ArgumentOutOfRangeException ("A MeshNode only contains 3 vertices"); } } public int this[int i] { get { if (i == 0) { return v1; } else if (i == 1) { return v2; } else if (i == 2) { return v3; } else { throw new System.ArgumentOutOfRangeException ("A MeshNode only contains 3 vertices"); } } } public Vector3 ClosestPoint (Vector3 p, Int3[] vertices) { return Polygon.ClosestPointOnTriangle ((Vector3)vertices[v1],(Vector3)vertices[v2],(Vector3)vertices[v3],p); } }*/ }
// 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. #if XMLSERIALIZERGENERATOR namespace Microsoft.XmlSerializer.Generator #else namespace System.Xml.Serialization #endif { using System.Reflection; using System.Collections; using System.IO; using System.Xml.Schema; using System; using System.Text; using System.Threading; using System.Globalization; using System.Security; using System.Xml.Serialization.Configuration; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.Versioning; using System.Xml; /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public struct XmlDeserializationEvents { private XmlNodeEventHandler _onUnknownNode; private XmlAttributeEventHandler _onUnknownAttribute; private XmlElementEventHandler _onUnknownElement; private UnreferencedObjectEventHandler _onUnreferencedObject; internal object sender; /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownNode"]/*' /> public XmlNodeEventHandler OnUnknownNode { get { return _onUnknownNode; } set { _onUnknownNode = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownAttribute"]/*' /> public XmlAttributeEventHandler OnUnknownAttribute { get { return _onUnknownAttribute; } set { _onUnknownAttribute = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownElement"]/*' /> public XmlElementEventHandler OnUnknownElement { get { return _onUnknownElement; } set { _onUnknownElement = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnreferencedObject"]/*' /> public UnreferencedObjectEventHandler OnUnreferencedObject { get { return _onUnreferencedObject; } set { _onUnreferencedObject = value; } } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' /> ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract class XmlSerializerImplementation { /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' /> public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' /> public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' /> public virtual Hashtable ReadMethods { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' /> public virtual Hashtable WriteMethods { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' /> public virtual Hashtable TypedSerializers { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' /> public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' /> public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSerializer { internal enum SerializationMode { CodeGenOnly, ReflectionOnly, ReflectionAsBackup } internal static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup; private static bool ReflectionMethodEnabled { get { return Mode == SerializationMode.ReflectionOnly || Mode == SerializationMode.ReflectionAsBackup; } } private TempAssembly _tempAssembly; #pragma warning disable 0414 private bool _typedSerializer; #pragma warning restore 0414 private Type _primitiveType; private XmlMapping _mapping; private XmlDeserializationEvents _events = new XmlDeserializationEvents(); #if uapaot private XmlSerializer innerSerializer; public string DefaultNamespace = null; #else internal string DefaultNamespace = null; #endif private Type _rootType; private static TempAssemblyCache s_cache = new TempAssemblyCache(); private static volatile XmlSerializerNamespaces s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get { if (s_defaultNamespaces == null) { XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.AddInternal("xsi", XmlSchema.InstanceNamespace); nss.AddInternal("xsd", XmlSchema.Namespace); if (s_defaultNamespaces == null) { s_defaultNamespaces = nss; } } return s_defaultNamespaces; } } private static readonly Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>>(); /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' /> ///<internalonly/> protected XmlSerializer() { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if !uapaot public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null) #else public XmlSerializer(Type type, Type[] extraTypes) : this(type) #endif { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(XmlTypeMapping xmlTypeMapping) { if (xmlTypeMapping == null) throw new ArgumentNullException(nameof(xmlTypeMapping)); #if !uapaot _tempAssembly = GenerateTempAssembly(xmlTypeMapping); #endif _mapping = xmlTypeMapping; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type) : this(type, (string)null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, string defaultNamespace) { if (type == null) throw new ArgumentNullException(nameof(type)); DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GetKnownMapping(type, defaultNamespace); if (_mapping != null) { _primitiveType = type; return; } #if !uapaot _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { { XmlSerializerImplementation contract = null; Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, null, out contract); if (assembly == null) { // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); } else { // we found the pre-generated assembly, now make sure that the assembly has the right serializer // try to avoid the reflection step, need to get ElementName, namespace and the Key form the type _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); _tempAssembly = new TempAssembly(new XmlMapping[] { _mapping }, assembly, contract); } } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } #else XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly(); if (contract != null) { this.innerSerializer = contract.GetSerializer(type); } else if (ReflectionMethodEnabled) { var importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } } #endif } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) { if (type == null) throw new ArgumentNullException(nameof(type)); DefaultNamespace = defaultNamespace; _rootType = type; XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) importer.IncludeType(extraTypes[i]); } _mapping = importer.ImportTypeMapping(type, root, defaultNamespace); #if !uapaot _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location); #endif } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace) { return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location) { if (xmlMapping == null) { throw new ArgumentNullException(nameof(xmlMapping)); } xmlMapping.CheckShallow(); if (xmlMapping.IsSoap) { return null; } return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o) { Serialize(textWriter, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(textWriter); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; Serialize(xmlWriter, o, namespaces); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o) { Serialize(stream, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; Serialize(xmlWriter, o, namespaces); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o) { Serialize(xmlWriter, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { Serialize(xmlWriter, o, namespaces, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' /> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' /> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } SerializePrimitive(xmlWriter, o, namespaces); } #if !uapaot else if (ShouldUseReflectionBasedSerialization()) { XmlMapping mapping; if (_mapping != null && _mapping.GenerateSerializer) { mapping = _mapping; } else { XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace); mapping = importer.ImportTypeMapping(_rootType, null, DefaultNamespace); } var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); writer.WriteObject(o); } else if (_tempAssembly == null || _typedSerializer) { // The contion for the block is never true, thus the block is never hit. XmlSerializationWriter writer = CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly); try { Serialize(o, writer); } finally { writer.Dispose(); } } else _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); #else else { if (this.innerSerializer != null) { if (!string.IsNullOrEmpty(this.DefaultNamespace)) { this.innerSerializer.DefaultNamespace = this.DefaultNamespace; } XmlSerializationWriter writer = this.innerSerializer.CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); try { this.innerSerializer.Serialize(o, writer); } finally { writer.Dispose(); } } else if (ReflectionMethodEnabled) { XmlMapping mapping; if (_mapping != null && _mapping.GenerateSerializer) { mapping = _mapping; } else { XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace); mapping = importer.ImportTypeMapping(_rootType, null, DefaultNamespace); } var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); writer.WriteObject(o); } else { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this._rootType, typeof(XmlSerializer).Name)); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; throw new InvalidOperationException(SR.XmlGenError, e); } xmlWriter.Flush(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(Stream stream) { XmlTextReader xmlReader = new XmlTextReader(stream); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize3"]/*' /> public object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { return Deserialize(xmlReader, null, events); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' /> public object Deserialize(XmlReader xmlReader, string encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' /> public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) { events.sender = this; try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } return DeserializePrimitive(xmlReader, events); } #if !uapaot else if (ShouldUseReflectionBasedSerialization()) { XmlMapping mapping; if (_mapping != null && _mapping.GenerateSerializer) { mapping = _mapping; } else { XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace); mapping = importer.ImportTypeMapping(_rootType, null, DefaultNamespace); } var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); return reader.ReadObject(); } else if (_tempAssembly == null || _typedSerializer) { XmlSerializationReader reader = CreateReader(); reader.Init(xmlReader, events, encodingStyle, _tempAssembly); try { return Deserialize(reader); } finally { reader.Dispose(); } } else { return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } #else else { if (this.innerSerializer != null) { if (!string.IsNullOrEmpty(this.DefaultNamespace)) { this.innerSerializer.DefaultNamespace = this.DefaultNamespace; } XmlSerializationReader reader = this.innerSerializer.CreateReader(); reader.Init(xmlReader, encodingStyle); try { return this.innerSerializer.Deserialize(reader); } finally { reader.Dispose(); } } else if (ReflectionMethodEnabled) { XmlMapping mapping; if (_mapping != null && _mapping.GenerateSerializer) { mapping = _mapping; } else { XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace); mapping = importer.ImportTypeMapping(_rootType, null, DefaultNamespace); } var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); return reader.ReadObject(); } else { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this._rootType, typeof(XmlSerializer).Name)); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; if (xmlReader is IXmlLineInfo) { IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e); } else { throw new InvalidOperationException(SR.XmlSerializeError, e); } } } private bool ShouldUseReflectionBasedSerialization() { return Mode == SerializationMode.ReflectionOnly || (_mapping != null && _mapping.IsSoap); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]; return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty); } #if !uapaot else if (_tempAssembly != null) { return _tempAssembly.CanRead(_mapping, xmlReader); } else { return false; } #else if (this.innerSerializer != null) { return this.innerSerializer.CanDeserialize(xmlReader); } else { return ReflectionMethodEnabled; } #endif } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings) { return FromMappings(mappings, (Type)null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>(); #if uapaot var serializers = new XmlSerializer[mappings.Length]; for(int i=0;i<mappings.Length;i++) { serializers[i] = new XmlSerializer(); serializers[i]._rootType = type; serializers[i]._mapping = mappings[i]; } return serializers; #else XmlSerializerImplementation contract = null; Assembly assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); TempAssembly tempAssembly = null; if (assembly == null) { if (XmlMapping.IsShallow(mappings)) { return Array.Empty<XmlSerializer>(); } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } return serializers; } else { // Use XmlSerializer cache when the type is not null. return GetSerializersFromCache(mappings, type); } } } else { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; return serializers; } #endif } #if XMLSERIALIZERGENERATOR [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [ResourceExposure(ResourceScope.None)] public static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, string codePath) { if (types == null || types.Length == 0) return false; if (mappings == null) throw new ArgumentNullException(nameof(mappings)); if(!Directory.Exists(codePath)) { throw new ArgumentException(SR.Format(SR.XmlMelformMapping)); } if (XmlMapping.IsShallow(mappings)) { throw new InvalidOperationException(SR.Format(SR.XmlMelformMapping)); } Assembly assembly = null; for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, type.FullName)); } if (assembly == null) { assembly = type.Assembly; } else if (type.Assembly != assembly) { throw new ArgumentException(SR.Format(SR.XmlPregenOrphanType, type.FullName, assembly.Location), "types"); } } return TempAssembly.GenerateSerializerFile(mappings, types, null, assembly, new Hashtable(), codePath); } #endif private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; Dictionary<XmlSerializerMappingKey, XmlSerializer> typedMappingTable = null; lock (s_xmlSerializerTable) { if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable)) { typedMappingTable = new Dictionary<XmlSerializerMappingKey, XmlSerializer>(); s_xmlSerializerTable[type] = typedMappingTable; } } lock (typedMappingTable) { var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>(); for (int i = 0; i < mappings.Length; i++) { XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]); if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i])) { pendingKeys.Add(mappingKey, i); } } if (pendingKeys.Count > 0) { XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count]; int index = 0; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { pendingMappings[index++] = mappingKey.Mapping; } TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null); XmlSerializerImplementation contract = tempAssembly.Contract; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = pendingKeys[mappingKey]; serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key]; serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping); typedMappingTable[mappingKey] = serializers[index]; } } } return serializers; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromTypes(Type[] types) { if (types == null) return Array.Empty<XmlSerializer>(); #if uapaot var serializers = new XmlSerializer[types.Length]; for (int i = 0; i < types.Length; i++) { serializers[i] = new XmlSerializer(types[i]); } return serializers; #else XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } return FromMappings(mappings); #endif } #if uapaot // this the global XML serializer contract introduced for multi-file private static XmlSerializerImplementation xmlSerializerContract; internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly() { // hack to pull in SetXmlSerializerContract which is only referenced from the // code injected by MainMethodInjector transform // there's probably also a way to do this via [DependencyReductionRoot], // but I can't get the compiler to find that... if (xmlSerializerContract == null) SetXmlSerializerContract(null); // this method body used to be rewritten by an IL transform // with the restructuring for multi-file, it has become a regular method return xmlSerializerContract; } public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation) { xmlSerializerContract = xmlSerializerImplementation; } #endif /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string GetXmlSerializerAssemblyName(Type type) { return GetXmlSerializerAssemblyName(type, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return Compiler.GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownNode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event XmlNodeEventHandler UnknownNode { add { _events.OnUnknownNode += value; } remove { _events.OnUnknownNode -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event XmlAttributeEventHandler UnknownAttribute { add { _events.OnUnknownAttribute += value; } remove { _events.OnUnknownAttribute -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownElement"]/*' /> public event XmlElementEventHandler UnknownElement { add { _events.OnUnknownElement += value; } remove { _events.OnUnknownElement -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnreferencedObject"]/*' /> public event UnreferencedObjectEventHandler UnreferencedObject { add { _events.OnUnreferencedObject += value; } remove { _events.OnUnreferencedObject -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' /> ///<internalonly/> protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' /> ///<internalonly/> protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' /> ///<internalonly/> protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' /> ///<internalonly/> protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { _tempAssembly = tempAssembly; _mapping = mapping; _typedSerializer = true; } private static XmlTypeMapping GetKnownMapping(Type type, string ns) { if (ns != null && ns != string.Empty) return null; TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type]; if (typeDesc == null) return null; ElementAccessor element = new ElementAccessor(); element.Name = typeDesc.DataType.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); switch (_primitiveType.GetTypeCode()) { case TypeCode.String: writer.Write_string(o); break; case TypeCode.Int32: writer.Write_int(o); break; case TypeCode.Boolean: writer.Write_boolean(o); break; case TypeCode.Int16: writer.Write_short(o); break; case TypeCode.Int64: writer.Write_long(o); break; case TypeCode.Single: writer.Write_float(o); break; case TypeCode.Double: writer.Write_double(o); break; case TypeCode.Decimal: writer.Write_decimal(o); break; case TypeCode.DateTime: writer.Write_dateTime(o); break; case TypeCode.Char: writer.Write_char(o); break; case TypeCode.Byte: writer.Write_unsignedByte(o); break; case TypeCode.SByte: writer.Write_byte(o); break; case TypeCode.UInt16: writer.Write_unsignedShort(o); break; case TypeCode.UInt32: writer.Write_unsignedInt(o); break; case TypeCode.UInt64: writer.Write_unsignedLong(o); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { writer.Write_QName(o); } else if (_primitiveType == typeof(byte[])) { writer.Write_base64Binary(o); } else if (_primitiveType == typeof(Guid)) { writer.Write_guid(o); } else if (_primitiveType == typeof(TimeSpan)) { writer.Write_TimeSpan(o); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } } private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); object o; switch (_primitiveType.GetTypeCode()) { case TypeCode.String: o = reader.Read_string(); break; case TypeCode.Int32: o = reader.Read_int(); break; case TypeCode.Boolean: o = reader.Read_boolean(); break; case TypeCode.Int16: o = reader.Read_short(); break; case TypeCode.Int64: o = reader.Read_long(); break; case TypeCode.Single: o = reader.Read_float(); break; case TypeCode.Double: o = reader.Read_double(); break; case TypeCode.Decimal: o = reader.Read_decimal(); break; case TypeCode.DateTime: o = reader.Read_dateTime(); break; case TypeCode.Char: o = reader.Read_char(); break; case TypeCode.Byte: o = reader.Read_unsignedByte(); break; case TypeCode.SByte: o = reader.Read_byte(); break; case TypeCode.UInt16: o = reader.Read_unsignedShort(); break; case TypeCode.UInt32: o = reader.Read_unsignedInt(); break; case TypeCode.UInt64: o = reader.Read_unsignedLong(); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { o = reader.Read_QName(); } else if (_primitiveType == typeof(byte[])) { o = reader.Read_base64Binary(); } else if (_primitiveType == typeof(Guid)) { o = reader.Read_guid(); } else if (_primitiveType == typeof(TimeSpan)) { o = reader.Read_TimeSpan(); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } return o; } private class XmlSerializerMappingKey { public XmlMapping Mapping; public XmlSerializerMappingKey(XmlMapping mapping) { this.Mapping = mapping; } public override bool Equals(object obj) { XmlSerializerMappingKey other = obj as XmlSerializerMappingKey; if (other == null) return false; if (this.Mapping.Key != other.Mapping.Key) return false; if (this.Mapping.ElementName != other.Mapping.ElementName) return false; if (this.Mapping.Namespace != other.Mapping.Namespace) return false; if (this.Mapping.IsSoap != other.Mapping.IsSoap) return false; return true; } public override int GetHashCode() { int hashCode = this.Mapping.IsSoap ? 0 : 1; if (this.Mapping.Key != null) hashCode ^= this.Mapping.Key.GetHashCode(); if (this.Mapping.ElementName != null) hashCode ^= this.Mapping.ElementName.GetHashCode(); if (this.Mapping.Namespace != null) hashCode ^= this.Mapping.Namespace.GetHashCode(); return hashCode; } } } }
/* Azure Media Services REST API v2 Function This function submits a job to process a live stream with media analytics. The first task is a subclipping task that createq a MP4 file, then media analytics are processed on this asset. Input: { "channelName": "channel1", // Mandatory "programName" : "program1", // Mandatory "intervalSec" : 60 // Optional. Default is 60 seconds. The duration of subclip (and interval between two calls) "mesSubclip" : // Optional as subclip will always be done but it is required to specify an output storage { "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "mesThumbnails" : // Optional but required to generate thumbnails with Media Encoder Standard (MES) { "start" : "{Best}", // Optional. Start time/mode. Default is "{Best}" "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "indexV1" : // Optional but required to index audio with Media Indexer v1 { "language" : "English", // Optional. Default is "English" "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "indexV2" : // Optional but required to index audio with Media Indexer v2 { "language" : "EnUs", // Optional. Default is EnUs "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "ocr" : // Optional but required to do OCR { "language" : "AutoDetect", // Optional (Autodetect is the default) "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "faceDetection" : // Optional but required to do Face Detection { "mode" : "PerFaceEmotion", // Optional (PerFaceEmotion is the default) "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "faceRedaction" : // Optional but required to do Face Redaction { "mode" : "analyze" // Optional (analyze is the default) "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "motionDetection" : // Optional but required to do Motion Detection { "level" : "medium", // Optional (medium is the default) "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "summarization" : // Optional but required to do Motion Detection { "duration" : "0.0", // Optional (0.0 is the default) "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "videoAnnotation" : // Optional but required to do Video Annotator { "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, "contentModeration" : // Optional but required to do Content Moderator { "outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account) }, // General job properties "priority" : 10, // Optional, priority of the job // For compatibility only with old workflows. Do not use anymore! "indexV1Language" : "English", // Optional "indexV2Language" : "EnUs", // Optional "ocrLanguage" : "AutoDetect" or "English", // Optional "faceDetectionMode" : "PerFaceEmotion, // Optional "faceRedactionMode" : "analyze", // Optional, but required for face redaction "motionDetectionLevel" : "medium", // Optional "summarizationDuration" : "0.0", // Optional. 0.0 for automatic "mesThumbnailsStart" : "{Best}", // Optional. Add a task to generate thumbnails } Output: { "triggerStart" : "" // date and time when the function was called "jobId" : // job id "subclip" : { assetId : "", taskId : "", start : "", duration : "" }, "indexV1" : { assetId : "", taskId : "", language : "" }, "indexV2" : { assetId : "", taskId : "", language : "" }, "ocr" : { assetId : "", taskId : "" }, "faceDetection" : { assetId : "" taskId : "" }, "faceRedaction" : { assetId : "" taskId : "" }, "motionDetection" : { assetId : "", taskId : "" }, "summarization" : { assetId : "", taskId : "" }, "mesThumbnails" : { assetId : "", taskId : "" }, "videoAnnotation" : { assetId : "", taskId : "" }, "contentModeration" : { assetId : "", taskId : "" }, "programId" = programid, "channelName" : "", "programName" : "", "programUrl":"", "programState" : "Running", "programStateChanged" : "True", // if state changed since last call "otherJobsQueue" = 3 // number of jobs in the queue } */ using System; using System.Net; using System.Net.Http; using Newtonsoft.Json; using Microsoft.WindowsAzure.MediaServices.Client; using System.Linq; using System.Threading.Tasks; using System.IO; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; namespace media_functions_for_logic_app { public static class live_subclip_analytics { // Field for service context. private static CloudMediaContext _context = null; [FunctionName("live-subclip-analytics")] public static async Task<object> Run([HttpTrigger(WebHookType = "genericJson")]HttpRequestMessage req, TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext execContext) { // Variables int taskindex = 0; int OutputMES = -1; int OutputPremium = -1; int OutputIndex1 = -1; int OutputIndex2 = -1; int OutputOCR = -1; int OutputFaceDetection = -1; int OutputFaceRedaction = -1; int OutputMotion = -1; int OutputSummarization = -1; int OutputMesThumbnails = -1; int OutputVideoAnnotation = -1; int OutputContentModeration = -1; int id = 0; string programid = ""; string programName = ""; string channelName = ""; string programUrl = ""; string programState = ""; string lastProgramState = ""; IJob job = null; ITask taskEncoding = null; int NumberJobsQueue = 0; int intervalsec = 60; // Interval for each subclip job (sec). Default is 60 TimeSpan starttime = TimeSpan.FromSeconds(0); TimeSpan duration = TimeSpan.FromSeconds(intervalsec); log.Info($"Webhook was triggered!"); string triggerStart = DateTime.UtcNow.ToString("o"); string jsonContent = await req.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(jsonContent); log.Info(jsonContent); if (data.channelName == null || data.programName == null) { return req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass channel name and program name in the input object (channelName, programName)" }); } if (data.intervalSec != null) { intervalsec = (int)data.intervalSec; } MediaServicesCredentials amsCredentials = new MediaServicesCredentials(); log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}"); try { AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain, new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret), AzureEnvironments.AzureCloudEnvironment); AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials); _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider); // find the Channel, Program and Asset channelName = (string)data.channelName; var channel = _context.Channels.Where(c => c.Name == channelName).FirstOrDefault(); if (channel == null) { log.Info("Channel not found"); return req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Channel not found" }); } programName = (string)data.programName; var program = channel.Programs.Where(p => p.Name == programName).FirstOrDefault(); if (program == null) { log.Info("Program not found"); return req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Program not found" }); } programState = program.State.ToString(); programid = program.Id; var asset = ManifestHelpers.GetAssetFromProgram(_context, programid); if (asset == null) { log.Info($"Asset not found for program {programid}"); return req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" }); } log.Info($"Using asset Id : {asset.Id}"); // Table storage to store and real the last timestamp processed // Retrieve the storage account from the connection string. CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(amsCredentials.StorageAccountName, amsCredentials.StorageAccountKey), true); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Retrieve a reference to the table. CloudTable table = tableClient.GetTableReference("liveanalytics"); // Create the table if it doesn't exist. if (!table.CreateIfNotExists()) { log.Info($"Table {table.Name} already exists"); } else { log.Info($"Table {table.Name} created"); } var lastendtimeInTable = ManifestHelpers.RetrieveLastEndTime(table, programid); // Get the manifest data (timestamps) var assetmanifestdata = ManifestHelpers.GetManifestTimingData(_context, asset, log); if (assetmanifestdata.Error) { return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = "Data cannot be read from program manifest." }); } log.Info("Timestamps: " + string.Join(",", assetmanifestdata.TimestampList.Select(n => n.ToString()).ToArray())); var livetime = TimeSpan.FromSeconds((double)assetmanifestdata.TimestampEndLastChunk / (double)assetmanifestdata.TimeScale); log.Info($"Livetime: {livetime}"); starttime = ManifestHelpers.ReturnTimeSpanOnGOP(assetmanifestdata, livetime.Subtract(TimeSpan.FromSeconds(intervalsec))); log.Info($"Value starttime : {starttime}"); if (lastendtimeInTable != null) { lastProgramState = lastendtimeInTable.ProgramState; log.Info($"Value ProgramState retrieved : {lastProgramState}"); var lastendtimeInTableValue = TimeSpan.Parse(lastendtimeInTable.LastEndTime); log.Info($"Value lastendtimeInTable retrieved : {lastendtimeInTableValue}"); id = int.Parse(lastendtimeInTable.Id); log.Info($"Value id retrieved : {id}"); if (lastendtimeInTableValue != null) { var delta = (livetime - lastendtimeInTableValue - TimeSpan.FromSeconds(intervalsec)).Duration(); log.Info($"Delta: {delta}"); //if (delta < (new TimeSpan(0, 0, 3*intervalsec))) // less than 3 times the normal duration (3*60s) if (delta < (TimeSpan.FromSeconds(3 * intervalsec))) // less than 3 times the normal duration (3*60s) { starttime = lastendtimeInTableValue; log.Info($"Value new starttime : {starttime}"); } } } duration = livetime - starttime; log.Info($"Value duration: {duration}"); if (duration == new TimeSpan(0)) // Duration is zero, this may happen sometimes ! { return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = "Stopping. Duration of subclip is zero." }); } // D:\home\site\wwwroot\Presets\LiveSubclip.json string ConfigurationSubclip = File.ReadAllText(Path.Combine(System.IO.Directory.GetParent(execContext.FunctionDirectory).FullName, "presets", "LiveSubclip.json")).Replace("0:00:00.000000", starttime.Subtract(TimeSpan.FromMilliseconds(100)).ToString()).Replace("0:00:30.000000", duration.Add(TimeSpan.FromMilliseconds(200)).ToString()); int priority = 10; if (data.priority != null) { priority = (int)data.priority; } // MES Subclipping TASK // Declare a new encoding job with the Standard encoder job = _context.Jobs.Create("Azure Function - Job for Live Analytics - " + programName, priority); // Get a media processor reference, and pass to it the name of the // processor to use for the specific task. IMediaProcessor processor = MediaServicesHelper.GetLatestMediaProcessorByName(_context, "Media Encoder Standard"); // Change or modify the custom preset JSON used here. // string preset = File.ReadAllText("D:\home\site\wwwroot\Presets\H264 Multiple Bitrate 720p.json"); // Create a task with the encoding details, using a string preset. // In this case "H264 Multiple Bitrate 720p" system defined preset is used. taskEncoding = job.Tasks.AddNew("Subclipping task", processor, ConfigurationSubclip, TaskOptions.None); // Specify the input asset to be encoded. taskEncoding.InputAssets.Add(asset); OutputMES = taskindex++; // Add an output asset to contain the results of the job. // This output is specified as AssetCreationOptions.None, which // means the output asset is not encrypted. var subclipasset = taskEncoding.OutputAssets.AddNew(asset.Name + " subclipped " + triggerStart, JobHelpers.OutputStorageFromParam(data.mesSubclip), AssetCreationOptions.None); log.Info($"Adding media analytics tasks"); //new OutputIndex1 = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.indexV1 == null) ? (string)data.indexV1Language : ((string)data.indexV1.language ?? "English"), "Azure Media Indexer", "IndexerV1.xml", "English", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.indexV1)); OutputIndex2 = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.indexV2 == null) ? (string)data.indexV2Language : ((string)data.indexV2.language ?? "EnUs"), "Azure Media Indexer 2 Preview", "IndexerV2.json", "EnUs", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.indexV2)); OutputOCR = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.ocr == null) ? (string)data.ocrLanguage : ((string)data.ocr.language ?? "AutoDetect"), "Azure Media OCR", "OCR.json", "AutoDetect", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.ocr)); OutputFaceDetection = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.faceDetection == null) ? (string)data.faceDetectionMode : ((string)data.faceDetection.mode ?? "PerFaceEmotion"), "Azure Media Face Detector", "FaceDetection.json", "PerFaceEmotion", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.faceDetection)); OutputFaceRedaction = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.faceRedaction == null) ? (string)data.faceRedactionMode : ((string)data.faceRedaction.mode ?? "comined"), "Azure Media Redactor", "FaceRedaction.json", "combined", ref taskindex, priority - 1, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.faceRedaction)); OutputMotion = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.motionDetection == null) ? (string)data.motionDetectionLevel : ((string)data.motionDetection.level ?? "medium"), "Azure Media Motion Detector", "MotionDetection.json", "medium", ref taskindex, priority - 1, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.motionDetection)); OutputSummarization = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.summarization == null) ? (string)data.summarizationDuration : ((string)data.summarization.duration ?? "0.0"), "Azure Media Video Thumbnails", "Summarization.json", "0.0", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.summarization)); OutputVideoAnnotation = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.videoAnnotation != null) ? "1.0" : null, "Azure Media Video Annotator", "VideoAnnotation.json", "1.0", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.videoAnnotation)); OutputContentModeration = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.contentModeration != null) ? "2.0" : null, "Azure Media Content Moderator", "ContentModeration.json", "2.0", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.contentModeration)); // MES Thumbnails OutputMesThumbnails = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.mesThumbnails != null) ? ((string)data.mesThumbnails.Start ?? "{Best}") : null, "Media Encoder Standard", "MesThumbnails.json", "{Best}", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.mesThumbnails)); job.Submit(); log.Info("Job Submitted"); id++; ManifestHelpers.UpdateLastEndTime(table, starttime + duration, programid, id, program.State); log.Info($"Output MES index {OutputMES}"); // Let store some data in altid of subclipped asset var sid = JobHelpers.ReturnId(job, OutputMES); log.Info($"SID {sid}"); var subclipassetrefreshed = _context.Assets.Where(a => a.Id == sid).FirstOrDefault(); log.Info($"subclipassetrefreshed ID {subclipassetrefreshed.Id}"); subclipassetrefreshed.AlternateId = JsonConvert.SerializeObject(new ManifestHelpers.SubclipInfo() { programId = programid, subclipStart = starttime, subclipDuration = duration }); subclipassetrefreshed.Update(); // Let store some data in altid of index assets var index1sid = JobHelpers.ReturnId(job, OutputIndex1); if (index1sid != null) { var index1assetrefreshed = _context.Assets.Where(a => a.Id == index1sid).FirstOrDefault(); log.Info($"index1assetrefreshed ID {index1assetrefreshed.Id}"); index1assetrefreshed.AlternateId = JsonConvert.SerializeObject(new ManifestHelpers.SubclipInfo() { programId = programid, subclipStart = starttime, subclipDuration = duration }); index1assetrefreshed.Update(); } var index2sid = JobHelpers.ReturnId(job, OutputIndex2); if (index2sid != null) { var index2assetrefreshed = _context.Assets.Where(a => a.Id == index2sid).FirstOrDefault(); log.Info($"index2assetrefreshed ID {index2assetrefreshed.Id}"); index2assetrefreshed.AlternateId = JsonConvert.SerializeObject(new ManifestHelpers.SubclipInfo() { programId = programid, subclipStart = starttime, subclipDuration = duration }); index2assetrefreshed.Update(); } // Get program URL var publishurlsmooth = MediaServicesHelper.GetValidOnDemandURI(_context, asset); if (publishurlsmooth != null) { programUrl = publishurlsmooth.ToString(); } NumberJobsQueue = _context.Jobs.Where(j => j.State == JobState.Queued).Count(); } catch (Exception ex) { string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : ""); log.Info($"ERROR: Exception {message}"); return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message }); } log.Info("Job Id: " + job.Id); log.Info("Output asset Id: " + ((OutputMES > -1) ? JobHelpers.ReturnId(job, OutputMES) : JobHelpers.ReturnId(job, OutputPremium))); return req.CreateResponse(HttpStatusCode.OK, new { triggerStart = triggerStart, jobId = job.Id, subclip = new { assetId = JobHelpers.ReturnId(job, OutputMES), taskId = JobHelpers.ReturnTaskId(job, OutputMES), start = starttime, duration = duration, }, mesThumbnails = new { assetId = JobHelpers.ReturnId(job, OutputMesThumbnails), taskId = JobHelpers.ReturnTaskId(job, OutputMesThumbnails) }, indexV1 = new { assetId = JobHelpers.ReturnId(job, OutputIndex1), taskId = JobHelpers.ReturnTaskId(job, OutputIndex1), language = (string)data.indexV1Language }, indexV2 = new { assetId = JobHelpers.ReturnId(job, OutputIndex2), taskId = JobHelpers.ReturnTaskId(job, OutputIndex2), language = (string)data.indexV2Language, }, ocr = new { assetId = JobHelpers.ReturnId(job, OutputOCR), taskId = JobHelpers.ReturnTaskId(job, OutputOCR) }, faceDetection = new { assetId = JobHelpers.ReturnId(job, OutputFaceDetection), taskId = JobHelpers.ReturnTaskId(job, OutputFaceDetection) }, faceRedaction = new { assetId = JobHelpers.ReturnId(job, OutputFaceRedaction), taskId = JobHelpers.ReturnTaskId(job, OutputFaceRedaction) }, motionDetection = new { assetId = JobHelpers.ReturnId(job, OutputMotion), taskId = JobHelpers.ReturnTaskId(job, OutputMotion) }, summarization = new { assetId = JobHelpers.ReturnId(job, OutputSummarization), taskId = JobHelpers.ReturnTaskId(job, OutputSummarization) }, videoAnnotation = new { assetId = JobHelpers.ReturnId(job, OutputVideoAnnotation), taskId = JobHelpers.ReturnTaskId(job, OutputVideoAnnotation) }, contentModeration = new { assetId = JobHelpers.ReturnId(job, OutputContentModeration), taskId = JobHelpers.ReturnTaskId(job, OutputContentModeration) }, channelName = channelName, programName = programName, programId = programid, programUrl = programUrl, programState = programState, programStateChanged = (lastProgramState != programState).ToString(), otherJobsQueue = NumberJobsQueue }); } } }
using System; using System.ComponentModel; using System.Drawing.Design; using System.IO; using System.Xml.Serialization; using CslaGenerator.Attributes; using CslaGenerator.Design; using CslaGenerator.Util; namespace CslaGenerator.Metadata { public class PropertyNameChangedEventArgs : EventArgs { public string OldName; public string NewName; public PropertyNameChangedEventArgs(string oldName, string newName) { OldName = oldName; NewName = newName; } } public delegate void PropertyNameChanged(ValueProperty sender, PropertyNameChangedEventArgs e); /// <summary> /// Summary description for ValueProperty. /// </summary> [Serializable] public class ValueProperty : Property, IBoundProperty, IHaveBusinessRules { [TypeConverter(typeof(EnumDescriptionOrCaseConverter))] public enum DataAccessBehaviour { ReadWrite, ReadOnly, WriteOnly, UpdateOnly, CreateOnly } [TypeConverter(typeof(EnumDescriptionOrCaseConverter))] public enum UserDefinedKeyBehaviour { Default, UserProvidedPK, DBProvidedPK } internal static AuthorizationActions Convert(string actionProperty) { AuthorizationActions result; switch (actionProperty) { case "Read Authorization Type": result = AuthorizationActions.ReadProperty; break; case "Write Authorization Type": result = AuthorizationActions.WriteProperty; break; case "Create Authorization Type": result = AuthorizationActions.CreateObject; break; case "Get Authorization Type": result = AuthorizationActions.GetObject; break; case "Update Authorization Type": result = AuthorizationActions.EditObject; break; //case "Delete Authorization Type": default: result = AuthorizationActions.DeleteObject; break; } return result; } #region Private Fields private DbBindColumn _dbBindColumn = new DbBindColumn(); private string _fkConstraint = string.Empty; private bool _undoable = true; private string _defaultValue = string.Empty; private string _friendlyName = string.Empty; private bool _isDatabaseBound = true; private string _customPropertyType = string.Empty; private PropertyDeclaration _declarationMode; private BusinessRuleCollection _businessRules; private string _interfaces = string.Empty; private string[] _attributes = new string[] {}; private AuthorizationProvider _authzProvider; private AuthorizationRuleCollection _authzRules; private string _readRoles = string.Empty; private string _writeRoles = string.Empty; private PropertyAccess _access = PropertyAccess.IsPublic; private DataAccessBehaviour _dataAccess = DataAccessBehaviour.ReadWrite; private UserDefinedKeyBehaviour _primaryKey = UserDefinedKeyBehaviour.Default; private AccessorVisibility _propSetAccessibility = AccessorVisibility.Default; private TypeCodeEx _backingFieldType = TypeCodeEx.Empty; private bool _nullable; #endregion #region Constructor public ValueProperty() { var selectedItem = GeneratorController.Current.GetSelectedItem(); if (selectedItem != null) { if (((CslaObjectInfo) selectedItem).IsReadOnlyObject()) { ReadOnly = true; } } _businessRules = new BusinessRuleCollection(); NameChanged += _businessRules.OnParentChanged; _authzRules = new AuthorizationRuleCollection(); _authzRules.Add(new AuthorizationRule()); _authzRules.Add(new AuthorizationRule()); NameChanged += _authzRules.OnParentChanged; } #endregion #region UI Properties #region 00. Database [Category("00. Database")] [Editor(typeof(DbBindColumnEditor), typeof(UITypeEditor))] [TypeConverter(typeof(DbBindColumnConverter))] [Description("The database column this property is bound to.")] [UserFriendlyName("DB Bind Column")] public virtual DbBindColumn DbBindColumn { get { return _dbBindColumn; } set { _dbBindColumn = value; ResetProperties(value); } } [Category("00. Database")] [Description("When \"PrimaryKey\" is set to \"Default\", this controls the data flow of the property. Using the legend \"C=Create\", \"R=Read\", \"U=Update\" and \"x=no op\", the rules are as follows:" + "\r\n\tReadWrite=CRU (full access)" + "\r\n\tReadOnly=xRx (can't write)" + "\r\n\tWriteOnly=CxU (can't read)" + "\r\n\tUpdateOnly=xRU (can't create)" + "\r\n\tCreateOnly=CRx (can't update)")] [UserFriendlyName("Data Access Behaviour")] public virtual DataAccessBehaviour DataAccess { get { return _dataAccess; } set { _dataAccess = value; } } [Category("00. Database")] [Description("The type of primary key or \"Default\" to none.")] [UserFriendlyName("Primary Key")] public virtual UserDefinedKeyBehaviour PrimaryKey { get { return _primaryKey; } set { _primaryKey = value; } } [Category("00. Database")] [Description("Explicitly add the foreign key constraint for this column (shows on INNER JOIN declarations).")] [Editor(typeof(FKConstraintEditor), typeof(UITypeEditor))] [UserFriendlyName("FK Constraint")] public virtual string FKConstraint { get { return _fkConstraint; } set { _fkConstraint = value; } } [Category("00. Database")] [Description("The stored procedure parameter name.")] [UserFriendlyName("Parameter Name")] public override string ParameterName { get { if (_parameterName.Equals(String.Empty)) { if (!string.IsNullOrEmpty(DbBindColumn.ColumnName)) return DbBindColumn.ColumnName; return Name; } return _parameterName; } set { _parameterName = value; } } #endregion #region 01. Definition [Category("01. Definition")] [Description("The property name.")] public override string Name { get { var name = base.Name; if (string.IsNullOrEmpty(name)) return "Unnamed Property"; return name; } set { value = PropertyHelper.Tidy(value); var e = new PropertyNameChangedEventArgs(base.Name, value); base.Name = value; if (NameChanged != null) NameChanged(this, e); } } [Category("01. Definition")] [Description("Human readable friendly display name of the property.")] [UserFriendlyName("Property Friendly Name")] public string FriendlyName { get { if (string.IsNullOrEmpty(_friendlyName)) return PropertyHelper.SplitOnCaps(base.Name); return _friendlyName; } set { if (value != null && !value.Equals(PropertyHelper.SplitOnCaps(base.Name))) _friendlyName = value; else _friendlyName = string.Empty; } } [Category("01. Definition")] [Description("If set to false, disables database interaction. Set to read only when database interaction is impossible.")] [UserFriendlyName("Database Bound")] public virtual bool IsDatabaseBound { get { if (base.PropertyType == TypeCodeEx.CustomType) { if (_declarationMode != PropertyDeclaration.ClassicPropertyWithTypeConversion && _declarationMode != PropertyDeclaration.ManagedWithTypeConversion && _declarationMode != PropertyDeclaration.UnmanagedWithTypeConversion) _isDatabaseBound = false; if (_backingFieldType == TypeCodeEx.Empty || _backingFieldType == TypeCodeEx.CustomType) _isDatabaseBound = false; } return _isDatabaseBound; } set { _isDatabaseBound = value; } } [Category("01. Definition")] [Description("The property data Type.")] [UserFriendlyName("Property Type")] public override TypeCodeEx PropertyType { get { return base.PropertyType; } set { base.PropertyType = value; } } [Category("01. Definition")] [Description("Use a standard Type or a Type that is neither native nor defined on CSLA.NET.")] [UserFriendlyName("Custom Property Type")] public virtual string CustomPropertyType { get { return _customPropertyType; } set { _customPropertyType = value; } } [Category("01. Definition")] [Description("Property Declaration Mode.")] [UserFriendlyName("Declaration Mode")] public virtual PropertyDeclaration DeclarationMode { get { return _declarationMode; } set { _declarationMode = value; } } [Category("01. Definition")] [Description("Type of Backing Field of the Property. Set to \"Empty\" for no backing field. " + "Is set to read only when Declaration Mode isn't using type conversion. " + "For custom type properties, only numeric and string are accepted.")] [UserFriendlyName("Backing Field Type")] public virtual TypeCodeEx BackingFieldType { get { if (_declarationMode == PropertyDeclaration.ClassicPropertyWithTypeConversion || _declarationMode == PropertyDeclaration.ManagedWithTypeConversion || _declarationMode == PropertyDeclaration.UnmanagedWithTypeConversion) return _backingFieldType; return TypeCodeEx.Empty; } set { if (base.PropertyType == TypeCodeEx.CustomType && (!value.IsNumeric() && value != TypeCodeEx.String)) return; _backingFieldType = value; } } [Category("01. Definition")] [Description("Whether this property can be changed by other classes.")] public override bool ReadOnly { get { return base.ReadOnly; } set { base.ReadOnly = value; } } [Category("01. Definition")] [Description("Whether this property can have a null value. The following types can't be null: \"ByteArray \", \"DBNull \", \"Object\" and \"Empty\".")] public override bool Nullable { get { if (BackingFieldType == TypeCodeEx.Empty && base.PropertyType.IsNullAllowedOnType()) return _nullable; if (_backingFieldType.IsNullAllowedOnType()) return _nullable; return false; } set { _nullable = value; } } [Category("01. Definition")] [Description("Value that is set when the object is created.")] [UserFriendlyName("Default Value")] public virtual string DefaultValue { get { return _defaultValue; } set { _defaultValue = PropertyHelper.TidyAllowSpaces(value); } } #endregion #region 02. Advanced [Category("02. Advanced")] [Description("The attributes you want to add to this property.")] public virtual string[] Attributes { get { return _attributes; } set { _attributes = PropertyHelper.TidyAllowSpaces(value); } } [Category("02. Advanced")] [Description("The interface this property explicitly implements.")] public virtual string Interfaces { get { return _interfaces; } set { value = PropertyHelper.Tidy(value); if (!string.IsNullOrEmpty(value)) { var namePostfix = '.' + Name; if (value.LastIndexOf(namePostfix) != value.Length - namePostfix.Length) { if (GeneratorController.Current.CurrentUnit != null) { if (GeneratorController.Current.CurrentUnit.GenerationParams.OutputLanguage == CodeLanguage.CSharp || _interfaces == string.Empty) value = value + namePostfix; } } } _interfaces = value; } } #endregion #region 03. Business Rules & Authorization [Category("03. Business Rules & Authorization")] [Description("Collection of business rules (transformation, validation, etc).")] [Editor(typeof(PropertyCollectionForm), typeof(UITypeEditor))] [UserFriendlyName("Business Rules Collection")] public virtual BusinessRuleCollection BusinessRules { get { return _businessRules; } } [Category("03. Business Rules & Authorization")] [Description("The Authorization Provider for this property.")] [UserFriendlyName("Authorization Provider")] public virtual AuthorizationProvider AuthzProvider { get { return _authzProvider; } set { _authzProvider = value; } } [Category("03. Business Rules & Authorization")] [Description("Roles allowed to read the property. Use a comma to separate multiple roles.")] [UserFriendlyName("Read Roles")] public virtual string ReadRoles { get { return _readRoles; } set { _readRoles = PropertyHelper.TidyAllowSpaces(value).Replace(';', ',').Trim(new[] {','}); } } [Category("03. Business Rules & Authorization")] [Description("Roles allowed to write to the property. Use a comma to separate multiple roles.")] [UserFriendlyName("Write Roles")] public virtual string WriteRoles { get { return _writeRoles; } set { _writeRoles = PropertyHelper.TidyAllowSpaces(value).Replace(';', ',').Trim(new[] {','}); } } [Category("03. Business Rules & Authorization")] [Description("The Authorization Type that controls read action. You can either select an object defined in the current project or an object defined in another assembly.")] [Editor(typeof(ObjectEditor), typeof(UITypeEditor))] [TypeConverter(typeof(AuthorizationRuleTypeConverter))] [UserFriendlyName("Read Authorization Type")] public virtual AuthorizationRule ReadAuthzRuleType { get { return _authzRules[0]; } set { if (!ReferenceEquals(value, _authzRules[0])) { if (_authzRules[0] != null) { _authzRules[0] = value; _authzRules[0].Parent = Name; } } } } [Category("03. Business Rules & Authorization")] [Description("The Authorization Type that controls write action. You can either select an object defined in the current project or an object defined in another assembly.")] [Editor(typeof(ObjectEditor), typeof(UITypeEditor))] [TypeConverter(typeof(AuthorizationRuleTypeConverter))] [UserFriendlyName("Write Authorization Type")] public virtual AuthorizationRule WriteAuthzRuleType { get { return _authzRules[1]; } set { if (!ReferenceEquals(value, _authzRules[1])) { if (_authzRules[1] != null) { _authzRules[1] = value; _authzRules[1].Parent = Name; } } } } #endregion #region 05. Options [Category("05. Options")] [Description("Accessibility for the property as a whole.\r\nDefaults to IsPublic.")] [UserFriendlyName("Property Accessibility")] public PropertyAccess Access { get { return _access; } set { _access = value; } } [Category("05. Options")] [Description("Accessibility for property setter.\r\n" + "If \"ReadOnly\" is true, this settings is ignored.\r\n - Auto properties have a private setter\r\n - Classic, managed and unmanaged properties have no setter.\r\n" + "If \"ReadOnly\" is false, this setting applies. By default the setter has the same accessibility of the property.")] [UserFriendlyName("Setter Accessibility")] public virtual AccessorVisibility PropSetAccessibility { get { return _propSetAccessibility; } set { _propSetAccessibility = value; } } [Category("05. Options")] [Description("Setting to false will cause the n-level undo process to ignore that property's value.")] public virtual bool Undoable { get { return _undoable; } set { _undoable = value; } } #endregion #endregion [field: NonSerialized] public event PropertyNameChanged NameChanged; public override object Clone() { using (var buffer = new MemoryStream()) { var ser = new XmlSerializer(typeof(ValueProperty)); ser.Serialize(buffer, this); buffer.Position = 0; return ser.Deserialize(buffer); } } internal void RetrieveSummaryFromColumnDefinition() { if (DbBindColumn.Column != null) { var prop = DbBindColumn.Column.ColumnDescription; if (!string.IsNullOrWhiteSpace(prop)) Summary = prop; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using revashare_svc_webapi.Client.Areas.HelpPage.ModelDescriptions; using revashare_svc_webapi.Client.Areas.HelpPage.Models; namespace revashare_svc_webapi.Client.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace John.Doyle.Mediocore.Developer.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using UnityEngine; using System.Text; using System.Collections.Generic; namespace Uzu { /// <summary> /// A class for pooling of Unity GameObjects. /// Allows reuse of GameObjects, while avoiding the expensive overhead of /// repeated Instantiate/Destroy calls. /// </summary> public class GameObjectPool : BaseBehaviour { /// <summary> /// Can we spawn any objects w/o having to re-allocate? /// </summary> public bool HasAvailableObject { get { return AvailableObjectCount != 0; } } /// <summary> /// The total # of objects that are available to use w/o having to re-allocate. /// </summary> public int AvailableObjectCount { get { return _availableObjects.Count; } } /// <summary> /// The total # of objects that are currently being utilized. /// </summary> public int ActiveObjectCount { get { return _allObjects.Count - _availableObjects.Count; } } /// <summary> /// The total # of objects that this pool can currently accomodate without growing. /// </summary> public int Capacity { get { return _allObjects.Count; } } /// <summary> /// Is the pool allowed to grow if it needs to spawn new objects? /// </summary> public bool DoesGrow { get { return _doesGrow; } } public List<GameObject> ActiveObjects { get { List<GameObject> activeObjects = new List<GameObject> (ActiveObjectCount); for (int i = 0; i < _allObjects.Count; i++) { PooledBehaviour obj = _allObjects [i]; if (!_availableObjects.Contains (obj)) { activeObjects.Add (obj.gameObject); } } return activeObjects; } } /// <summary> /// Spawn a new GameObject with the given position. /// Re-uses an object in the pool if available. /// </summary> public GameObject Spawn (Vector3 position) { return Spawn (position, _prefabTransform.localRotation); } /// <summary> /// Spawn a new GameObject with the given position/rotation. /// Re-uses an object in the pool if available. /// </summary> public GameObject Spawn (Vector3 position, Quaternion rotation) { GameObject resultGO; PooledBehaviour resultComponent; if (_availableObjects.Count == 0) { // Should we automatically grow? if (!_doesGrow) { Debug.LogWarning ("Pool capacity [" + _initialCount + "] reached."); return null; } resultGO = CreateObject (position, rotation); resultComponent = resultGO.GetComponent<PooledBehaviour> (); } else { resultComponent = _availableObjects.Pop (); resultGO = resultComponent.gameObject; Transform resultTransform = resultComponent.CachedXform; resultTransform.localPosition = position; resultTransform.localRotation = rotation; } // Activate. resultGO.SetActive (true); resultComponent.OnSpawn (); return resultGO; } /// <summary> /// Unspawns a given GameObject and adds it back to the available /// resource pool. /// </summary> public void Unspawn (GameObject targetGO) { PooledBehaviour targetComponent = targetGO.GetComponent<PooledBehaviour> (); #if UNITY_EDITOR if (targetComponent == null) { Debug.LogError("Attempting to Unspawn an object not belonging to this pool!"); return; } #endif // UNITY_EDITOR // If the object has been manually assigned to this pool, // add it to our master list. if (!_allObjects.Contains(targetComponent)) { _allObjects.Add (targetComponent); } // Reset parent in case the object was moved by the user. targetComponent.CachedXform.parent = _poolParentTransform; if (!_availableObjects.Contains (targetComponent)) { targetComponent.OnUnspawn (); targetGO.SetActive (false); _availableObjects.Push (targetComponent); } } /// <summary> /// Unspawns all GameObjects and adds them all back to the available /// resource pool. /// </summary> public void UnspawnAll () { for (int i = 0; i < _allObjects.Count; i++) { Unspawn (_allObjects [i].gameObject); } } /// <summary> /// Destroys all GameObjects in the pool. /// </summary> public void DestroyAll () { for (int i = 0; i < _allObjects.Count; i++) { GameObject.Destroy (_allObjects [i].gameObject); } _availableObjects.Clear (); _allObjects.Clear (); } #region Implementation. [SerializeField] private int _initialCount; [SerializeField] private GameObject _prefab; [SerializeField] private bool _doesGrow = true; private Transform _poolParentTransform; private Transform _prefabTransform; private Stack<PooledBehaviour> _availableObjects; private List<PooledBehaviour> _allObjects; private GameObject CreateObject (Vector3 position, Quaternion rotation) { GameObject resultGO = GameObject.Instantiate (_prefab, position, rotation) as GameObject; PooledBehaviour resultComponent = resultGO.GetComponent<PooledBehaviour> (); if (resultComponent == null) { Debug.LogError ("Pooled object must contain a Uzu.PooledBehaviour component."); GameObject.Destroy (resultGO); return null; } Transform resultTransform = resultComponent.CachedXform; resultTransform.parent = _poolParentTransform; resultTransform.localPosition = position; resultTransform.localRotation = rotation; resultTransform.localScale = _prefabTransform.localScale; _allObjects.Add (resultComponent); resultComponent.AddToPool (this); return resultGO; } protected override void Awake () { base.Awake (); // Create a parent for grouping all objects together. { StringBuilder stringBuilder = new StringBuilder ("UzuPool - "); stringBuilder.Append (_prefab.name); GameObject poolParent = new GameObject (stringBuilder.ToString ()); _poolParentTransform = poolParent.transform; _poolParentTransform.parent = CachedXform; _poolParentTransform.localPosition = Vector3.zero; _poolParentTransform.localScale = Vector3.one; _poolParentTransform.localRotation = Quaternion.identity; } _prefabTransform = _prefab.transform; _availableObjects = new Stack<PooledBehaviour> (_initialCount); _allObjects = new List<PooledBehaviour> (_initialCount); // Pre-allocate our pool. { // Allocate objects. for (int i = 0; i < _initialCount; ++i) { CreateObject (Vector3.zero, Quaternion.identity); } // Add to pool. for (int i = 0; i < _allObjects.Count; i++) { GameObject targetGO = _allObjects [i].gameObject; targetGO.SetActive (false); PooledBehaviour targetComponent = targetGO.GetComponent<PooledBehaviour> (); _availableObjects.Push (targetComponent); } } } #endregion } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using NUnit.Util; namespace NUnit.UiKit { /// <summary> /// Summary description for OptionsDialogBase. /// </summary> public class SettingsDialogBase : System.Windows.Forms.Form { #region Instance Fields protected System.Windows.Forms.Button cancelButton; protected System.Windows.Forms.Button okButton; private SettingsPageCollection pageList; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private bool reloadProjectOnClose; #endregion #region Construction and Disposal public SettingsDialogBase() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // pageList = new SettingsPageCollection( ); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.CausesValidation = false; this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(256, 424); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(72, 24); this.cancelButton.TabIndex = 18; this.cancelButton.Text = "Cancel"; // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.Location = new System.Drawing.Point(168, 424); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(72, 24); this.okButton.TabIndex = 17; this.okButton.Text = "OK"; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // SettingsDialogBase // this.ClientSize = new System.Drawing.Size(336, 458); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SettingsDialogBase"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Settings"; this.Closed += new System.EventHandler(this.SettingsDialogBase_Closed); this.ResumeLayout(false); } #endregion #region Properties public SettingsPageCollection SettingsPages { get { return pageList; } } #endregion #region Public Methods public void ApplySettings() { foreach( SettingsPage page in pageList ) if ( page.SettingsLoaded ) page.ApplySettings(); } #endregion #region Event Handlers private void SettingsDialogBase_Closed(object sender, System.EventArgs e) { if (this.reloadProjectOnClose) Services.TestLoader.ReloadTest(); } private void okButton_Click(object sender, System.EventArgs e) { if ( Services.TestLoader.IsTestLoaded && this.HasChangesRequiringReload ) { DialogResult answer = UserMessage.Ask( "Some changes will only take effect when you reload the test project. Do you want to reload now?", "NUnit Options", MessageBoxButtons.YesNo ); if ( answer == DialogResult.Yes ) this.reloadProjectOnClose = true; } ApplySettings(); DialogResult = DialogResult.OK; Close(); } #endregion #region Helper Methods private bool HasChangesRequiringReload { get { foreach( SettingsPage page in pageList ) if ( page.SettingsLoaded && page.HasChangesRequiringReload ) return true; return false; } } #endregion #region Nested SettingsPageCollection Class public class SettingsPageCollection : CollectionBase { public void Add( SettingsPage page ) { this.InnerList.Add( page ); } public void AddRange( params SettingsPage[] pages ) { this.InnerList.AddRange( pages ); } public SettingsPage this[int index] { get { return (SettingsPage)InnerList[index]; } } public SettingsPage this[string key] { get { foreach( SettingsPage page in InnerList ) if ( page.Key == key ) return page; return null; } } } #endregion } }
namespace MoreLinq.Test { using System; using System.Collections.Generic; using NUnit.Framework; /// <summary> /// Tests that verify the behavior of the RandomSubset() operator /// </summary> [TestFixture] public class RandomSubsetTest { /// <summary> /// Verify that RandomSubset() behaves in a lazy manner. /// </summary> [Test] public void TestRandomSubsetIsLazy() { new BreakingSequence<int>().RandomSubset(10); new BreakingSequence<int>().RandomSubset(10, new Random()); } /// <summary> /// Verify that involving RandomSubsets with a subset size less than 0 results in an exception. /// </summary> [Test] public void TestRandomSubsetNegativeSubsetSize() { AssertThrowsArgument.OutOfRangeException("subsetSize", () => Enumerable.Range(1, 10).RandomSubset(-5)); } /// <summary> /// Verify that involving RandomSubsets with a subset size less than 0 results in an exception. /// </summary> [Test] public void TestRandomSubsetNegativeSubsetSize2() { AssertThrowsArgument.OutOfRangeException("subsetSize", () => Enumerable.Range(1, 10).RandomSubset(-1, new Random())); } /// <summary> /// Verify that the 0-size random subset of the empty set is the empty set. /// </summary> [Test] public void TestRandomSubsetOfEmptySequence() { var sequence = Enumerable.Empty<int>(); var result = sequence.RandomSubset(0); // we can only get subsets <= sequence.Count() Assert.AreEqual(0, result.Count()); } /// <summary> /// Verify that RandomSubset can produce a random subset of equal length to the original sequence. /// </summary> [Test] public void TestRandomSubsetSameLengthAsSequence() { const int count = 100; var sequence = Enumerable.Range(1, count); var resultA = sequence.RandomSubset(count); var resultB = sequence.RandomSubset(count, new Random(12345)); // ensure random subset is always a complete reordering of original sequence Assert.AreEqual(count, resultA.Distinct().Count()); Assert.AreEqual(count, resultB.Distinct().Count()); } /// <summary> /// Verify that RandomSubset can produce a random subset shorter than the original sequence. /// </summary> [Test] public void TestRandomSubsetShorterThanSequence() { const int count = 100; const int subsetSize = 20; var sequence = Enumerable.Range(1, count); var resultA = sequence.RandomSubset(subsetSize); var resultB = sequence.RandomSubset(subsetSize, new Random(12345)); // ensure random subset is always a distinct subset of original sequence Assert.AreEqual(subsetSize, resultA.Distinct().Count()); Assert.AreEqual(subsetSize, resultB.Distinct().Count()); } /// <summary> /// Verify that attempting to fetch a random subset longer than the original sequence /// results in an exception. Only thrown when the resulting random sequence is enumerated. /// </summary> [Test] public void TestRandomSubsetLongerThanSequence() { const int count = 100; const int subsetSize = count + 5; var sequence = Enumerable.Range(1, count); AssertThrowsArgument.OutOfRangeException("subsetSize", () => { sequence.RandomSubset(subsetSize).Consume(); }); } /// <summary> /// Verify that attempting to fetch a random subset longer than the original sequence /// results in an exception. Only thrown when the resulting random sequence is enumerated. /// </summary> [Test] public void TestRandomSubsetLongerThanSequence2() { const int count = 100; const int subsetSize = count + 5; var sequence = Enumerable.Range(1, count); AssertThrowsArgument.OutOfRangeException("subsetSize", () => { sequence.RandomSubset(subsetSize, new Random(1234)).Consume(); }); } /// <summary> /// Verify that RandomSubset does not exhibit selection bias in the subsets it returns. /// </summary> /// <remarks> /// It's actually a complicated matter to ensure that a random process does not exhibit /// any kind of bias. In this test, we want to make sure that the probability of any /// particular subset being returned is roughly the same as any other. Here's how. /// /// This test selects a random subset of length N from an ascending sequence 1..N. /// It then adds up the values of the random result into an accumulator array. After many /// iterations, we would hope that each index of the accumulator array approach the same /// value. Of course, in the real world, there will be some variance, and the values will /// never be the same. However, we can compute the relative standard deviation (RSD) of the /// variance. As the number of trials increases, the RSD should continue decreasing /// asymptotically towards zero. By running several iterations of increasing trial size, /// we can assert that the RSD continually decreases, approaching zero. /// /// For math geeks who read this: /// A decreasing RSD demonstrates that the random subsets form a cumulative distribution /// approaching unity (1.0). Which, given that the original sequence was monotonic, implies /// there cannot be a selection bias in the returned subsets - quod erat demonstrandum (QED). /// </remarks> [Test] [Explicit] public void TestRandomSubsetIsUnbiased() { const int count = 20; var sequence = Enumerable.Range(1, count); var rsdTrials = new[] { 1000, 10000, 100000, 500000, 10000000 }; var rsdResults = new[] { 0.0, 0.0, 0.0, 0.0, 0.0 }; var trialIndex = 0; foreach (var trialSize in rsdTrials) { var biasAccumulator = Enumerable.Repeat(0.0, count).ToArray(); for (var i = 0; i < trialSize; i++) { var index = 0; var result = sequence.RandomSubset(count); foreach (var itemA in result) biasAccumulator[index++] += itemA; } rsdResults[trialIndex++] = RelativeStandardDeviation(biasAccumulator); } // ensure that wth increasing trial size the a RSD% continually decreases for (var j = 0; j < rsdResults.Length - 1; j++) Assert.Less(rsdResults[j + 1], rsdResults[j]); // ensure that the RSD% for the 5M trial size is < 1.0 (this is somewhat arbitrary) Assert.Less(rsdResults.Last(), 1.0); // for sanity, we output the RSD% values as a cross-check, the expected result should be // that the RSD% rapidly decreases and eventually drops below 1.0 Console.WriteLine("RSD% = {0:0.00000}, {1:0.00000}, {2:0.00000}, {3:0.00000}, {4:0.00000}", rsdResults[0], rsdResults[1], rsdResults[2], rsdResults[3], rsdResults[4]); } /// <summary> /// Verify that RandomSubsets is idempotent with respect to the original sequence. /// </summary> /// <remarks> /// Internally, RandomSubsets perform some in-place operations on a copy of the sequence. /// This attempts to verify that the original sequence remains unaltered after a random /// subset is returned and enumerated. /// </remarks> [Test] public void TestRandomSubsetIsIdempotent() { const int count = 100; const int subsetSize = count; var sequence = Enumerable.Range(1, count).ToArray(); var sequenceClone = sequence.ToArray(); var resultA = sequence.RandomSubset(subsetSize); var resultB = sequence.RandomSubset(subsetSize); // force complete enumeration of random subsets resultA.Consume(); resultB.Consume(); // verify the original sequence is untouched Assert.That(sequence, Is.EqualTo(sequenceClone)); } /// <summary> /// Verify that RandomSubset produces subset where all elements belongs to original sequence. /// </summary> [Test] public void TestRandomSubsetReturnsOriginalSequenceElements() { const int count = 100; var sequence = Enumerable.Range(1, count); var result = sequence.RandomSubset(count, new Random(12345)); // we do not test overload without seed because it can return original sequence Assert.That(sequence, Is.Not.EqualTo(result)); // ensure random subset returns exactly the same elements of original sequence Assert.That(sequence, Is.EqualTo(result.OrderBy(x => x))); } static double RelativeStandardDeviation(IEnumerable<double> values) { var average = values.Average(); var standardDeviation = StandardDeviationInternal(values, average); return (standardDeviation * 100.0) / average; } static double StandardDeviationInternal(IEnumerable<double> values, double average) { return Math.Sqrt(values.Select(value => Math.Pow(value - average, 2.0)).Average()); } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** namespace NUnit.ConsoleRunner { using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using System.Xml; using System.Resources; using System.Text; using System.Text.RegularExpressions; using System.Diagnostics; using System.Runtime.InteropServices; using NUnit.Core; using NUnit.Core.Filters; using NUnit.Util; /// <summary> /// Summary description for ConsoleUi. /// </summary> public class ConsoleUi { [STAThread] public static int Main(string[] args) { ConsoleOptions options = new ConsoleOptions(args); if(!options.nologo) WriteCopyright(); if(options.help) { options.Help(); return 0; } if(options.NoArgs) { Console.Error.WriteLine("fatal error: no inputs specified"); options.Help(); return 0; } if(!options.Validate()) { Console.Error.WriteLine("fatal error: invalid arguments"); options.Help(); return 2; } // Add Standard Services to ServiceManager ServiceManager.Services.AddService( new SettingsService() ); ServiceManager.Services.AddService( new DomainManager() ); //ServiceManager.Services.AddService( new RecentFilesService() ); //ServiceManager.Services.AddService( new TestLoader() ); ServiceManager.Services.AddService( new AddinRegistry() ); ServiceManager.Services.AddService( new AddinManager() ); // Initialize Services ServiceManager.Services.InitializeServices(); try { ConsoleUi consoleUi = new ConsoleUi(); return consoleUi.Execute( options ); } catch( FileNotFoundException ex ) { Console.WriteLine( ex.Message ); return 2; } catch( BadImageFormatException ex ) { Console.WriteLine( ex.Message ); return 2; } catch( Exception ex ) { Console.WriteLine( "Unhandled Exception:\n{0}", ex.ToString() ); return 2; } finally { if(options.wait) { Console.Out.WriteLine("\nHit <enter> key to continue"); Console.ReadLine(); } } } private static XmlTextReader GetTransformReader(ConsoleOptions parser) { XmlTextReader reader = null; if(!parser.IsTransform) { Assembly assembly = Assembly.GetAssembly(typeof(XmlResultVisitor)); ResourceManager resourceManager = new ResourceManager("NUnit.Util.Transform",assembly); string xmlData = (string)resourceManager.GetObject("Summary.xslt"); reader = new XmlTextReader(new StringReader(xmlData)); } else { FileInfo xsltInfo = new FileInfo(parser.transform); if(!xsltInfo.Exists) { Console.Error.WriteLine("Transform file: {0} does not exist", xsltInfo.FullName); reader = null; } else { reader = new XmlTextReader(xsltInfo.FullName); } } return reader; } private static void WriteCopyright() { Assembly executingAssembly = Assembly.GetExecutingAssembly(); System.Version version = executingAssembly.GetName().Version; object[] objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); AssemblyProductAttribute productAttr = (AssemblyProductAttribute)objectAttrs[0]; objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); AssemblyCopyrightAttribute copyrightAttr = (AssemblyCopyrightAttribute)objectAttrs[0]; Console.WriteLine(String.Format("{0} version {1}", productAttr.Product, version.ToString(3))); Console.WriteLine(copyrightAttr.Copyright); Console.WriteLine(); Console.WriteLine( "Runtime Environment - " ); RuntimeFramework framework = RuntimeFramework.CurrentFramework; Console.WriteLine( string.Format(" OS Version: {0}", Environment.OSVersion ) ); Console.WriteLine( string.Format(" CLR Version: {0} ( {1} )", Environment.Version, framework.GetDisplayName() ) ); Console.WriteLine(); } private static TestRunner MakeRunnerFromCommandLine( ConsoleOptions options ) { ConsoleOptions.DomainUsage domainUsage = options.domain; if ( domainUsage == ConsoleOptions.DomainUsage.Default ) domainUsage = options.ParameterCount == 1 ? ConsoleOptions.DomainUsage.Single : ConsoleOptions.DomainUsage.Multiple; TestRunner testRunner = null; switch( domainUsage ) { case ConsoleOptions.DomainUsage.None: testRunner = new NUnit.Core.RemoteTestRunner(); // Make sure that addins are available CoreExtensions.Host.AddinRegistry = Services.AddinRegistry; break; case ConsoleOptions.DomainUsage.Single: testRunner = new TestDomain(); break; case ConsoleOptions.DomainUsage.Multiple: testRunner = new MultipleTestDomainRunner(); break; } TestPackage package; if ( options.IsTestProject ) { NUnitProject project = NUnitProject.LoadProject( (string)options.Parameters[0] ); string configName = options.config; if ( configName != null ) project.SetActiveConfig( configName ); package = project.MakeTestPackage(); if ( options.IsFixture ) package.TestName = options.fixture; } else if ( options.Parameters.Count == 1 ) { package = new TestPackage( (string)options.Parameters[0] ); } else { package = new TestPackage( "UNNAMED", options.Parameters ); } if ( options.IsFixture ) package.TestName = options.fixture; package.Settings["ShadowCopyFiles"] = !options.noshadow; package.Settings["UseThreadedRunner"] = !options.nothread; testRunner.Load( package ); return testRunner; } public ConsoleUi() { } public int Execute( ConsoleOptions options ) { XmlTextReader transformReader = GetTransformReader(options); if(transformReader == null) return 3; TextWriter outWriter = Console.Out; if ( options.isOut ) { StreamWriter outStreamWriter = new StreamWriter( options.output ); outStreamWriter.AutoFlush = true; outWriter = outStreamWriter; } TextWriter errorWriter = Console.Error; if ( options.isErr ) { StreamWriter errorStreamWriter = new StreamWriter( options.err ); errorStreamWriter.AutoFlush = true; errorWriter = errorStreamWriter; } TestRunner testRunner = MakeRunnerFromCommandLine( options ); try { if (testRunner.Test == null) { testRunner.Unload(); Console.Error.WriteLine("Unable to locate fixture {0}", options.fixture); return 2; } EventCollector collector = new EventCollector( options, outWriter, errorWriter ); TestFilter catFilter = TestFilter.Empty; if (options.HasInclude) { Console.WriteLine( "Included categories: " + options.include ); catFilter = new CategoryFilter( options.IncludedCategories ); } if ( options.HasExclude ) { Console.WriteLine( "Excluded categories: " + options.exclude ); TestFilter excludeFilter = new NotFilter( new CategoryFilter( options.ExcludedCategories ) ); if ( catFilter.IsEmpty ) catFilter = excludeFilter; else catFilter = new AndFilter( catFilter, excludeFilter ); } TestResult result = null; string savedDirectory = Environment.CurrentDirectory; TextWriter savedOut = Console.Out; TextWriter savedError = Console.Error; try { result = testRunner.Run( collector, catFilter ); } finally { outWriter.Flush(); errorWriter.Flush(); if ( options.isOut ) outWriter.Close(); if ( options.isErr ) errorWriter.Close(); Environment.CurrentDirectory = savedDirectory; Console.SetOut( savedOut ); Console.SetError( savedError ); } Console.WriteLine(); string xmlOutput = CreateXmlOutput( result ); if (options.xmlConsole) { Console.WriteLine(xmlOutput); } else { try { //CreateSummaryDocument(xmlOutput, transformReader ); XmlResultTransform xform = new XmlResultTransform( transformReader ); xform.Transform( new StringReader( xmlOutput ), Console.Out ); } catch( Exception ex ) { Console.WriteLine( "Error: {0}", ex.Message ); return 3; } } // Write xml output here string xmlResultFile = options.IsXml ? options.xml : "TestResult.xml"; using ( StreamWriter writer = new StreamWriter( xmlResultFile ) ) { writer.Write(xmlOutput); } //if ( testRunner != null ) // testRunner.Unload(); if ( collector.HasExceptions ) { collector.WriteExceptions(); return 2; } return result.IsFailure ? 1 : 0; } finally { testRunner.Unload(); } } private string CreateXmlOutput( TestResult result ) { StringBuilder builder = new StringBuilder(); XmlResultVisitor resultVisitor = new XmlResultVisitor(new StringWriter( builder ), result); result.Accept(resultVisitor); resultVisitor.Write(); return builder.ToString(); } #region Nested Class to Handle Events private class EventCollector : MarshalByRefObject, EventListener { private int testRunCount; private int testIgnoreCount; private int failureCount; private int level; private ConsoleOptions options; private TextWriter outWriter; private TextWriter errorWriter; StringCollection messages; private bool progress = false; private string currentTestName; private ArrayList unhandledExceptions = new ArrayList(); public EventCollector( ConsoleOptions options, TextWriter outWriter, TextWriter errorWriter ) { level = 0; this.options = options; this.outWriter = outWriter; this.errorWriter = errorWriter; this.currentTestName = string.Empty; this.progress = !options.xmlConsole && !options.labels && !options.nodots; AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException); } public bool HasExceptions { get { return unhandledExceptions.Count > 0; } } public void WriteExceptions() { Console.WriteLine(); Console.WriteLine("Unhandled exceptions:"); int index = 1; foreach( string msg in unhandledExceptions ) Console.WriteLine( "{0}) {1}", index++, msg ); } public void RunStarted(string name, int testCount) { } public void RunFinished(TestResult result) { } public void RunFinished(Exception exception) { } public void TestFinished(TestCaseResult testResult) { if(testResult.Executed) { testRunCount++; if(testResult.IsFailure) { failureCount++; if ( progress ) Console.Write("F"); messages.Add( string.Format( "{0}) {1} :", failureCount, testResult.Test.TestName.FullName ) ); messages.Add( testResult.Message.Trim( Environment.NewLine.ToCharArray() ) ); string stackTrace = StackTraceFilter.Filter( testResult.StackTrace ); if ( stackTrace != null && stackTrace != string.Empty ) { string[] trace = stackTrace.Split( System.Environment.NewLine.ToCharArray() ); foreach( string s in trace ) { if ( s != string.Empty ) { string link = Regex.Replace( s.Trim(), @".* in (.*):line (.*)", "$1($2)"); messages.Add( string.Format( "at\n{0}", link ) ); } } } } } else { testIgnoreCount++; if ( progress ) Console.Write("N"); } currentTestName = string.Empty; } public void TestStarted(TestName testName) { currentTestName = testName.FullName; if ( options.labels ) outWriter.WriteLine("***** {0}", currentTestName ); if ( progress ) Console.Write("."); } public void SuiteStarted(TestName testName) { if ( level++ == 0 ) { messages = new StringCollection(); testRunCount = 0; testIgnoreCount = 0; failureCount = 0; Trace.WriteLine( "################################ UNIT TESTS ################################" ); Trace.WriteLine( "Running tests in '" + testName.FullName + "'..." ); } } public void SuiteFinished(TestSuiteResult suiteResult) { if ( --level == 0) { Trace.WriteLine( "############################################################################" ); if (messages.Count == 0) { Trace.WriteLine( "############## S U C C E S S #################" ); } else { Trace.WriteLine( "############## F A I L U R E S #################" ); foreach ( string s in messages ) { Trace.WriteLine(s); } } Trace.WriteLine( "############################################################################" ); Trace.WriteLine( "Executed tests : " + testRunCount ); Trace.WriteLine( "Ignored tests : " + testIgnoreCount ); Trace.WriteLine( "Failed tests : " + failureCount ); Trace.WriteLine( "Unhandled exceptions : " + unhandledExceptions.Count); Trace.WriteLine( "Total time : " + suiteResult.Time + " seconds" ); Trace.WriteLine( "############################################################################"); } } private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { if (e.ExceptionObject.GetType() != typeof(System.Threading.ThreadAbortException)) { this.UnhandledException((Exception)e.ExceptionObject); } } public void UnhandledException( Exception exception ) { // If we do labels, we already have a newline unhandledExceptions.Add(currentTestName + " : " + exception.ToString()); //if (!options.labels) outWriter.WriteLine(); string msg = string.Format("##### Unhandled Exception while running {0}", currentTestName); //outWriter.WriteLine(msg); //outWriter.WriteLine(exception.ToString()); Trace.WriteLine(msg); Trace.WriteLine(exception.ToString()); } public void TestOutput( TestOutput output) { switch ( output.Type ) { case TestOutputType.Out: outWriter.Write( output.Text ); break; case TestOutputType.Error: errorWriter.Write( output.Text ); break; } } public override object InitializeLifetimeService() { return null; } } #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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Threading { public partial class AbandonedMutexException : System.SystemException { public AbandonedMutexException() { } public AbandonedMutexException(int location, System.Threading.WaitHandle handle) { } public AbandonedMutexException(string message) { } public AbandonedMutexException(string message, System.Exception inner) { } public AbandonedMutexException(string message, System.Exception inner, int location, System.Threading.WaitHandle handle) { } public AbandonedMutexException(string message, int location, System.Threading.WaitHandle handle) { } protected AbandonedMutexException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Threading.Mutex Mutex { get { throw null; } } public int MutexIndex { get { throw null; } } } public partial struct AsyncFlowControl : System.IDisposable { public void Dispose() { } public override bool Equals(object obj) { throw null; } public bool Equals(System.Threading.AsyncFlowControl obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Threading.AsyncFlowControl a, System.Threading.AsyncFlowControl b) { throw null; } public static bool operator !=(System.Threading.AsyncFlowControl a, System.Threading.AsyncFlowControl b) { throw null; } public void Undo() { } } public sealed partial class AsyncLocal<T> { public AsyncLocal() { } [System.Security.SecurityCriticalAttribute] public AsyncLocal(System.Action<System.Threading.AsyncLocalValueChangedArgs<T>> valueChangedHandler) { } public T Value { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct AsyncLocalValueChangedArgs<T> { public T CurrentValue { get { throw null; } } public T PreviousValue { get { throw null; } } public bool ThreadContextChanged { get { throw null; } } } public sealed partial class AutoResetEvent : System.Threading.EventWaitHandle { public AutoResetEvent(bool initialState) : base(default(bool), default(System.Threading.EventResetMode)) { } } public partial class Barrier : System.IDisposable { public Barrier(int participantCount) { } public Barrier(int participantCount, System.Action<System.Threading.Barrier> postPhaseAction) { } public long CurrentPhaseNumber { get { throw null; } } public int ParticipantCount { get { throw null; } } public int ParticipantsRemaining { get { throw null; } } public long AddParticipant() { throw null; } public long AddParticipants(int participantCount) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void RemoveParticipant() { } public void RemoveParticipants(int participantCount) { } public void SignalAndWait() { } public bool SignalAndWait(int millisecondsTimeout) { throw null; } public bool SignalAndWait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public void SignalAndWait(System.Threading.CancellationToken cancellationToken) { } public bool SignalAndWait(System.TimeSpan timeout) { throw null; } public bool SignalAndWait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class BarrierPostPhaseException : System.Exception { public BarrierPostPhaseException() { } public BarrierPostPhaseException(System.Exception innerException) { } public BarrierPostPhaseException(string message) { } public BarrierPostPhaseException(string message, System.Exception innerException) { } protected BarrierPostPhaseException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public delegate void ContextCallback(object state); public partial class CountdownEvent : System.IDisposable { public CountdownEvent(int initialCount) { } public int CurrentCount { get { throw null; } } public int InitialCount { get { throw null; } } public bool IsSet { get { throw null; } } public System.Threading.WaitHandle WaitHandle { get { throw null; } } public void AddCount() { } public void AddCount(int signalCount) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void Reset() { } public void Reset(int count) { } public bool Signal() { throw null; } public bool Signal(int signalCount) { throw null; } public bool TryAddCount() { throw null; } public bool TryAddCount(int signalCount) { throw null; } public void Wait() { } public bool Wait(int millisecondsTimeout) { throw null; } public bool Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public void Wait(System.Threading.CancellationToken cancellationToken) { } public bool Wait(System.TimeSpan timeout) { throw null; } public bool Wait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } } public enum EventResetMode { AutoReset = 0, ManualReset = 1, } public partial class EventWaitHandle : System.Threading.WaitHandle { public EventWaitHandle(bool initialState, System.Threading.EventResetMode mode) { } [System.Security.SecurityCriticalAttribute] public EventWaitHandle(bool initialState, System.Threading.EventResetMode mode, string name) { } [System.Security.SecurityCriticalAttribute] public EventWaitHandle(bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew) { throw null; } [System.Security.SecurityCriticalAttribute] public static System.Threading.EventWaitHandle OpenExisting(string name) { throw null; } public bool Reset() { throw null; } public bool Set() { throw null; } [System.Security.SecurityCriticalAttribute] public static bool TryOpenExisting(string name, out System.Threading.EventWaitHandle result) { throw null; } } public sealed partial class ExecutionContext : System.IDisposable, System.Runtime.Serialization.ISerializable { private ExecutionContext() { } public static System.Threading.ExecutionContext Capture() { throw null; } public System.Threading.ExecutionContext CreateCopy() { throw null; } public void Dispose() { } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public static bool IsFlowSuppressed() { throw null; } public static void RestoreFlow() { } public static void Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) { } public static System.Threading.AsyncFlowControl SuppressFlow() { throw null; } } public partial class HostExecutionContext : System.IDisposable { public HostExecutionContext() { } public HostExecutionContext(object state) { } protected internal object State { get { throw null; } set { } } public virtual System.Threading.HostExecutionContext CreateCopy() { throw null; } public void Dispose() { } public virtual void Dispose(bool disposing) { } } public partial class HostExecutionContextManager { public HostExecutionContextManager() { } public virtual System.Threading.HostExecutionContext Capture() { throw null; } public virtual void Revert(object previousState) { } public virtual object SetHostExecutionContext(System.Threading.HostExecutionContext hostExecutionContext) { throw null; } } public static partial class Interlocked { public static int Add(ref int location1, int value) { throw null; } public static long Add(ref long location1, long value) { throw null; } public static double CompareExchange(ref double location1, double value, double comparand) { throw null; } public static int CompareExchange(ref int location1, int value, int comparand) { throw null; } public static long CompareExchange(ref long location1, long value, long comparand) { throw null; } public static System.IntPtr CompareExchange(ref System.IntPtr location1, System.IntPtr value, System.IntPtr comparand) { throw null; } public static object CompareExchange(ref object location1, object value, object comparand) { throw null; } public static float CompareExchange(ref float location1, float value, float comparand) { throw null; } public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class { throw null; } public static int Decrement(ref int location) { throw null; } public static long Decrement(ref long location) { throw null; } public static double Exchange(ref double location1, double value) { throw null; } public static int Exchange(ref int location1, int value) { throw null; } public static long Exchange(ref long location1, long value) { throw null; } public static System.IntPtr Exchange(ref System.IntPtr location1, System.IntPtr value) { throw null; } public static object Exchange(ref object location1, object value) { throw null; } public static float Exchange(ref float location1, float value) { throw null; } public static T Exchange<T>(ref T location1, T value) where T : class { throw null; } public static int Increment(ref int location) { throw null; } public static long Increment(ref long location) { throw null; } public static void MemoryBarrier() { } public static void MemoryBarrierProcessWide() { } public static long Read(ref long location) { throw null; } } public static partial class LazyInitializer { public static T EnsureInitialized<T>(ref T target) where T : class { throw null; } public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock) { throw null; } public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock, System.Func<T> valueFactory) { throw null; } public static T EnsureInitialized<T>(ref T target, System.Func<T> valueFactory) where T : class { throw null; } public static T EnsureInitialized<T>(ref T target, ref object syncLock, System.Func<T> valueFactory) where T : class { throw null; } } public partial struct LockCookie { public override bool Equals(object obj) { throw null; } public bool Equals(System.Threading.LockCookie obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Threading.LockCookie a, System.Threading.LockCookie b) { throw null; } public static bool operator !=(System.Threading.LockCookie a, System.Threading.LockCookie b) { throw null; } } public partial class LockRecursionException : System.Exception { public LockRecursionException() { } public LockRecursionException(string message) { } public LockRecursionException(string message, System.Exception innerException) { } protected LockRecursionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public enum LockRecursionPolicy { NoRecursion = 0, SupportsRecursion = 1, } public sealed partial class ManualResetEvent : System.Threading.EventWaitHandle { public ManualResetEvent(bool initialState) : base(default(bool), default(System.Threading.EventResetMode)) { } } public partial class ManualResetEventSlim : System.IDisposable { public ManualResetEventSlim() { } public ManualResetEventSlim(bool initialState) { } public ManualResetEventSlim(bool initialState, int spinCount) { } public bool IsSet { get { throw null; } } public int SpinCount { get { throw null; } } public System.Threading.WaitHandle WaitHandle { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void Reset() { } public void Set() { } public void Wait() { } public bool Wait(int millisecondsTimeout) { throw null; } public bool Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public void Wait(System.Threading.CancellationToken cancellationToken) { } public bool Wait(System.TimeSpan timeout) { throw null; } public bool Wait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } } public static partial class Monitor { public static void Enter(object obj) { } public static void Enter(object obj, ref bool lockTaken) { } public static void Exit(object obj) { } public static bool IsEntered(object obj) { throw null; } public static void Pulse(object obj) { } public static void PulseAll(object obj) { } public static bool TryEnter(object obj) { throw null; } public static void TryEnter(object obj, ref bool lockTaken) { } public static bool TryEnter(object obj, int millisecondsTimeout) { throw null; } public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTaken) { } public static bool TryEnter(object obj, System.TimeSpan timeout) { throw null; } public static void TryEnter(object obj, System.TimeSpan timeout, ref bool lockTaken) { } public static bool Wait(object obj) { throw null; } public static bool Wait(object obj, int millisecondsTimeout) { throw null; } public static bool Wait(object obj, int millisecondsTimeout, bool exitContext) { throw null; } public static bool Wait(object obj, System.TimeSpan timeout) { throw null; } public static bool Wait(object obj, System.TimeSpan timeout, bool exitContext) { throw null; } } public sealed partial class Mutex : System.Threading.WaitHandle { public Mutex() { } public Mutex(bool initiallyOwned) { } [System.Security.SecurityCriticalAttribute] public Mutex(bool initiallyOwned, string name) { } [System.Security.SecurityCriticalAttribute] public Mutex(bool initiallyOwned, string name, out bool createdNew) { throw null; } [System.Security.SecurityCriticalAttribute] public static System.Threading.Mutex OpenExisting(string name) { throw null; } public void ReleaseMutex() { } [System.Security.SecurityCriticalAttribute] public static bool TryOpenExisting(string name, out System.Threading.Mutex result) { throw null; } } public sealed partial class ReaderWriterLock : System.Runtime.ConstrainedExecution.CriticalFinalizerObject { public ReaderWriterLock() { } public bool IsReaderLockHeld { get { throw null; } } public bool IsWriterLockHeld { get { throw null; } } public int WriterSeqNum { get { throw null; } } public void AcquireReaderLock(int millisecondsTimeout) { } public void AcquireReaderLock(System.TimeSpan timeout) { } public void AcquireWriterLock(int millisecondsTimeout) { } public void AcquireWriterLock(System.TimeSpan timeout) { } public bool AnyWritersSince(int seqNum) { throw null; } public void DowngradeFromWriterLock(ref System.Threading.LockCookie lockCookie) { } ~ReaderWriterLock() { } public System.Threading.LockCookie ReleaseLock() { throw null; } public void ReleaseReaderLock() { } public void ReleaseWriterLock() { } public void RestoreLock(ref System.Threading.LockCookie lockCookie) { } public System.Threading.LockCookie UpgradeToWriterLock(int millisecondsTimeout) { throw null; } public System.Threading.LockCookie UpgradeToWriterLock(System.TimeSpan timeout) { throw null; } } public partial class ReaderWriterLockSlim : System.IDisposable { public ReaderWriterLockSlim() { } public ReaderWriterLockSlim(System.Threading.LockRecursionPolicy recursionPolicy) { } public int CurrentReadCount { get { throw null; } } public bool IsReadLockHeld { get { throw null; } } public bool IsUpgradeableReadLockHeld { get { throw null; } } public bool IsWriteLockHeld { get { throw null; } } public System.Threading.LockRecursionPolicy RecursionPolicy { get { throw null; } } public int RecursiveReadCount { get { throw null; } } public int RecursiveUpgradeCount { get { throw null; } } public int RecursiveWriteCount { get { throw null; } } public int WaitingReadCount { get { throw null; } } public int WaitingUpgradeCount { get { throw null; } } public int WaitingWriteCount { get { throw null; } } public void Dispose() { } public void EnterReadLock() { } public void EnterUpgradeableReadLock() { } public void EnterWriteLock() { } public void ExitReadLock() { } public void ExitUpgradeableReadLock() { } public void ExitWriteLock() { } public bool TryEnterReadLock(int millisecondsTimeout) { throw null; } public bool TryEnterReadLock(System.TimeSpan timeout) { throw null; } public bool TryEnterUpgradeableReadLock(int millisecondsTimeout) { throw null; } public bool TryEnterUpgradeableReadLock(System.TimeSpan timeout) { throw null; } public bool TryEnterWriteLock(int millisecondsTimeout) { throw null; } public bool TryEnterWriteLock(System.TimeSpan timeout) { throw null; } } public sealed partial class Semaphore : System.Threading.WaitHandle { public Semaphore(int initialCount, int maximumCount) { } public Semaphore(int initialCount, int maximumCount, string name) { } public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew) { throw null; } public static System.Threading.Semaphore OpenExisting(string name) { throw null; } public int Release() { throw null; } public int Release(int releaseCount) { throw null; } public static bool TryOpenExisting(string name, out System.Threading.Semaphore result) { throw null; } } public partial class SemaphoreFullException : System.SystemException { public SemaphoreFullException() { } public SemaphoreFullException(string message) { } public SemaphoreFullException(string message, System.Exception innerException) { } protected SemaphoreFullException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class SemaphoreSlim : System.IDisposable { public SemaphoreSlim(int initialCount) { } public SemaphoreSlim(int initialCount, int maxCount) { } public System.Threading.WaitHandle AvailableWaitHandle { get { throw null; } } public int CurrentCount { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public int Release() { throw null; } public int Release(int releaseCount) { throw null; } public void Wait() { } public bool Wait(int millisecondsTimeout) { throw null; } public bool Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public void Wait(System.Threading.CancellationToken cancellationToken) { } public bool Wait(System.TimeSpan timeout) { throw null; } public bool Wait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task WaitAsync() { throw null; } public System.Threading.Tasks.Task<bool> WaitAsync(int millisecondsTimeout) { throw null; } public System.Threading.Tasks.Task<bool> WaitAsync(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task WaitAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<bool> WaitAsync(System.TimeSpan timeout) { throw null; } public System.Threading.Tasks.Task<bool> WaitAsync(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } } public delegate void SendOrPostCallback(object state); [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SpinLock { public SpinLock(bool enableThreadOwnerTracking) { throw null; } public bool IsHeld { get { throw null; } } public bool IsHeldByCurrentThread { get { throw null; } } public bool IsThreadOwnerTrackingEnabled { get { throw null; } } public void Enter(ref bool lockTaken) { } public void Exit() { } public void Exit(bool useMemoryBarrier) { } public void TryEnter(ref bool lockTaken) { } public void TryEnter(int millisecondsTimeout, ref bool lockTaken) { } public void TryEnter(System.TimeSpan timeout, ref bool lockTaken) { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SpinWait { public int Count { get { throw null; } } public bool NextSpinWillYield { get { throw null; } } public void Reset() { } public void SpinOnce() { } public static void SpinUntil(System.Func<bool> condition) { } public static bool SpinUntil(System.Func<bool> condition, int millisecondsTimeout) { throw null; } public static bool SpinUntil(System.Func<bool> condition, System.TimeSpan timeout) { throw null; } } public partial class SynchronizationContext { public SynchronizationContext() { } public static System.Threading.SynchronizationContext Current { get { throw null; } } public virtual System.Threading.SynchronizationContext CreateCopy() { throw null; } public bool IsWaitNotificationRequired() { throw null; } public virtual void OperationCompleted() { } public virtual void OperationStarted() { } public virtual void Post(System.Threading.SendOrPostCallback d, object state) { } public virtual void Send(System.Threading.SendOrPostCallback d, object state) { } public static void SetSynchronizationContext(System.Threading.SynchronizationContext syncContext) { } protected void SetWaitNotificationRequired() { } [System.CLSCompliantAttribute(false)] [System.Runtime.ConstrainedExecution.PrePrepareMethodAttribute] public virtual int Wait(System.IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { throw null; } [System.CLSCompliantAttribute(false)] [System.Runtime.ConstrainedExecution.PrePrepareMethodAttribute] protected static int WaitHelper(System.IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { throw null; } } public partial class SynchronizationLockException : System.SystemException { public SynchronizationLockException() { } public SynchronizationLockException(string message) { } public SynchronizationLockException(string message, System.Exception innerException) { } protected SynchronizationLockException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class ThreadLocal<T> : System.IDisposable { public ThreadLocal() { } public ThreadLocal(bool trackAllValues) { } public ThreadLocal(System.Func<T> valueFactory) { } public ThreadLocal(System.Func<T> valueFactory, bool trackAllValues) { } public bool IsValueCreated { get { throw null; } } public T Value { get { throw null; } set { } } public System.Collections.Generic.IList<T> Values { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~ThreadLocal() { } public override string ToString() { throw null; } } public static partial class Volatile { public static bool Read(ref bool location) { throw null; } public static byte Read(ref byte location) { throw null; } public static double Read(ref double location) { throw null; } public static short Read(ref short location) { throw null; } public static int Read(ref int location) { throw null; } public static long Read(ref long location) { throw null; } public static System.IntPtr Read(ref System.IntPtr location) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte Read(ref sbyte location) { throw null; } public static float Read(ref float location) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort Read(ref ushort location) { throw null; } [System.CLSCompliantAttribute(false)] public static uint Read(ref uint location) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong Read(ref ulong location) { throw null; } [System.CLSCompliantAttribute(false)] public static System.UIntPtr Read(ref System.UIntPtr location) { throw null; } public static T Read<T>(ref T location) where T : class { throw null; } public static void Write(ref bool location, bool value) { } public static void Write(ref byte location, byte value) { } public static void Write(ref double location, double value) { } public static void Write(ref short location, short value) { } public static void Write(ref int location, int value) { } public static void Write(ref long location, long value) { } public static void Write(ref System.IntPtr location, System.IntPtr value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref sbyte location, sbyte value) { } public static void Write(ref float location, float value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref ushort location, ushort value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref uint location, uint value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref ulong location, ulong value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref System.UIntPtr location, System.UIntPtr value) { } public static void Write<T>(ref T location, T value) where T : class { } } public partial class WaitHandleCannotBeOpenedException : System.ApplicationException { public WaitHandleCannotBeOpenedException() { } public WaitHandleCannotBeOpenedException(string message) { } public WaitHandleCannotBeOpenedException(string message, System.Exception innerException) { } protected WaitHandleCannotBeOpenedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } }
// 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.Linq; using System.Text; using Microsoft.Research.AbstractDomains.Expressions; using System.Diagnostics.Contracts; using Microsoft.Research.DataStructures; using System.Diagnostics.CodeAnalysis; namespace Microsoft.Research.AbstractDomains.Numerical { [ContractVerification(true)] public class PentagonsPlus<Variable, Expression> : ReducedNumericalDomains<WeakUpperBoundsEqual<Variable, Expression>, Pentagons<Variable, Expression>, Variable, Expression> { #region Constructor public PentagonsPlus( WeakUpperBoundsEqual<Variable, Expression> left, Pentagons<Variable, Expression> right, ExpressionManagerWithEncoder<Variable, Expression> expManager) : base(left, right, expManager) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Requires(expManager != null); } #endregion #region Assign public override void Assign(Expression x, Expression exp) { // F: I am lazy... Contract.Assume(x != null); Contract.Assume(exp != null); // Infer some x >= 0 invariants which requires the information from the two domains // The information should be inferred in the pre-state var geqZero = new GreaterEqualThanZeroConstraints<Variable, Expression>(this.ExpressionManager).InferConstraints(x, exp, this); this.Left.Assign(x, exp, this); this.Right.Assign(x, exp); // The information is assumed in the post-state... foreach (var condition in geqZero) { this.TestTrue(condition); } } public override void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> convert) { var right = this.Right; this.AssignInParallel(this.Left, right.Right, sourcesToTargets, right.Left as INumericalAbstractDomain<Variable, Expression>); right.Left.AssignInParallel(sourcesToTargets, convert); } private void AssignInParallel (WeakUpperBoundsEqual<Variable, Expression> wubeq, WeakUpperBounds<Variable, Expression> wub, Dictionary<Variable, FList<Variable>> sourcesToTargets, INumericalAbstractDomain<Variable, Expression> oracleDomain) { Contract.Requires(wubeq != null); Contract.Requires(wub != null); // adding the domain-generated variables to the map as identity var oldToNewMap = new Dictionary<Variable, FList<Variable>>(sourcesToTargets); if (!wubeq.IsTop) { foreach (var e in wubeq.SlackVariables) { oldToNewMap[e] = FList<Variable>.Cons(e, FList<Variable>.Empty); } } if (!wub.IsTop) { foreach (var e in wub.SlackVariables) { oldToNewMap[e] = FList<Variable>.Cons(e, FList<Variable>.Empty); } } // when x has several targets including itself, the canonical element shouldn't be itself foreach (var sourceToTargets in sourcesToTargets) { var source = sourceToTargets.Key; var targets = sourceToTargets.Value; Contract.Assume(targets != null); if (targets.Length() > 1 && targets.Head.Equals(source)) { var tail = targets.Tail; Contract.Assert(tail != null); var newTargets = FList<Variable>.Cons(tail.Head, FList<Variable>.Cons(source, tail.Tail)); oldToNewMap[source] = newTargets; } } AssignInParallelWUBSpecific(wub, oldToNewMap); AssignInParallelWUBEQSpecific(wubeq, sourcesToTargets, oldToNewMap); } private void AssignInParallelWUBSpecific(WeakUpperBounds<Variable, Expression> wub, Dictionary<Variable, FList<Variable>> oldToNewMap) { Contract.Requires(wub != null); Contract.Requires(oldToNewMap != null); var newMappings = new Dictionary<Variable, List<Variable>>(wub.Count); foreach (var oldLeft_pair in wub.Elements) { if (!oldToNewMap.ContainsKey(oldLeft_pair.Key)) { continue; } var target = oldToNewMap[oldLeft_pair.Key]; Contract.Assume(target != null); var newLeft = target.Head; // our canonical element var oldBounds = oldLeft_pair.Value; if (!oldBounds.IsNormal()) { continue; } foreach (var oldRight in oldBounds.Values) { FList<Variable> olds; if (oldToNewMap.TryGetValue(oldRight, out olds)) { Contract.Assume(olds != null); // This case is so so common that we want to specialize it if (olds.Length() == 1) { var newRight = olds.Head; // our canonical element AddUpperBound(newLeft, newRight, newMappings); } else { foreach (var newRight in olds.GetEnumerable()) { AddUpperBound(newLeft, newRight, newMappings); } } } } // There are some more elements for (var list = oldToNewMap[oldLeft_pair.Key].Tail; list != null; list = list.Tail) { List<Variable> targets; if (newMappings.TryGetValue(newLeft, out targets)) { Contract.Assume(targets != null); foreach (var con in targets) { AddUpperBound(list.Head, con, newMappings); } } } } // Update var newConstraints = new Dictionary<Variable, SetOfConstraints<Variable>>(wub.Count); foreach (var pair in newMappings) { Contract.Assume(pair.Value != null); newConstraints.Add(pair.Key, new SetOfConstraints<Variable>(pair.Value)); } wub.SetElements(newConstraints); } private void AssignInParallelWUBEQSpecific( WeakUpperBoundsEqual<Variable, Expression> wubeq, Dictionary<Variable, FList<Variable>> sourcesToTargets, Dictionary<Variable, FList<Variable>> oldToNewMap) { Contract.Requires(wubeq != null); Contract.Requires(sourcesToTargets != null); Contract.Requires(oldToNewMap != null); var newMappings = new Dictionary<Variable, List<Variable>>(wubeq.Count); foreach (var oldLeft_Pair in wubeq.Elements) { FList<Variable> targets; if (oldToNewMap.TryGetValue(oldLeft_Pair.Key, out targets)) { Contract.Assume(targets != null); var oldBounds = oldLeft_Pair.Value; if (!oldBounds.IsNormal()) { continue; } var newLeft = targets.Head; // our canonical element foreach (var oldRight in oldBounds.Values) { FList<Variable> olds; if (oldToNewMap.TryGetValue(oldRight, out olds)) { Contract.Assume(olds != null); var newRight = olds.Head; // our canonical element AddUpperBound(newLeft, newRight, newMappings); } } } } // Precision improvements: // // Consider: // if (x < y) x = y; // Debug.Assert(x >= y); // // This is an example where at the end of the then branch, we have a single old variable being assigned to new new variables: // x := y' and y := y' // Since in this branch, we obviously have y' => y', the new renamed state should have y => x and x => y. That way, at the join, // the constraint x >= y is retained. // foreach (var pair in sourcesToTargets) { var targets = pair.Value; Contract.Assume(targets != null); var newCanonical = targets.Head; targets = targets.Tail; while (targets != null) { // make all other targets equal to canonical (rather than n^2 combinations) AddUpperBound(newCanonical, targets.Head, newMappings); AddUpperBound(targets.Head, newCanonical, newMappings); targets = targets.Tail; } } var result = new List<Pair<Variable, SetOfConstraints<Variable>>>(); // now add the new mappings foreach (var pair in newMappings) { var bounds = pair.Value; Contract.Assume(bounds != null); if (bounds.Count == 0) { continue; } var newBoundsFromClosure = new Set<Variable>(bounds); foreach (var upp in bounds) { List<Variable> values; if (!upp.Equals(pair.Key) && newMappings.TryGetValue(upp, out values)) { Contract.Assume(values != null); newBoundsFromClosure.AddRange(values); } } result.Add(pair.Key, new SetOfConstraints<Variable>(newBoundsFromClosure, false)); } wubeq.SetElements(result); } static internal void AddUpperBound(Variable key, Variable upperBound, Dictionary<Variable, List<Variable>> map) { Contract.Requires(map != null); List<Variable> bounds; if (!map.TryGetValue(key, out bounds)) { bounds = new List<Variable>(); map.Add(key, bounds); } Contract.Assume(bounds != null); // If we have it in the dictionary, then it is != null bounds.Add(upperBound); } #endregion #region Abstract domain operations public override IAbstractDomain Join(IAbstractDomain a) { if (this.IsBottom) return a; if (a.IsBottom) return this; if (this.IsTop) return this; if (a.IsTop) return a; var r = a as PentagonsPlus<Variable, Expression>; Contract.Assume(r != null, "Error cannot compare a cartesian abstract element with a " + a.GetType()); // These two lines have a weak notion of closure, which essentially avoids dropping "x <= y" if it is implied by the intervals abstract domain // It seems that it is as precise as the expensive join var joinLeftPart = this.Left.Join(r.Left, this.Right.Left, r.Right.Left); Contract.Assert(joinLeftPart != null); var joinRightPart = this.Right.Join(r.Right) as Pentagons<Variable, Expression>; Contract.Assume(joinRightPart != null); return new PentagonsPlus<Variable, Expression>(joinLeftPart, joinRightPart, this.ExpressionManager); } public override FlatAbstractDomain<bool> CheckIfGreaterEqualThanZero(Expression exp) { var left = this.Left.CheckIfGreaterEqualThanZero(exp); if (!left.IsTop) { return left; } return this.Right.CheckIfGreaterEqualThanZero(exp); } public override FlatAbstractDomain<bool> CheckIfLessThan(Expression e1, Expression e2) { var left = Left.CheckIfLessThan(e1, e2, Right); if (!left.IsTop) { return left; } return Right.CheckIfLessThan(e1, e2); } public override FlatAbstractDomain<bool> CheckIfLessThan_Un(Expression e1, Expression e2) { var left = Left.CheckIfLessThan_Un(e1, e2); if (!left.IsTop) { return left; } return Right.CheckIfLessThan_Un(e1, e2); } public override FlatAbstractDomain<bool> CheckIfLessEqualThan(Expression e1, Expression e2) { var left = Left.CheckIfLessEqualThan(e1, e2); if (!left.IsTop) { return left; } return Right.CheckIfLessEqualThan(e1, e2); } public override FlatAbstractDomain<bool> CheckIfLessEqualThan_Un(Expression e1, Expression e2) { var left = Left.CheckIfLessEqualThan_Un(e1, e2); if (!left.IsTop) { return left; } return Right.CheckIfLessEqualThan_Un(e1, e2); } public override IAbstractDomainForEnvironments<Variable, Expression> TestTrue(Expression guard) { Expression e1, e2; var newLeft = this.Left; var newRight = this.Right; if (this.IsLessThanPositive(guard, out e1, out e2)) { // We have e1 < e2. If we already know that e1 >= e2. then we have a contraddiction if (this.CheckIfLessEqualThan(e2, e1).IsTrue()) { var bott = this.Bottom as PentagonsPlus<Variable, Expression>; Contract.Assume(bott != null); return bott; } var decoder = this.ExpressionManager.Decoder; var e1Var = decoder.UnderlyingVariable(e1); var e2Var = decoder.UnderlyingVariable(e2); SetOfConstraints<Variable> upperBounds; if (this.Left.TryGetValue(e2Var, out upperBounds)) { // if guard == "e1 < e2" and we know that "e2 <= e3", then we also have "e1 < e3" if (upperBounds.IsNormal()) { foreach (var e3 in upperBounds.Values) { newRight = newRight.TestTrueLessThan(e1Var, e3); } } } } else if (this.TryMatchNotEqualTo(guard, out e1, out e2)) { newRight = HelperForTestTrueNotEqual(e1, e2, newRight); } newLeft = newLeft.TestTrue(guard); newRight = newRight.TestTrue(guard); return new PentagonsPlus<Variable, Expression>(newLeft, newRight, this.ExpressionManager); } public override IAbstractDomainForEnvironments<Variable, Expression> TestFalse(Expression guard) { Expression e1, e2; var newLeft = this.Left; var newRight = this.Right; if (this.TryMatchEqualTo(guard, out e1, out e2)) { // if "e1 != e2", then we can restrain "e1 <= e2" (resp "e2 <= e1") to "e1 < e2" (resp "e2 < e1") newRight = HelperForTestTrueNotEqual(e1, e2, newRight); } newLeft = newLeft.TestFalse(guard); newRight = newRight.TestFalse(guard); return new PentagonsPlus<Variable, Expression>(newLeft, newRight, this.ExpressionManager); } public override INumericalAbstractDomain<Variable, Expression> TestTrueLessThan(Expression exp1, Expression exp2) { var withPentagons = this as PentagonsPlus<Variable, Expression>; var newLeft = this.Left; var newRight = withPentagons.Right.TestTrueLessThan(exp1, exp2, this.Left); newLeft = newLeft.TestTrueLessThan(exp1, exp2); Contract.Assert(withPentagons.ExpressionManager.Encoder != null); return new PentagonsPlus<Variable, Expression>(newLeft, newRight, withPentagons.ExpressionManager); } [Pure] public override ReducedCartesianAbstractDomain<WeakUpperBoundsEqual<Variable, Expression>, Pentagons<Variable, Expression>> Reduce(WeakUpperBoundsEqual<Variable, Expression> left, Pentagons<Variable, Expression> right) { return this.Factory(left, right); } [Pure] protected override ReducedCartesianAbstractDomain<WeakUpperBoundsEqual<Variable, Expression>, Pentagons<Variable, Expression>> Factory(WeakUpperBoundsEqual<Variable, Expression> left, Pentagons<Variable, Expression> right) { Contract.Ensures(Contract.Result<ReducedCartesianAbstractDomain<WeakUpperBoundsEqual<Variable, Expression>, Pentagons<Variable, Expression>>>() != null); return new PentagonsPlus<Variable, Expression>(left, right, this.ExpressionManager); } #endregion #region Private methods private Pentagons<Variable, Expression> HelperForTestTrueNotEqual(Expression e1, Expression e2, Pentagons<Variable, Expression> newRight) { Contract.Requires(newRight != null); Contract.Ensures(Contract.Result<Pentagons<Variable, Expression>>() != null); var decoder = this.ExpressionManager.Decoder; // Get rid of the conversion operators e1 = decoder.Stripped(e1); e2 = decoder.Stripped(e2); var e1Var = decoder.UnderlyingVariable(e1); var e2Var = decoder.UnderlyingVariable(e2); SetOfConstraints<Variable> upperBounds; if (this.Left.TryGetValue(e1Var, out upperBounds)) { if (upperBounds.IsNormal() && upperBounds.Contains(e2Var)) { // if "e1 <= e2" then "e2 < e1" newRight = newRight.TestTrueLessThan(e1, e2); } } if (this.Left.TryGetValue(e2Var, out upperBounds)) { if (upperBounds.IsNormal() && upperBounds.Contains(e1Var)) { // if "e2 <= e1" then "e2 < e1" newRight = newRight.TestTrueLessThan(e2, e1); } } return newRight; } private bool IsLessThanPositive(Expression guard, out Expression e1, out Expression e2) { ExpressionOperator op; e1 = default(Expression); e2 = default(Expression); var decoder = this.ExpressionManager.Decoder; switch (decoder.OperatorFor(guard)) { case ExpressionOperator.Equal: case ExpressionOperator.Equal_Obj: if (decoder.Match_E1relopE2eq0(decoder.LeftExpressionFor(guard), decoder.RightExpressionFor(guard), out op, out e1, out e2)) { // here guard is "(e1 op e2) == 0" return this.IsLessThanNegative(decoder.LeftExpressionFor(guard), out e1, out e2); } else { return false; } case ExpressionOperator.GreaterThan: { e1 = decoder.RightExpressionFor(guard); e2 = decoder.LeftExpressionFor(guard); return true; } case ExpressionOperator.LessThan: { e1 = decoder.LeftExpressionFor(guard); e2 = decoder.RightExpressionFor(guard); return true; } case ExpressionOperator.GreaterThan_Un: case ExpressionOperator.LessThan_Un: default: { return false; } } } private bool IsLessThanNegative(Expression guard, out Expression e1, out Expression e2) { ExpressionOperator op; e1 = default(Expression); e2 = default(Expression); var decoder = this.ExpressionManager.Decoder; switch (decoder.OperatorFor(guard)) { case ExpressionOperator.Equal: case ExpressionOperator.Equal_Obj: if (decoder.Match_E1relopE2eq0(decoder.LeftExpressionFor(guard), decoder.RightExpressionFor(guard), out op, out e1, out e2)) { // the guard is "(e1 op e2) == 0" return this.IsLessThanPositive(decoder.LeftExpressionFor(guard), out e1, out e2); } else { return false; } case ExpressionOperator.GreaterEqualThan: { // !(a >= b) == (a < b) e1 = decoder.LeftExpressionFor(guard); e2 = decoder.RightExpressionFor(guard); return true; } case ExpressionOperator.LessEqualThan: { // !(a <= b) == (a > b) == (b < a) e1 = decoder.RightExpressionFor(guard); e2 = decoder.LeftExpressionFor(guard); return true; } default: { return false; } } } private bool TryMatchEqualTo(Expression guard, out Expression e1, out Expression e2) { var decoder = this.ExpressionManager.Decoder; switch (decoder.OperatorFor(guard)) { case ExpressionOperator.Equal: case ExpressionOperator.Equal_Obj: { e1 = decoder.Stripped(this.ExpressionManager.Decoder.LeftExpressionFor(guard)); e2 = decoder.Stripped(this.ExpressionManager.Decoder.RightExpressionFor(guard)); return true; } default: { e1 = e2 = default(Expression); return false; } } } private bool TryMatchNotEqualTo(Expression guard, out Expression e1, out Expression e2) { var decoder = this.ExpressionManager.Decoder; var op_guard = decoder.OperatorFor(guard); switch (op_guard) { case ExpressionOperator.Equal: case ExpressionOperator.Equal_Obj: { ExpressionOperator op; if (decoder.Match_E1relopE2eq0(decoder.LeftExpressionFor(guard), decoder.RightExpressionFor(guard), out op, out e1, out e2)) { if (op == op_guard) { return true; } } goto default; } case ExpressionOperator.NotEqual: { e1 = decoder.LeftExpressionFor(guard); e2 = decoder.RightExpressionFor(guard); return true; } default: { e1 = e2 = default(Expression); return false; } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using Xunit; namespace System.Tests { public static partial class TimeSpanTests { private static IEnumerable<object[]> MultiplicationTestData() { yield return new object[] {new TimeSpan(2, 30, 0), 2.0, new TimeSpan(5, 0, 0)}; yield return new object[] {new TimeSpan(14, 2, 30, 0), 192.0, TimeSpan.FromDays(2708)}; yield return new object[] {TimeSpan.FromDays(366), Math.PI, new TimeSpan(993446995288779)}; yield return new object[] {TimeSpan.FromDays(366), -Math.E, new TimeSpan(-859585952922633)}; yield return new object[] {TimeSpan.FromDays(29.530587981), 13.0, TimeSpan.FromDays(383.897643819444)}; yield return new object[] {TimeSpan.FromDays(-29.530587981), -12.0, TimeSpan.FromDays(354.367055833333)}; yield return new object[] {TimeSpan.FromDays(-29.530587981), 0.0, TimeSpan.Zero}; yield return new object[] {TimeSpan.MaxValue, 0.5, TimeSpan.FromTicks((long)(long.MaxValue * 0.5))}; } [Theory, MemberData(nameof(MultiplicationTestData))] public static void Multiplication(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(expected, timeSpan * factor); Assert.Equal(expected, factor * timeSpan); } [Fact] public static void OverflowingMultiplication() { Assert.Throws<OverflowException>(() => TimeSpan.MaxValue * 1.000000001); Assert.Throws<OverflowException>(() => -1.000000001 * TimeSpan.MaxValue); } [Fact] public static void NaNMultiplication() { AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1) * double.NaN); AssertExtensions.Throws<ArgumentException>("factor", () => double.NaN * TimeSpan.FromDays(1)); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void Division(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(factor, expected / timeSpan, 14); double divisor = 1.0 / factor; Assert.Equal(expected, timeSpan / divisor); } [Fact] public static void DivideByZero() { Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1) / 0); Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1) / 0); Assert.Throws<OverflowException>(() => TimeSpan.Zero / 0); Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1) / TimeSpan.Zero); Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1) / TimeSpan.Zero); Assert.True(double.IsNaN(TimeSpan.Zero / TimeSpan.Zero)); } [Fact] public static void NaNDivision() { AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1) / double.NaN); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void NamedMultiplication(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(expected, timeSpan.Multiply(factor)); } [Fact] public static void NamedOverflowingMultiplication() { Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Multiply(1.000000001)); } [Fact] public static void NamedNaNMultiplication() { AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1).Multiply(double.NaN)); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void NamedDivision(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(factor, expected.Divide(timeSpan), 14); double divisor = 1.0 / factor; Assert.Equal(expected, timeSpan.Divide(divisor)); } [Fact] public static void NamedDivideByZero() { Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1).Divide(0)); Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1).Divide(0)); Assert.Throws<OverflowException>(() => TimeSpan.Zero.Divide(0)); Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1).Divide(TimeSpan.Zero)); Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1).Divide(TimeSpan.Zero)); Assert.True(double.IsNaN(TimeSpan.Zero.Divide(TimeSpan.Zero))); } [Fact] public static void NamedNaNDivision() { AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1).Divide(double.NaN)); } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse_Span(string inputString, IFormatProvider provider, TimeSpan expected) { ReadOnlySpan<char> input = inputString.AsReadOnlySpan(); TimeSpan result; Assert.Equal(expected, TimeSpan.Parse(input, provider)); Assert.True(TimeSpan.TryParse(input, provider, out result)); Assert.Equal(expected, result); // Also negate if (!char.IsWhiteSpace(input[0])) { input = ("-" + inputString).AsReadOnlySpan(); expected = -expected; Assert.Equal(expected, TimeSpan.Parse(input, provider)); Assert.True(TimeSpan.TryParse(input, provider, out result)); Assert.Equal(expected, result); } } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Span_Invalid(string inputString, IFormatProvider provider, Type exceptionType) { if (inputString != null) { Assert.Throws(exceptionType, () => TimeSpan.Parse(inputString.AsReadOnlySpan(), provider)); Assert.False(TimeSpan.TryParse(inputString.AsReadOnlySpan(), provider, out TimeSpan result)); Assert.Equal(TimeSpan.Zero, result); } } [Theory] [MemberData(nameof(ParseExact_Valid_TestData))] public static void ParseExact_Span_Valid(string inputString, string format, TimeSpan expected) { ReadOnlySpan<char> input = inputString.AsReadOnlySpan(); TimeSpan result; Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US"))); Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US"))); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result)); Assert.Equal(expected, result); Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result)); Assert.Equal(expected, result); if (format != "c" && format != "t" && format != "T" && format != "g" && format != "G") { // TimeSpanStyles is interpreted only for custom formats Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative)); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result)); Assert.Equal(expected.Negate(), result); } else { // Inputs that can be parsed in standard formats with ParseExact should also be parsable with Parse Assert.Equal(expected, TimeSpan.Parse(input, CultureInfo.InvariantCulture)); Assert.True(TimeSpan.TryParse(input, CultureInfo.InvariantCulture, out result)); Assert.Equal(expected, result); } } [Theory] [MemberData(nameof(ParseExact_Invalid_TestData))] public static void ParseExactTest__Span_Invalid(string inputString, string format, Type exceptionType) { if (inputString != null) { Assert.Throws(exceptionType, () => TimeSpan.ParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US"))); TimeSpan result; Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US"), out result)); Assert.Equal(TimeSpan.Zero, result); Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), new[] { format }, new CultureInfo("en-US"), out result)); Assert.Equal(TimeSpan.Zero, result); } } [Fact] public static void ParseExactMultiple_Span_InvalidNullEmptyFormats() { TimeSpan result; AssertExtensions.Throws<ArgumentNullException>("formats", () => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null)); Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null, out result)); Assert.Throws<FormatException>(() => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), new string[0], null)); Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), new string[0], null, out result)); } [Theory] [MemberData(nameof(ToString_MemberData))] public static void TryFormat_Valid(TimeSpan input, string format, string expected) { int charsWritten; Span<char> dst; dst = new char[expected.Length - 1]; Assert.False(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture)); Assert.Equal(0, charsWritten); dst = new char[expected.Length]; Assert.True(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(dst)); dst = new char[expected.Length + 1]; Assert.True(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(dst.Slice(0, dst.Length - 1))); Assert.Equal(0, dst[dst.Length - 1]); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using ExcelDataReader.Portable.Async; using ExcelDataReader.Portable.Core; using ExcelDataReader.Portable.Core.BinaryFormat; using ExcelDataReader.Portable.Data; using ExcelDataReader.Portable.Exceptions; using ExcelDataReader.Portable.Log; using ExcelDataReader.Portable.Misc; namespace ExcelDataReader.Portable { /// <summary> /// ExcelDataReader Class /// </summary> public class ExcelBinaryReader : IExcelDataReader { #region Members private Stream m_file; private XlsHeader m_hdr; private List<XlsWorksheet> m_sheets; private XlsBiffStream m_stream; //private DataSet m_workbookData; private XlsWorkbookGlobals m_globals; private ushort m_version; private Encoding m_encoding; private bool m_isValid; private bool m_isClosed; private readonly Encoding m_Default_Encoding = Encoding.Unicode; private string m_exceptionMessage; private object[] m_cellsValues; private uint[] m_dbCellAddrs; private int m_dbCellAddrsIndex; private bool m_canRead; private int m_SheetIndex; private int m_depth; private int m_cellOffset; private int m_maxCol; private int m_maxRow; private bool m_noIndex; private XlsBiffRow m_currentRowRecord; private ReadOption readOption = ReadOption.Strict; private bool m_IsFirstRead; private const string WORKBOOK = "Workbook"; private const string BOOK = "Book"; private const string COLUMN = "Column"; private bool disposed; private readonly IDataHelper dataHelper; private bool convertOaDate = true; #endregion public ExcelBinaryReader(IDataHelper dataHelper) { this.dataHelper = dataHelper; m_encoding = m_Default_Encoding; m_version = 0x0600; m_isValid = true; m_SheetIndex = -1; m_IsFirstRead = true; } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { //if (m_workbookData != null) m_workbookData.Dispose(); if (m_sheets != null) m_sheets.Clear(); } //m_workbookData = null; m_sheets = null; m_stream = null; m_globals = null; m_encoding = null; m_hdr = null; disposed = true; } } ~ExcelBinaryReader() { Dispose(false); } #endregion #region Private methods private int findFirstDataCellOffset(int startOffset) { //seek to the first dbcell record var record = m_stream.ReadAt(startOffset); while (!(record is XlsBiffDbCell)) { if (m_stream.Position >= m_stream.Size) return -1; if (record is XlsBiffEOF) return -1; record = m_stream.Read(); } XlsBiffDbCell startCell = (XlsBiffDbCell)record; XlsBiffRow row = null; int offs = startCell.RowAddress; do { row = m_stream.ReadAt(offs) as XlsBiffRow; if (row == null) break; offs += row.Size; } while (null != row); return offs; } private void readWorkBookGlobals() { //Read Header try { m_hdr = XlsHeader.ReadHeader(m_file); } catch (HeaderException ex) { fail(ex.Message); return; } catch (FormatException ex) { fail(ex.Message); return; } XlsRootDirectory dir = new XlsRootDirectory(m_hdr); XlsDirectoryEntry workbookEntry = dir.FindEntry(WORKBOOK) ?? dir.FindEntry(BOOK); if (workbookEntry == null) { fail(Errors.ErrorStreamWorkbookNotFound); return; } if (workbookEntry.EntryType != STGTY.STGTY_STREAM) { fail(Errors.ErrorWorkbookIsNotStream); return; } m_stream = new XlsBiffStream(m_hdr, workbookEntry.StreamFirstSector, workbookEntry.IsEntryMiniStream, dir, this); m_globals = new XlsWorkbookGlobals(); m_stream.Seek(0, SeekOrigin.Begin); XlsBiffRecord rec = m_stream.Read(); XlsBiffBOF bof = rec as XlsBiffBOF; if (bof == null || bof.Type != BIFFTYPE.WorkbookGlobals) { fail(Errors.ErrorWorkbookGlobalsInvalidData); return; } bool sst = false; m_version = bof.Version; m_sheets = new List<XlsWorksheet>(); while (null != (rec = m_stream.Read())) { switch (rec.ID) { case BIFFRECORDTYPE.INTERFACEHDR: m_globals.InterfaceHdr = (XlsBiffInterfaceHdr)rec; break; case BIFFRECORDTYPE.BOUNDSHEET: XlsBiffBoundSheet sheet = (XlsBiffBoundSheet)rec; if (sheet.Type != XlsBiffBoundSheet.SheetType.Worksheet) break; sheet.IsV8 = isV8(); //sheet.UseEncoding = Encoding; this.Log().Debug("BOUNDSHEET IsV8={0}", sheet.IsV8); m_sheets.Add(new XlsWorksheet(m_globals.Sheets.Count, sheet)); m_globals.Sheets.Add(sheet); break; case BIFFRECORDTYPE.MMS: m_globals.MMS = rec; break; case BIFFRECORDTYPE.COUNTRY: m_globals.Country = rec; break; case BIFFRECORDTYPE.CODEPAGE: m_globals.CodePage = (XlsBiffSimpleValueRecord)rec; //set encoding based on code page name //PCL does not supported codepage numbers if (m_globals.CodePage.Value == 1200) m_encoding = EncodingHelper.GetEncoding(65001); else m_encoding = EncodingHelper.GetEncoding(m_globals.CodePage.Value); //note: the format spec states that for BIFF8 this is always UTF-16. //as PCL does not supported codepage numbers, it is best to assume UTF-16 for encoding //try //{ // m_encoding = Encoding.GetEncoding(m_globals.CodePage.Value); //} //catch (ArgumentException) //{ // // Warning - Password protection //} break; case BIFFRECORDTYPE.FONT: case BIFFRECORDTYPE.FONT_V34: m_globals.Fonts.Add(rec); break; case BIFFRECORDTYPE.FORMAT_V23: { var fmt = (XlsBiffFormatString) rec; //fmt.UseEncoding = m_encoding; m_globals.Formats.Add((ushort) m_globals.Formats.Count, fmt); } break; case BIFFRECORDTYPE.FORMAT: { var fmt = (XlsBiffFormatString) rec; m_globals.Formats.Add(fmt.Index, fmt); } break; case BIFFRECORDTYPE.XF: case BIFFRECORDTYPE.XF_V4: case BIFFRECORDTYPE.XF_V3: case BIFFRECORDTYPE.XF_V2: m_globals.ExtendedFormats.Add(rec); break; case BIFFRECORDTYPE.SST: m_globals.SST = (XlsBiffSST)rec; sst = true; break; case BIFFRECORDTYPE.CONTINUE: if (!sst) break; XlsBiffContinue contSST = (XlsBiffContinue)rec; m_globals.SST.Append(contSST); break; case BIFFRECORDTYPE.EXTSST: m_globals.ExtSST = rec; sst = false; break; case BIFFRECORDTYPE.PROTECT: case BIFFRECORDTYPE.PASSWORD: case BIFFRECORDTYPE.PROT4REVPASSWORD: //IsProtected break; case BIFFRECORDTYPE.EOF: if (m_globals.SST != null) m_globals.SST.ReadStrings(); return; default: continue; } } } private bool readWorkSheetGlobals(XlsWorksheet sheet, out XlsBiffIndex idx, out XlsBiffRow row) { idx = null; row = null; m_stream.Seek((int)sheet.DataOffset, SeekOrigin.Begin); XlsBiffBOF bof = m_stream.Read() as XlsBiffBOF; if (bof == null || bof.Type != BIFFTYPE.Worksheet) return false; //DumpBiffRecords(); XlsBiffRecord rec = m_stream.Read(); if (rec == null) return false; if (rec is XlsBiffIndex) { idx = rec as XlsBiffIndex; } else if (rec is XlsBiffUncalced) { // Sometimes this come before the index... idx = m_stream.Read() as XlsBiffIndex; } //if (null == idx) //{ // // There is a record before the index! Chech his type and see the MS Biff Documentation // return false; //} if (idx != null) { idx.IsV8 = isV8(); this.Log().Debug("INDEX IsV8={0}", idx.IsV8); } XlsBiffRecord trec; XlsBiffDimensions dims = null; do { trec = m_stream.Read(); if (trec.ID == BIFFRECORDTYPE.DIMENSIONS) { dims = (XlsBiffDimensions)trec; break; } } while (trec != null && trec.ID != BIFFRECORDTYPE.ROW); //if we are already on row record then set that as the row, otherwise step forward till we get to a row record if (trec.ID == BIFFRECORDTYPE.ROW) row = (XlsBiffRow)trec; XlsBiffRow rowRecord = null; while (rowRecord == null) { if (m_stream.Position >= m_stream.Size) break; var thisRec = m_stream.Read(); this.Log().Debug("finding rowRecord offset {0}, rec: {1}", thisRec.Offset, thisRec.ID); if (thisRec is XlsBiffEOF) break; rowRecord = thisRec as XlsBiffRow; } if (rowRecord != null) this.Log().Debug("Got row {0}, rec: id={1},rowindex={2}, rowColumnStart={3}, rowColumnEnd={4}", rowRecord.Offset, rowRecord.ID, rowRecord.RowIndex, rowRecord.FirstDefinedColumn, rowRecord.LastDefinedColumn); row = rowRecord; if (dims != null) { dims.IsV8 = isV8(); this.Log().Debug("dims IsV8={0}", dims.IsV8); m_maxCol = dims.LastColumn - 1; //handle case where sheet reports last column is 1 but there are actually more if (m_maxCol <= 0 && rowRecord != null) { m_maxCol = rowRecord.LastDefinedColumn; } m_maxRow = (int)dims.LastRow; sheet.Dimensions = dims; } else { m_maxCol = 256; m_maxRow = (int)idx.LastExistingRow; } if (idx != null && idx.LastExistingRow <= idx.FirstExistingRow) { return false; } else if (row == null) { return false; } m_depth = 0; return true; } private void DumpBiffRecords() { XlsBiffRecord rec = null; var startPos = m_stream.Position; do { rec = m_stream.Read(); this.Log().Debug(rec.ID.ToString()); } while (rec != null && m_stream.Position < m_stream.Size); m_stream.Seek(startPos, SeekOrigin.Begin); } private bool readWorkSheetRow() { m_cellsValues = new object[m_maxCol]; while (m_cellOffset < m_stream.Size) { XlsBiffRecord rec = m_stream.ReadAt(m_cellOffset); m_cellOffset += rec.Size; if ((rec is XlsBiffDbCell) || (rec is XlsBiffMSODrawing)) { break; }; if (rec is XlsBiffEOF) { return false; }; XlsBiffBlankCell cell = rec as XlsBiffBlankCell; if ((null == cell) || (cell.ColumnIndex >= m_maxCol)) continue; if (cell.RowIndex != m_depth) { m_cellOffset -= rec.Size; break; }; pushCellValue(cell); } m_depth++; return m_depth < m_maxRow; } private void pushCellValue(XlsBiffBlankCell cell) { double _dValue; this.Log().Debug("pushCellValue {0}", cell.ID); switch (cell.ID) { case BIFFRECORDTYPE.BOOLERR: if (cell.ReadByte(7) == 0) m_cellsValues[cell.ColumnIndex] = cell.ReadByte(6) != 0; break; case BIFFRECORDTYPE.BOOLERR_OLD: if (cell.ReadByte(8) == 0) m_cellsValues[cell.ColumnIndex] = cell.ReadByte(7) != 0; break; case BIFFRECORDTYPE.INTEGER: case BIFFRECORDTYPE.INTEGER_OLD: m_cellsValues[cell.ColumnIndex] = ((XlsBiffIntegerCell)cell).Value; break; case BIFFRECORDTYPE.NUMBER: case BIFFRECORDTYPE.NUMBER_OLD: _dValue = ((XlsBiffNumberCell)cell).Value; m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ? _dValue : tryConvertOADateTime(_dValue, cell.XFormat); this.Log().Debug("VALUE: {0}", _dValue); break; case BIFFRECORDTYPE.LABEL: case BIFFRECORDTYPE.LABEL_OLD: case BIFFRECORDTYPE.RSTRING: m_cellsValues[cell.ColumnIndex] = ((XlsBiffLabelCell)cell).Value; this.Log().Debug("VALUE: {0}", m_cellsValues[cell.ColumnIndex]); break; case BIFFRECORDTYPE.LABELSST: string tmp = m_globals.SST.GetString(((XlsBiffLabelSSTCell)cell).SSTIndex); this.Log().Debug("VALUE: {0}", tmp); m_cellsValues[cell.ColumnIndex] = tmp; break; case BIFFRECORDTYPE.RK: _dValue = ((XlsBiffRKCell)cell).Value; m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ? _dValue : tryConvertOADateTime(_dValue, cell.XFormat); this.Log().Debug("VALUE: {0}", _dValue); break; case BIFFRECORDTYPE.MULRK: XlsBiffMulRKCell _rkCell = (XlsBiffMulRKCell)cell; for (ushort j = cell.ColumnIndex; j <= _rkCell.LastColumnIndex; j++) { _dValue = _rkCell.GetValue(j); this.Log().Debug("VALUE[{1}]: {0}", _dValue, j); m_cellsValues[j] = !ConvertOaDate ? _dValue : tryConvertOADateTime(_dValue, _rkCell.GetXF(j)); } break; case BIFFRECORDTYPE.BLANK: case BIFFRECORDTYPE.BLANK_OLD: case BIFFRECORDTYPE.MULBLANK: // Skip blank cells break; case BIFFRECORDTYPE.FORMULA: case BIFFRECORDTYPE.FORMULA_OLD: object _oValue = ((XlsBiffFormulaCell)cell).Value; if (null != _oValue && _oValue is FORMULAERROR) { _oValue = null; } else { m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ? _oValue : tryConvertOADateTime(_oValue, (ushort)(cell.XFormat));//date time offset } this.Log().Debug("VALUE: {0}", _oValue); break; default: break; } } private bool moveToNextRecord() { //if sheet has no index if (m_noIndex) { this.Log().Debug("No index"); return moveToNextRecordNoIndex(); } //if sheet has index if (null == m_dbCellAddrs || m_dbCellAddrsIndex == m_dbCellAddrs.Length || m_depth == m_maxRow) return false; m_canRead = readWorkSheetRow(); //read last row if (!m_canRead && m_depth > 0) m_canRead = true; if (!m_canRead && m_dbCellAddrsIndex < (m_dbCellAddrs.Length - 1)) { m_dbCellAddrsIndex++; m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]); if (m_cellOffset < 0) return false; m_canRead = readWorkSheetRow(); } return m_canRead; } private bool moveToNextRecordNoIndex() { //seek from current row record to start of cell data where that cell relates to the next row record XlsBiffRow rowRecord = m_currentRowRecord; if (rowRecord == null) return false; if (rowRecord.RowIndex < m_depth) { m_stream.Seek(rowRecord.Offset + rowRecord.Size, SeekOrigin.Begin); do { if (m_stream.Position >= m_stream.Size) return false; var record = m_stream.Read(); if (record is XlsBiffEOF) return false; rowRecord = record as XlsBiffRow; } while (rowRecord == null || rowRecord.RowIndex < m_depth); } m_currentRowRecord = rowRecord; //m_depth = m_currentRowRecord.RowIndex; //we have now found the row record for the new row, the we need to seek forward to the first cell record XlsBiffBlankCell cell = null; do { if (m_stream.Position >= m_stream.Size) return false; var record = m_stream.Read(); if (record is XlsBiffEOF) return false; if (record.IsCell) { var candidateCell = record as XlsBiffBlankCell; if (candidateCell != null) { if (candidateCell.RowIndex == m_currentRowRecord.RowIndex) cell = candidateCell; } } } while (cell == null); m_cellOffset = cell.Offset; m_canRead = readWorkSheetRow(); //read last row //if (!m_canRead && m_depth > 0) m_canRead = true; //if (!m_canRead && m_dbCellAddrsIndex < (m_dbCellAddrs.Length - 1)) //{ // m_dbCellAddrsIndex++; // m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]); // m_canRead = readWorkSheetRow(); //} return m_canRead; } private void initializeSheetRead() { if (m_SheetIndex == ResultsCount) return; m_dbCellAddrs = null; m_IsFirstRead = false; if (m_SheetIndex == -1) m_SheetIndex = 0; XlsBiffIndex idx; if (!readWorkSheetGlobals(m_sheets[m_SheetIndex], out idx, out m_currentRowRecord)) { //read next sheet m_SheetIndex++; initializeSheetRead(); return; }; if (idx == null) { //no index, but should have the first row record m_noIndex = true; } else { m_dbCellAddrs = idx.DbCellAddresses; m_dbCellAddrsIndex = 0; m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]); if (m_cellOffset < 0) { fail("Badly formed binary file. Has INDEX but no DBCELL"); return; } } } private void fail(string message) { m_exceptionMessage = message; m_isValid = false; m_file.Dispose(); m_isClosed = true; m_sheets = null; m_stream = null; m_globals = null; m_encoding = null; m_hdr = null; } private object tryConvertOADateTime(double value, ushort XFormat) { ushort format = 0; if (XFormat >= 0 && XFormat < m_globals.ExtendedFormats.Count) { var rec = m_globals.ExtendedFormats[XFormat]; switch (rec.ID) { case BIFFRECORDTYPE.XF_V2: format = (ushort) (rec.ReadByte(2) & 0x3F); break; case BIFFRECORDTYPE.XF_V3: if ((rec.ReadByte(3) & 4) == 0) return value; format = rec.ReadByte(1); break; case BIFFRECORDTYPE.XF_V4: if ((rec.ReadByte(5) & 4) == 0) return value; format = rec.ReadByte(1); break; default: if ((rec.ReadByte(m_globals.Sheets[m_globals.Sheets.Count-1].IsV8 ? 9 : 7) & 4) == 0) return value; format = rec.ReadUInt16(2); break; } } else { format = XFormat; } switch (format) { // numeric built in formats case 0: //"General"; case 1: //"0"; case 2: //"0.00"; case 3: //"#,##0"; case 4: //"#,##0.00"; case 5: //"\"$\"#,##0_);(\"$\"#,##0)"; case 6: //"\"$\"#,##0_);[Red](\"$\"#,##0)"; case 7: //"\"$\"#,##0.00_);(\"$\"#,##0.00)"; case 8: //"\"$\"#,##0.00_);[Red](\"$\"#,##0.00)"; case 9: //"0%"; case 10: //"0.00%"; case 11: //"0.00E+00"; case 12: //"# ?/?"; case 13: //"# ??/??"; case 0x30:// "##0.0E+0"; case 0x25:// "_(#,##0_);(#,##0)"; case 0x26:// "_(#,##0_);[Red](#,##0)"; case 0x27:// "_(#,##0.00_);(#,##0.00)"; case 40:// "_(#,##0.00_);[Red](#,##0.00)"; case 0x29:// "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)"; case 0x2a:// "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)"; case 0x2b:// "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)"; case 0x2c:// "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)"; return value; // date formats case 14: //this.GetDefaultDateFormat(); case 15: //"D-MM-YY"; case 0x10: // "D-MMM"; case 0x11: // "MMM-YY"; case 0x12: // "h:mm AM/PM"; case 0x13: // "h:mm:ss AM/PM"; case 20: // "h:mm"; case 0x15: // "h:mm:ss"; case 0x16: // string.Format("{0} {1}", this.GetDefaultDateFormat(), this.GetDefaultTimeFormat()); case 0x2d: // "mm:ss"; case 0x2e: // "[h]:mm:ss"; case 0x2f: // "mm:ss.0"; return Helpers.ConvertFromOATime(value); case 0x31:// "@"; return value.ToString(); default: XlsBiffFormatString fmtString; if (m_globals.Formats.TryGetValue(format, out fmtString) ) { var fmt = fmtString.Value; var formatReader = new FormatReader() {FormatString = fmt}; if (formatReader.IsDateFormatString()) return Helpers.ConvertFromOATime(value); } return value; } } private object tryConvertOADateTime(object value, ushort XFormat) { double _dValue; if (double.TryParse(value.ToString(), out _dValue)) return tryConvertOADateTime(_dValue, XFormat); return value; } public bool isV8() { return m_version >= 0x600; } #endregion #region IExcelDataReader Members public async Task InitializeAsync(Stream fileStream) { m_file = fileStream; await Task.Run(() => readWorkBookGlobals()); // set the sheet index to the index of the first sheet.. this is so that properties such as Name which use m_sheetIndex reflect the first sheet in the file without having to perform a read() operation m_SheetIndex = 0; } //public DataSet AsDataSet() //{ // return AsDataSet(false); //} //public DataSet AsDataSet(bool convertOADateTime) //{ // if (!m_isValid) return null; // if (m_isClosed) return m_workbookData; // ConvertOaDate = convertOADateTime; // m_workbookData = new DataSet(); // for (int index = 0; index < ResultsCount; index++) // { // DataTable table = readWholeWorkSheet(m_sheets[index]); // if (null != table) // m_workbookData.Tables.Add(table); // } // m_file.Close(); // m_isClosed = true; // m_workbookData.AcceptChanges(); // Helpers.FixDataTypes(m_workbookData); // return m_workbookData; //} public string ExceptionMessage { get { return m_exceptionMessage; } } public string Name { get { if (null != m_sheets && m_sheets.Count > 0) return m_sheets[m_SheetIndex].Name; else return null; } } public string VisibleState { get { if (null != m_sheets && m_sheets.Count > 0) return m_sheets[m_SheetIndex].VisibleState; else return null; } } public bool IsValid { get { return m_isValid; } } public void Close() { m_file.Dispose(); m_isClosed = true; } public int Depth { get { return m_depth; } } public int ResultsCount { get { return m_globals.Sheets.Count; } } public bool IsClosed { get { return m_isClosed; } } public bool NextResult() { if (m_SheetIndex >= (this.ResultsCount - 1)) return false; m_SheetIndex++; m_IsFirstRead = true; return true; } public bool Read() { if (!m_isValid) return false; if (m_IsFirstRead) initializeSheetRead(); return moveToNextRecord(); } public int FieldCount { get { return m_maxCol; } } public bool GetBoolean(int i) { if (IsDBNull(i)) return false; return Boolean.Parse(m_cellsValues[i].ToString()); } public DateTime GetDateTime(int i) { if (IsDBNull(i)) return DateTime.MinValue; // requested change: 3 object val = m_cellsValues[i]; if (val is DateTime) { // if the value is already a datetime.. return it without further conversion return (DateTime)val; } // otherwise proceed with conversion attempts string valString = val.ToString(); double dVal; try { dVal = double.Parse(valString); } catch (FormatException) { return DateTime.Parse(valString); } return DateTimeHelper.FromOADate(dVal); } public decimal GetDecimal(int i) { if (IsDBNull(i)) return decimal.MinValue; return decimal.Parse(m_cellsValues[i].ToString()); } public double GetDouble(int i) { if (IsDBNull(i)) return double.MinValue; return double.Parse(m_cellsValues[i].ToString()); } public float GetFloat(int i) { if (IsDBNull(i)) return float.MinValue; return float.Parse(m_cellsValues[i].ToString()); } public short GetInt16(int i) { if (IsDBNull(i)) return short.MinValue; return short.Parse(m_cellsValues[i].ToString()); } public int GetInt32(int i) { if (IsDBNull(i)) return int.MinValue; return int.Parse(m_cellsValues[i].ToString()); } public long GetInt64(int i) { if (IsDBNull(i)) return long.MinValue; return long.Parse(m_cellsValues[i].ToString()); } public string GetString(int i) { if (IsDBNull(i)) return null; return m_cellsValues[i].ToString(); } public object GetValue(int i) { return m_cellsValues[i]; } public bool IsDBNull(int i) { return (null == m_cellsValues[i]) || (dataHelper.IsDBNull(m_cellsValues[i])); } public object this[int i] { get { return m_cellsValues[i]; } } #endregion #region Not Supported IDataReader Members //public DataTable GetSchemaTable() //{ // throw new NotSupportedException(); //} public int RecordsAffected { get { throw new NotSupportedException(); } } #endregion #region Not Supported IDataRecord Members public byte GetByte(int i) { throw new NotSupportedException(); } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } public char GetChar(int i) { throw new NotSupportedException(); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } //public IDataReader GetData(int i) //{ // throw new NotSupportedException(); //} public string GetDataTypeName(int i) { throw new NotSupportedException(); } public Type GetFieldType(int i) { throw new NotSupportedException(); } public Guid GetGuid(int i) { throw new NotSupportedException(); } public string GetName(int i) { throw new NotSupportedException(); } public int GetOrdinal(string name) { throw new NotSupportedException(); } public int GetValues(object[] values) { throw new NotSupportedException(); } public object this[string name] { get { throw new NotSupportedException(); } } #endregion #region IExcelDataReader Members public bool IsFirstRowAsColumnNames { get; set; } public bool ConvertOaDate { get { return convertOaDate; } set { convertOaDate = value; } } public ReadOption ReadOption { get { return readOption; } set { readOption = value; } } public Encoding Encoding { get { return m_encoding; } } public Encoding DefaultEncoding { get { return Encoding.UTF8; } } #endregion #region Dataset public async Task LoadDataSetAsync(IDatasetHelper datasetHelper) { await LoadDataSetAsync(datasetHelper, false); } public async Task LoadDataSetAsync(IDatasetHelper datasetHelper, bool convertOADateTime) { if (!m_isValid) { datasetHelper.IsValid = false; } datasetHelper.IsValid = true; if (m_isClosed) { await Task.FromResult(0); } ConvertOaDate = convertOADateTime; datasetHelper.CreateNew(); //m_workbookData = new DataSet(); await Task.Run(() => readAllSheets(datasetHelper)); m_file.Dispose(); m_isClosed = true; datasetHelper.DatasetLoadComplete(); } private void readAllSheets(IDatasetHelper datasetHelper) { for (int index = 0; index < ResultsCount; index++) { readWholeWorkSheet(m_sheets[index], datasetHelper); } } private void readWholeWorkSheet(XlsWorksheet sheet, IDatasetHelper datasetHelper) { XlsBiffIndex idx; if (!readWorkSheetGlobals(sheet, out idx, out m_currentRowRecord)) { datasetHelper.IsValid = false; return; } //DataTable table = new DataTable(sheet.Name); datasetHelper.CreateNewTable(sheet.Name); datasetHelper.AddExtendedPropertyToTable("visiblestate", sheet.VisibleState); bool triggerCreateColumns = true; if (idx != null) readWholeWorkSheetWithIndex(idx, triggerCreateColumns, datasetHelper); else readWholeWorkSheetNoIndex(triggerCreateColumns, datasetHelper); datasetHelper.EndLoadTable(); } //TODO: quite a bit of duplication with the noindex version private void readWholeWorkSheetWithIndex(XlsBiffIndex idx, bool triggerCreateColumns, IDatasetHelper datasetHelper) { m_dbCellAddrs = idx.DbCellAddresses; for (int index = 0; index < m_dbCellAddrs.Length; index++) { if (m_depth == m_maxRow) break; // init reading data m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[index]); if (m_cellOffset < 0) return; //DataTable columns if (triggerCreateColumns) { if (IsFirstRowAsColumnNames && readWorkSheetRow() || (IsFirstRowAsColumnNames && m_maxRow == 1)) { for (int i = 0; i < m_maxCol; i++) { if (m_cellsValues[i] != null && m_cellsValues[i].ToString().Length > 0) datasetHelper.AddColumn(m_cellsValues[i].ToString()); else datasetHelper.AddColumn(string.Concat(COLUMN, i)); } } else { for (int i = 0; i < m_maxCol; i++) { datasetHelper.AddColumn(null); } } triggerCreateColumns = false; datasetHelper.BeginLoadData(); //table.BeginLoadData(); } while (readWorkSheetRow()) { datasetHelper.AddRow(m_cellsValues); } //add the row if (m_depth > 0 && !(IsFirstRowAsColumnNames && m_maxRow == 1)) { datasetHelper.AddRow(m_cellsValues); } } } private void readWholeWorkSheetNoIndex(bool triggerCreateColumns, IDatasetHelper datasetHelper) { while (Read()) { if (m_depth == m_maxRow) break; bool justAddedColumns = false; //DataTable columns if (triggerCreateColumns) { if (IsFirstRowAsColumnNames || (IsFirstRowAsColumnNames && m_maxRow == 1)) { for (int i = 0; i < m_maxCol; i++) { if (m_cellsValues[i] != null && m_cellsValues[i].ToString().Length > 0) datasetHelper.AddColumn(m_cellsValues[i].ToString()); else datasetHelper.AddColumn(string.Concat(COLUMN, i)); } justAddedColumns = true; } else { for (int i = 0; i < m_maxCol; i++) { datasetHelper.AddColumn(null); } } triggerCreateColumns = false; datasetHelper.BeginLoadData(); } if (!justAddedColumns && m_depth > 0 && !(IsFirstRowAsColumnNames && m_maxRow == 1)) { datasetHelper.AddRow(m_cellsValues); } } if (m_depth > 0 && !(IsFirstRowAsColumnNames && m_maxRow == 1)) { datasetHelper.AddRow(m_cellsValues); } } #endregion } internal class EncodingHelper { public static Encoding GetEncoding(ushort codePage) { var encoding = (Encoding)null; switch (codePage) { case 037: encoding = Encoding.GetEncoding("IBM037"); break; case 437: encoding = Encoding.GetEncoding("IBM437"); break; case 500: encoding = Encoding.GetEncoding("IBM500"); break; case 708: encoding = Encoding.GetEncoding("ASMO-708"); break; case 709: encoding = Encoding.GetEncoding(""); break; case 710: encoding = Encoding.GetEncoding(""); break; case 720: encoding = Encoding.GetEncoding("DOS-720"); break; case 737: encoding = Encoding.GetEncoding("ibm737"); break; case 775: encoding = Encoding.GetEncoding("ibm775"); break; case 850: encoding = Encoding.GetEncoding("ibm850"); break; case 852: encoding = Encoding.GetEncoding("ibm852"); break; case 855: encoding = Encoding.GetEncoding("IBM855"); break; case 857: encoding = Encoding.GetEncoding("ibm857"); break; case 858: encoding = Encoding.GetEncoding("IBM00858"); break; case 860: encoding = Encoding.GetEncoding("IBM860"); break; case 861: encoding = Encoding.GetEncoding("ibm861"); break; case 862: encoding = Encoding.GetEncoding("DOS-862"); break; case 863: encoding = Encoding.GetEncoding("IBM863"); break; case 864: encoding = Encoding.GetEncoding("IBM864"); break; case 865: encoding = Encoding.GetEncoding("IBM865"); break; case 866: encoding = Encoding.GetEncoding("cp866"); break; case 869: encoding = Encoding.GetEncoding("ibm869"); break; case 870: encoding = Encoding.GetEncoding("IBM870"); break; case 874: encoding = Encoding.GetEncoding("windows-874"); break; case 875: encoding = Encoding.GetEncoding("cp875"); break; case 932: encoding = Encoding.GetEncoding("shift_jis"); break; case 936: encoding = Encoding.GetEncoding("gb2312"); break; case 949: encoding = Encoding.GetEncoding("ks_c_5601-1987"); break; case 950: encoding = Encoding.GetEncoding("big5"); break; case 1026: encoding = Encoding.GetEncoding("IBM1026"); break; case 1047: encoding = Encoding.GetEncoding("IBM01047"); break; case 1140: encoding = Encoding.GetEncoding("IBM01140"); break; case 1141: encoding = Encoding.GetEncoding("IBM01141"); break; case 1142: encoding = Encoding.GetEncoding("IBM01142"); break; case 1143: encoding = Encoding.GetEncoding("IBM01143"); break; case 1144: encoding = Encoding.GetEncoding("IBM01144"); break; case 1145: encoding = Encoding.GetEncoding("IBM01145"); break; case 1146: encoding = Encoding.GetEncoding("IBM01146"); break; case 1147: encoding = Encoding.GetEncoding("IBM01147"); break; case 1148: encoding = Encoding.GetEncoding("IBM01148"); break; case 1149: encoding = Encoding.GetEncoding("IBM01149"); break; case 1200: encoding = Encoding.GetEncoding("utf-16"); break; case 1201: encoding = Encoding.GetEncoding("unicodeFFFE"); break; case 1250: encoding = Encoding.GetEncoding("windows-1250"); break; case 1251: encoding = Encoding.GetEncoding("windows-1251"); break; case 1252: encoding = Encoding.GetEncoding("windows-1252"); break; case 1253: encoding = Encoding.GetEncoding("windows-1253"); break; case 1254: encoding = Encoding.GetEncoding("windows-1254"); break; case 1255: encoding = Encoding.GetEncoding("windows-1255"); break; case 1256: encoding = Encoding.GetEncoding("windows-1256"); break; case 1257: encoding = Encoding.GetEncoding("windows-1257"); break; case 1258: encoding = Encoding.GetEncoding("windows-1258"); break; case 1361: encoding = Encoding.GetEncoding("Johab"); break; case 10000: encoding = Encoding.GetEncoding("macintosh"); break; case 10001: encoding = Encoding.GetEncoding("x-mac-japanese"); break; case 10002: encoding = Encoding.GetEncoding("x-mac-chinesetrad"); break; case 10003: encoding = Encoding.GetEncoding("x-mac-korean"); break; case 10004: encoding = Encoding.GetEncoding("x-mac-arabic"); break; case 10005: encoding = Encoding.GetEncoding("x-mac-hebrew"); break; case 10006: encoding = Encoding.GetEncoding("x-mac-greek"); break; case 10007: encoding = Encoding.GetEncoding("x-mac-cyrillic"); break; case 10008: encoding = Encoding.GetEncoding("x-mac-chinesesimp"); break; case 10010: encoding = Encoding.GetEncoding("x-mac-romanian"); break; case 10017: encoding = Encoding.GetEncoding("x-mac-ukrainian"); break; case 10021: encoding = Encoding.GetEncoding("x-mac-thai"); break; case 10029: encoding = Encoding.GetEncoding("x-mac-ce"); break; case 10079: encoding = Encoding.GetEncoding("x-mac-icelandic"); break; case 10081: encoding = Encoding.GetEncoding("x-mac-turkish"); break; case 10082: encoding = Encoding.GetEncoding("x-mac-croatian"); break; case 12000: encoding = Encoding.GetEncoding("utf-32"); break; case 12001: encoding = Encoding.GetEncoding("utf-32BE"); break; case 20000: encoding = Encoding.GetEncoding("x-Chinese_CNS"); break; case 20001: encoding = Encoding.GetEncoding("x-cp20001"); break; case 20002: encoding = Encoding.GetEncoding("x_Chinese-Eten"); break; case 20003: encoding = Encoding.GetEncoding("x-cp20003"); break; case 20004: encoding = Encoding.GetEncoding("x-cp20004"); break; case 20005: encoding = Encoding.GetEncoding("x-cp20005"); break; case 20105: encoding = Encoding.GetEncoding("x-IA5"); break; case 20106: encoding = Encoding.GetEncoding("x-IA5-German"); break; case 20107: encoding = Encoding.GetEncoding("x-IA5-Swedish"); break; case 20108: encoding = Encoding.GetEncoding("x-IA5-Norwegian"); break; case 20127: encoding = Encoding.GetEncoding("us-ascii"); break; case 20261: encoding = Encoding.GetEncoding("x-cp20261"); break; case 20269: encoding = Encoding.GetEncoding("x-cp20269"); break; case 20273: encoding = Encoding.GetEncoding("IBM273"); break; case 20277: encoding = Encoding.GetEncoding("IBM277"); break; case 20278: encoding = Encoding.GetEncoding("IBM278"); break; case 20280: encoding = Encoding.GetEncoding("IBM280"); break; case 20284: encoding = Encoding.GetEncoding("IBM284"); break; case 20285: encoding = Encoding.GetEncoding("IBM285"); break; case 20290: encoding = Encoding.GetEncoding("IBM290"); break; case 20297: encoding = Encoding.GetEncoding("IBM297"); break; case 20420: encoding = Encoding.GetEncoding("IBM420"); break; case 20423: encoding = Encoding.GetEncoding("IBM423"); break; case 20424: encoding = Encoding.GetEncoding("IBM424"); break; case 20833: encoding = Encoding.GetEncoding("x-EBCDIC-KoreanExtended"); break; case 20838: encoding = Encoding.GetEncoding("IBM-Thai"); break; case 20866: encoding = Encoding.GetEncoding("koi8-r"); break; case 20871: encoding = Encoding.GetEncoding("IBM871"); break; case 20880: encoding = Encoding.GetEncoding("IBM880"); break; case 20905: encoding = Encoding.GetEncoding("IBM905"); break; case 20924: encoding = Encoding.GetEncoding("IBM00924"); break; case 20932: encoding = Encoding.GetEncoding("EUC-JP"); break; case 20936: encoding = Encoding.GetEncoding("x-cp20936"); break; case 20949: encoding = Encoding.GetEncoding("x-cp20949"); break; case 21025: encoding = Encoding.GetEncoding("cp1025"); break; case 21027: encoding = Encoding.GetEncoding(""); break; case 21866: encoding = Encoding.GetEncoding("koi8-u"); break; case 28591: encoding = Encoding.GetEncoding("iso-8859-1"); break; case 28592: encoding = Encoding.GetEncoding("iso-8859-2"); break; case 28593: encoding = Encoding.GetEncoding("iso-8859-3"); break; case 28594: encoding = Encoding.GetEncoding("iso-8859-4"); break; case 28595: encoding = Encoding.GetEncoding("iso-8859-5"); break; case 28596: encoding = Encoding.GetEncoding("iso-8859-6"); break; case 28597: encoding = Encoding.GetEncoding("iso-8859-7"); break; case 28598: encoding = Encoding.GetEncoding("iso-8859-8"); break; case 28599: encoding = Encoding.GetEncoding("iso-8859-9"); break; case 28603: encoding = Encoding.GetEncoding("iso-8859-13"); break; case 28605: encoding = Encoding.GetEncoding("iso-8859-15"); break; case 29001: encoding = Encoding.GetEncoding("x-Europa"); break; case 38598: encoding = Encoding.GetEncoding("iso-8859-8-i"); break; case 50220: encoding = Encoding.GetEncoding("iso-2022-jp"); break; case 50221: encoding = Encoding.GetEncoding("csISO2022JP"); break; case 50222: encoding = Encoding.GetEncoding("iso-2022-jp"); break; case 50225: encoding = Encoding.GetEncoding("iso-2022-kr"); break; case 50227: encoding = Encoding.GetEncoding("x-cp50227"); break; case 50229: encoding = Encoding.GetEncoding(""); break; case 50930: encoding = Encoding.GetEncoding(""); break; case 50931: encoding = Encoding.GetEncoding(""); break; case 50933: encoding = Encoding.GetEncoding(""); break; case 50935: encoding = Encoding.GetEncoding(""); break; case 50936: encoding = Encoding.GetEncoding(""); break; case 50937: encoding = Encoding.GetEncoding(""); break; case 50939: encoding = Encoding.GetEncoding(""); break; case 51932: encoding = Encoding.GetEncoding("euc-jp"); break; case 51936: encoding = Encoding.GetEncoding("EUC-CN"); break; case 51949: encoding = Encoding.GetEncoding("euc-kr"); break; case 51950: encoding = Encoding.GetEncoding(""); break; case 52936: encoding = Encoding.GetEncoding("hz-gb-2312"); break; case 54936: encoding = Encoding.GetEncoding("GB18030"); break; case 57002: encoding = Encoding.GetEncoding("x-iscii-de"); break; case 57003: encoding = Encoding.GetEncoding("x-iscii-be"); break; case 57004: encoding = Encoding.GetEncoding("x-iscii-ta"); break; case 57005: encoding = Encoding.GetEncoding("x-iscii-te"); break; case 57006: encoding = Encoding.GetEncoding("x-iscii-as"); break; case 57007: encoding = Encoding.GetEncoding("x-iscii-or"); break; case 57008: encoding = Encoding.GetEncoding("x-iscii-ka"); break; case 57009: encoding = Encoding.GetEncoding("x-iscii-ma"); break; case 57010: encoding = Encoding.GetEncoding("x-iscii-gu"); break; case 57011: encoding = Encoding.GetEncoding("x-iscii-pa"); break; case 65000: encoding = Encoding.GetEncoding("utf-7"); break; case 65001: encoding = Encoding.GetEncoding("utf-8"); break; } return encoding; } } /// <summary> /// Strict is as normal, Loose is more forgiving and will not cause an exception if a record size takes it beyond the end of the file. It will be trunacted in this case (SQl Reporting Services) /// </summary> public enum ReadOption { Strict, Loose } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: DynamicPropertyReader.cs // // Description: Helper methods to retrive dynami properties from // DependencyObjects. // // History: // 04/25/2003 : [....] - moving from Avalon branch. // //--------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.TextFormatting; using System.Windows.Markup; using MS.Internal.PtsHost; using MS.Internal.Annotations.Component; namespace MS.Internal.Text { // ---------------------------------------------------------------------- // Helper methods to retrive dynami properties from DependencyObjects. // ---------------------------------------------------------------------- internal static class DynamicPropertyReader { // ------------------------------------------------------------------ // // Property Groups // // ------------------------------------------------------------------ #region Property Groups // ------------------------------------------------------------------ // Retrieve typeface properties from specified element. // ------------------------------------------------------------------ internal static Typeface GetTypeface(DependencyObject element) { Debug.Assert(element != null); FontFamily fontFamily = (FontFamily) element.GetValue(TextElement.FontFamilyProperty); FontStyle fontStyle = (FontStyle) element.GetValue(TextElement.FontStyleProperty); FontWeight fontWeight = (FontWeight) element.GetValue(TextElement.FontWeightProperty); FontStretch fontStretch = (FontStretch) element.GetValue(TextElement.FontStretchProperty); return new Typeface(fontFamily, fontStyle, fontWeight, fontStretch); } internal static Typeface GetModifiedTypeface(DependencyObject element, FontFamily fontFamily) { Debug.Assert(element != null); FontStyle fontStyle = (FontStyle) element.GetValue(TextElement.FontStyleProperty); FontWeight fontWeight = (FontWeight) element.GetValue(TextElement.FontWeightProperty); FontStretch fontStretch = (FontStretch) element.GetValue(TextElement.FontStretchProperty); return new Typeface(fontFamily, fontStyle, fontWeight, fontStretch); } // ------------------------------------------------------------------ // Retrieve text properties from specified inline object. // // WORKAROUND: see PS task #13486 & #3399. // For inline object go to its parent and retrieve text decoration // properties from there. // ------------------------------------------------------------------ internal static TextDecorationCollection GetTextDecorationsForInlineObject(DependencyObject element, TextDecorationCollection textDecorations) { Debug.Assert(element != null); DependencyObject parent = LogicalTreeHelper.GetParent(element); TextDecorationCollection parentTextDecorations = null; if (parent != null) { // Get parent text decorations if it is non-null parentTextDecorations = GetTextDecorations(parent); } // see if the two text decorations are equal. bool textDecorationsEqual = (textDecorations == null) ? parentTextDecorations == null : textDecorations.ValueEquals(parentTextDecorations); if (!textDecorationsEqual) { if (parentTextDecorations == null) { textDecorations = null; } else { textDecorations = new TextDecorationCollection(); int count = parentTextDecorations.Count; for (int i = 0; i < count; ++i) { textDecorations.Add(parentTextDecorations[i]); } } } return textDecorations; } /// <summary> /// Helper method to get a TextDecorations property value. It returns null (instead of empty collection) /// when the property is not set on the given DO. /// </summary> internal static TextDecorationCollection GetTextDecorations(DependencyObject element) { return GetCollectionValue(element, Inline.TextDecorationsProperty) as TextDecorationCollection; } /// <summary> /// Helper method to get a TextEffects property value. It returns null (instead of empty collection) /// when the property is not set on the given DO. /// </summary> internal static TextEffectCollection GetTextEffects(DependencyObject element) { return GetCollectionValue(element, TextElement.TextEffectsProperty) as TextEffectCollection; } /// <summary> /// Helper method to get a collection property value. It returns null (instead of empty collection) /// when the property is not set on the given DO. /// </summary> /// <remarks> /// Property system's GetValue() call creates a mutable empty collection when the property is accessed for the first time. /// To avoids workingset overhead of those empty collections, we return null instead. /// </remarks> private static object GetCollectionValue(DependencyObject element, DependencyProperty property) { bool hasModifiers; if (element.GetValueSource(property, null, out hasModifiers) != BaseValueSourceInternal.Default || hasModifiers) { return element.GetValue(property); } return null; } #endregion Property Groups // ------------------------------------------------------------------ // // Block Properties // // ------------------------------------------------------------------ #region Block Properties // ------------------------------------------------------------------ // GetKeepTogether // ------------------------------------------------------------------ internal static bool GetKeepTogether(DependencyObject element) { Paragraph p = element as Paragraph; return (p != null) ? p.KeepTogether : false; } // ------------------------------------------------------------------ // GetKeepWithNext // ------------------------------------------------------------------ internal static bool GetKeepWithNext(DependencyObject element) { Paragraph p = element as Paragraph; return (p != null) ? p.KeepWithNext : false; } // ------------------------------------------------------------------ // GetMinWidowLines // ------------------------------------------------------------------ internal static int GetMinWidowLines(DependencyObject element) { Paragraph p = element as Paragraph; return (p != null) ? p.MinWidowLines : 0; } // ------------------------------------------------------------------ // GetMinOrphanLines // ------------------------------------------------------------------ internal static int GetMinOrphanLines(DependencyObject element) { Paragraph p = element as Paragraph; return (p != null) ? p.MinOrphanLines : 0; } #endregion Block Properties // ------------------------------------------------------------------ // // Misc Properties // // ------------------------------------------------------------------ #region Misc Properties /// <summary> /// Gets actual value of LineHeight property. If LineHeight is Double.Nan, returns FontSize*FontFamily.LineSpacing /// </summary> internal static double GetLineHeightValue(DependencyObject d) { double lineHeight = (double)d.GetValue(Block.LineHeightProperty); // If LineHeight value is 'Auto', treat it as LineSpacing * FontSize. if (DoubleUtil.IsNaN(lineHeight)) { FontFamily fontFamily = (FontFamily)d.GetValue(TextElement.FontFamilyProperty); double fontSize = (double)d.GetValue(TextElement.FontSizeProperty); lineHeight = fontFamily.LineSpacing * fontSize; } return Math.Max(TextDpi.MinWidth, Math.Min(TextDpi.MaxWidth, lineHeight)); } // ------------------------------------------------------------------ // Retrieve background brush property from specified element. // If 'element' is the same object as paragraph owner, ignore background // brush, because it is handled outside as paragraph's background. // NOTE: This method is only used to read background of text content. // // element - Element associated with content. Passed only for // performance reasons; it can be extracted from 'position'. // paragraphOwner - Owner of paragraph (usually the parent of 'element'). // // ------------------------------------------------------------------ internal static Brush GetBackgroundBrush(DependencyObject element) { Debug.Assert(element != null); Brush backgroundBrush = null; // If 'element' is FrameworkElement, it is the host of the text content. // If 'element' is Block, the content is directly hosted by a block paragraph. // In such cases ignore background brush, because it is handled outside as paragraph's background. while (backgroundBrush == null && CanApplyBackgroundBrush(element)) { backgroundBrush = (Brush)element.GetValue(TextElement.BackgroundProperty); Invariant.Assert(element is FrameworkContentElement); element = ((FrameworkContentElement)element).Parent; } return backgroundBrush; } // ------------------------------------------------------------------ // Retrieve background brush property from specified UIElement. // // position - Exact position of the content. // ------------------------------------------------------------------ internal static Brush GetBackgroundBrushForInlineObject(StaticTextPointer position) { object selected; Brush backgroundBrush; Debug.Assert(!position.IsNull); selected = position.TextContainer.Highlights.GetHighlightValue(position, LogicalDirection.Forward, typeof(TextSelection)); if (selected == DependencyProperty.UnsetValue) { backgroundBrush = (Brush)position.GetValue(TextElement.BackgroundProperty); } else { backgroundBrush = SelectionHighlightInfo.BackgroundBrush; } return backgroundBrush; } // ------------------------------------------------------------------ // GetBaselineAlignment // ------------------------------------------------------------------ internal static BaselineAlignment GetBaselineAlignment(DependencyObject element) { Inline i = element as Inline; BaselineAlignment baselineAlignment = (i != null) ? i.BaselineAlignment : BaselineAlignment.Baseline; // Walk up the tree to check if it inherits BaselineAlignment from a parent while (i != null && BaselineAlignmentIsDefault(i)) { i = i.Parent as Inline; } if (i != null) { // Found an Inline with non-default baseline alignment baselineAlignment = i.BaselineAlignment; } return baselineAlignment; } // ------------------------------------------------------------------ // GetBaselineAlignmentForInlineObject // ------------------------------------------------------------------ internal static BaselineAlignment GetBaselineAlignmentForInlineObject(DependencyObject element) { return GetBaselineAlignment(LogicalTreeHelper.GetParent(element)); } // ------------------------------------------------------------------ // Retrieve CultureInfo property from specified element. // ------------------------------------------------------------------ internal static CultureInfo GetCultureInfo(DependencyObject element) { XmlLanguage language = (XmlLanguage) element.GetValue(FrameworkElement.LanguageProperty); try { return language.GetSpecificCulture(); } catch (InvalidOperationException) { // We default to en-US if no part of the language tag is recognized. return System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS; } } // ------------------------------------------------------------------ // Retrieve Number substitution properties from given element // ------------------------------------------------------------------ internal static NumberSubstitution GetNumberSubstitution(DependencyObject element) { NumberSubstitution numberSubstitution = new NumberSubstitution(); numberSubstitution.CultureSource = (NumberCultureSource)element.GetValue(NumberSubstitution.CultureSourceProperty); numberSubstitution.CultureOverride = (CultureInfo)element.GetValue(NumberSubstitution.CultureOverrideProperty); numberSubstitution.Substitution = (NumberSubstitutionMethod)element.GetValue(NumberSubstitution.SubstitutionProperty); return numberSubstitution; } private static bool CanApplyBackgroundBrush(DependencyObject element) { // If 'element' is FrameworkElement, it is the host of the text content. // If 'element' is Block, the content is directly hosted by a block paragraph. // In such cases ignore background brush, because it is handled outside as paragraph's background. // We will only apply background on Inline elements that are not AnchoredBlocks. // NOTE: We ideally do not need the AnchoredBlock check because when walking up the content tree we should hit a block before // an AnchoredBlock. Leaving it in in case this helper is used for other purposes. if (!(element is Inline) || element is AnchoredBlock) { return false; } return true; } private static bool BaselineAlignmentIsDefault(DependencyObject element) { Invariant.Assert(element != null); bool hasModifiers; if (element.GetValueSource(Inline.BaselineAlignmentProperty, null, out hasModifiers) != BaseValueSourceInternal.Default || hasModifiers) { return false; } return true; } #endregion Misc Properties } }
using System; using System.Drawing; using System.Windows.Forms; using Aga.Controls.Tree; using Aga.Controls.Tree.NodeControls; using Aga.Controls; namespace SampleApp { public partial class SimpleExample : UserControl { private class ToolTipProvider : IToolTipProvider { public string GetToolTip(TreeNodeAdv node, NodeControl nodeControl) { return "Drag&Drop nodes to move them"; } } private TreeModel _model; private Font _childFont; public SimpleExample() { InitializeComponent(); _tree.NodeMouseClick += new EventHandler<TreeNodeAdvMouseEventArgs>(_tree_NodeMouseClick); _nodeTextBox.ToolTipProvider = new ToolTipProvider(); _nodeTextBox.DrawText += new EventHandler<DrawEventArgs>(_nodeTextBox_DrawText); _model = new TreeModel(); _childFont = new Font(_tree.Font.FontFamily, 18, FontStyle.Bold); _tree.Model = _model; ChangeButtons(); _tree.BeginUpdate(); for (int i = 0; i < 10; i++) { Node node = AddRoot(); for (int n = 0; n < 500; n++) { Node child = AddChild(node); for (int k = 0; k < 5; k++) AddChild(child); } } _tree.EndUpdate(); TreeModel model2 = new TreeModel(); _tree2.Model = model2; for (int i = 0; i < 10; i++) model2.Nodes.Add(new MyNode("Node" + i.ToString())); } void _tree_NodeMouseClick(object sender, TreeNodeAdvMouseEventArgs e) { Console.WriteLine("NodeMouseClick at " + e.Node.Index.ToString()); } void _nodeTextBox_DrawText(object sender, DrawEventArgs e) { if ((e.Node.Tag as MyNode).Text.StartsWith("Child")) { e.TextColor = Color.Red; e.Font = _childFont; } } private Node AddRoot() { Node node = new MyNode("Long Root Node Text" + _model.Nodes.Count.ToString()); _model.Nodes.Add(node); return node; } private Node AddChild(Node parent) { Node node = new MyNode("Child Node " + parent.Nodes.Count.ToString()); parent.Nodes.Add(node); return node; } private void ClearClick(object sender, EventArgs e) { _tree.BeginUpdate(); _model.Nodes.Clear(); _tree.EndUpdate(); } private void AddRootClick(object sender, EventArgs e) { AddRoot(); } private void AddChildClick(object sender, EventArgs e) { if (_tree.SelectedNode != null) { Node parent = _tree.SelectedNode.Tag as Node; AddChild(parent); _tree.SelectedNode.IsExpanded = true; } } private void DeleteClick(object sender, EventArgs e) { if (_tree.SelectedNode != null) (_tree.SelectedNode.Tag as Node).Parent = null; } private void _tree_SelectionChanged(object sender, EventArgs e) { ChangeButtons(); } private void ChangeButtons() { _addChild.Enabled = (_tree.SelectedNode != null); _deleteNode.Enabled = (_tree.SelectedNode != null); btnExpNode.Enabled = (_tree.SelectedNode != null); btnExpNodes.Enabled = (_tree.SelectedNode != null); btnCollNode.Enabled = (_tree.SelectedNode != null); btnCollNodes.Enabled = (_tree.SelectedNode != null); } private void _tree_ItemDrag(object sender, ItemDragEventArgs e) { _tree.DoDragDropSelectedNodes(DragDropEffects.Move); } private void _tree_DragOver(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(typeof(TreeNodeAdv[])) && _tree.DropPosition.Node != null) { TreeNodeAdv[] nodes = e.Data.GetData(typeof(TreeNodeAdv[])) as TreeNodeAdv[]; TreeNodeAdv parent = _tree.DropPosition.Node; if (_tree.DropPosition.Position != NodePosition.Inside) parent = parent.Parent; foreach (TreeNodeAdv node in nodes) if (!CheckNodeParent(parent, node)) { e.Effect = DragDropEffects.None; return; } e.Effect = e.AllowedEffect; } } private bool CheckNodeParent(TreeNodeAdv parent, TreeNodeAdv node) { while (parent != null) { if (node == parent) return false; else parent = parent.Parent; } return true; } private void _tree_DragDrop(object sender, DragEventArgs e) { _tree.BeginUpdate(); TreeNodeAdv[] nodes = (TreeNodeAdv[])e.Data.GetData(typeof(TreeNodeAdv[])); Node dropNode = _tree.DropPosition.Node.Tag as Node; if (_tree.DropPosition.Position == NodePosition.Inside) { foreach (TreeNodeAdv n in nodes) { (n.Tag as Node).Parent = dropNode; } _tree.DropPosition.Node.IsExpanded = true; } else { Node parent = dropNode.Parent; Node nextItem = dropNode; if (_tree.DropPosition.Position == NodePosition.After) nextItem = dropNode.NextNode; foreach(TreeNodeAdv node in nodes) (node.Tag as Node).Parent = null; int index = -1; index = parent.Nodes.IndexOf(nextItem); foreach (TreeNodeAdv node in nodes) { Node item = node.Tag as Node; if (index == -1) parent.Nodes.Add(item); else { parent.Nodes.Insert(index, item); index++; } } } _tree.EndUpdate(); } private void _timer_Tick(object sender, EventArgs e) { _tree.Refresh(); } private void _performanceTest_Click(object sender, EventArgs e) { _timer.Enabled = _performanceTest.Checked; } private void _autoRowHeight_Click(object sender, EventArgs e) { _tree.AutoRowHeight = _autoRowHeight.Checked; } private void _fontSize_ValueChanged(object sender, EventArgs e) { _tree.Font = new Font(_tree.Font.FontFamily, (float)_fontSize.Value); } private void _tree_NodeMouseDoubleClick(object sender, TreeNodeAdvMouseEventArgs e) { if (e.Control is NodeTextBox) MessageBox.Show(e.Node.Tag.ToString()); } private void _tree2_ItemDrag(object sender, ItemDragEventArgs e) { _tree2.DoDragDropSelectedNodes(DragDropEffects.Move); } private void button1_Click(object sender, EventArgs e) { TimeCounter.Start(); _tree.FullUpdate(); //_model.Root.Nodes[0].Text = "Child"; button1.Text = TimeCounter.Finish().ToString(); } private void button2_Click(object sender, EventArgs e) { if (_tree.Root.Children.Count > 0) { if (_tree.Root.Children[0].IsExpanded) _tree.CollapseAll(); else _tree.ExpandAll(); } } private void btnExpNode_Click(object sender, EventArgs e) { _tree.SelectedNode.Expand(); } private void btnExpNodes_Click(object sender, EventArgs e) { _tree.SelectedNode.ExpandAll(); } private void btnCollNode_Click(object sender, EventArgs e) { _tree.SelectedNode.Collapse(); } private void btnCollNodes_Click(object sender, EventArgs e) { _tree.SelectedNode.CollapseAll(); } private void button3_Click(object sender, EventArgs e) { _tree.ClearSelection(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsRequiredOptional { 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 ImplicitModelExtensions { /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pathParameter'> /// </param> public static Error GetRequiredPath(this IImplicitModel operations, string pathParameter) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredPathAsync(pathParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pathParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredPathAsync( this IImplicitModel operations, string pathParameter, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRequiredPathWithHttpMessagesAsync(pathParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> public static void PutOptionalQuery(this IImplicitModel operations, string queryParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalQueryAsync(queryParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalQueryAsync( this IImplicitModel operations, string queryParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalQueryWithHttpMessagesAsync(queryParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> public static void PutOptionalHeader(this IImplicitModel operations, string queryParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalHeaderAsync(queryParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalHeaderAsync( this IImplicitModel operations, string queryParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalHeaderWithHttpMessagesAsync(queryParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PutOptionalBody(this IImplicitModel operations, string bodyParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalBodyAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalBodyAsync( this IImplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalBodyWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetRequiredGlobalPath(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredGlobalPathAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredGlobalPathAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRequiredGlobalPathWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetRequiredGlobalQuery(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredGlobalQueryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredGlobalQueryAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRequiredGlobalQueryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetOptionalGlobalQuery(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetOptionalGlobalQueryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetOptionalGlobalQueryAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOptionalGlobalQueryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// <copyright file="QRTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 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 System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double; using MathNet.Numerics.LinearAlgebra.Double.Factorization; using MathNet.Numerics.LinearAlgebra.Factorization; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Factorization { /// <summary> /// QR factorization tests for a dense matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class QRTests { /// <summary> /// Constructor with wide matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void ConstructorWideMatrixThrowsInvalidMatrixOperationException() { Assert.That(() => UserQR.Create(Matrix<double>.Build.Dense(3, 4)), Throws.ArgumentException); } /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = Matrix<double>.Build.DenseIdentity(order); var factorQR = matrixI.QR(QRMethod.Full); var r = factorQR.R; Assert.AreEqual(matrixI.RowCount, r.RowCount); Assert.AreEqual(matrixI.ColumnCount, r.ColumnCount); for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i == j) { Assert.AreEqual(1.0, Math.Abs(r[i, j])); } else { Assert.AreEqual(0.0, r[i, j]); } } } } /// <summary> /// Can factorize identity matrix using thin QR. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentityUsingThinQR(int order) { var matrixI = Matrix<double>.Build.DenseIdentity(order); var factorQR = matrixI.QR(QRMethod.Thin); var r = factorQR.R; Assert.AreEqual(matrixI.ColumnCount, r.RowCount); Assert.AreEqual(matrixI.ColumnCount, r.ColumnCount); for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i == j) { Assert.AreEqual(1.0, Math.Abs(r[i, j])); } else { Assert.AreEqual(0.0, r[i, j]); } } } } /// <summary> /// Identity determinant is one. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void IdentityDeterminantIsOne(int order) { var matrixI = Matrix<double>.Build.DenseIdentity(order); var factorQR = matrixI.QR(); Assert.AreEqual(1.0, factorQR.Determinant); } /// <summary> /// Can factorize a random matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrix(int row, int column) { var matrixA = Matrix<double>.Build.Random(row, column, 1); var factorQR = matrixA.QR(QRMethod.Full); var q = factorQR.Q; var r = factorQR.R; // Make sure the R has the right dimensions. Assert.AreEqual(row, r.RowCount); Assert.AreEqual(column, r.ColumnCount); // Make sure the Q has the right dimensions. Assert.AreEqual(row, q.RowCount); Assert.AreEqual(row, q.ColumnCount); // Make sure the R factor is upper triangular. for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i > j) { Assert.AreEqual(0.0, r[i, j]); } } } // Make sure the Q*R is the original matrix. var matrixQfromR = q*r; for (var i = 0; i < matrixQfromR.RowCount; i++) { for (var j = 0; j < matrixQfromR.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j], matrixQfromR[i, j], 1.0e-11); } } // Make sure the Q is unitary --> (Q*)x(Q) = var matrixQtQ = q.Transpose() * q; for (var i = 0; i < matrixQtQ.RowCount; i++) { for (var j = 0; j < matrixQtQ.ColumnCount; j++) { Assert.AreEqual(matrixQtQ[i, j], i == j ? 1.0 : 0.0, 1e-3); } } } /// <summary> /// Can factorize a random matrix using thin QR. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrixUsingThinQR(int row, int column) { var matrixA = Matrix<double>.Build.Random(row, column, 1); var factorQR = matrixA.QR(QRMethod.Thin); var q = factorQR.Q; var r = factorQR.R; // Make sure the R has the right dimensions. Assert.AreEqual(column, r.RowCount); Assert.AreEqual(column, r.ColumnCount); // Make sure the Q has the right dimensions. Assert.AreEqual(row, q.RowCount); Assert.AreEqual(column, q.ColumnCount); // Make sure the R factor is upper triangular. for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i > j) { Assert.AreEqual(0.0, r[i, j]); } } } // Make sure the Q*R is the original matrix. var matrixQfromR = q*r; for (var i = 0; i < matrixQfromR.RowCount; i++) { for (var j = 0; j < matrixQfromR.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j], matrixQfromR[i, j], 1.0e-11); } } // Make sure the Q is unitary --> (Q*)x(Q) = var matrixQtQ = q.Transpose() * q; for (var i = 0; i < matrixQtQ.RowCount; i++) { for (var j = 0; j < matrixQtQ.ColumnCount; j++) { Assert.AreEqual(matrixQtQ[i, j], i == j ? 1.0 : 0.0, 1e-3); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVector(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(); var vectorb = Vector<double>.Build.Random(order, 1); var resultx = factorQR.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrix(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(); var matrixB = Matrix<double>.Build.Random(order, order, 1); var matrixX = factorQR.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(); var vectorb = Vector<double>.Build.Random(order, 1); var vectorbCopy = vectorb.Clone(); var resultx = new DenseVector(order); factorQR.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(); var matrixB = Matrix<double>.Build.Random(order, order, 1); var matrixBCopy = matrixB.Clone(); var matrixX = Matrix<double>.Build.Dense(order, order); factorQR.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorUsingThinQR(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(QRMethod.Thin); var vectorb = Vector<double>.Build.Random(order, 1); var resultx = factorQR.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 9); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixUsingThinQR(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(QRMethod.Thin); var matrixB = Matrix<double>.Build.Random(order, order, 1); var matrixX = factorQR.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 9); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGivenUsingThinQR(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(QRMethod.Thin); var vectorb = Vector<double>.Build.Random(order, 1); var vectorbCopy = vectorb.Clone(); var resultx = new DenseVector(order); factorQR.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 9); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGivenUsingThinQR(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(QRMethod.Thin); var matrixB = Matrix<double>.Build.Random(order, order, 1); var matrixBCopy = matrixB.Clone(); var matrixX = Matrix<double>.Build.Dense(order, order); factorQR.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 9); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } /// <summary> /// Can solve when using a tall matrix. /// </summary> /// <param name="method">The QR decomp method to use.</param> [TestCase(QRMethod.Full)] [TestCase(QRMethod.Thin)] public void CanSolveForMatrixWithTallRandomMatrix(QRMethod method) { var matrixA = Matrix<double>.Build.Random(20, 10, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(method); var matrixB = Matrix<double>.Build.Random(20, 5, 1); var matrixX = factorQR.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var test = (matrixA.Transpose() * matrixA).Inverse() * matrixA.Transpose() * matrixB; for (var i = 0; i < matrixX.RowCount; i++) { for (var j = 0; j < matrixX.ColumnCount; j++) { AssertHelpers.AlmostEqual(test[i, j], matrixX[i, j], 12); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve when using a tall matrix. /// </summary> /// <param name="method">The QR decomp method to use.</param> [TestCase(QRMethod.Full)] [TestCase(QRMethod.Thin)] public void CanSolveForVectorWithTallRandomMatrix(QRMethod method) { var matrixA = Matrix<double>.Build.Random(20, 10, 1); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(method); var vectorB = Vector<double>.Build.Random(20, 1); var vectorX = factorQR.Solve(vectorB); // The solution x dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, vectorX.Count); var test = (matrixA.Transpose() * matrixA).Inverse() * matrixA.Transpose() * vectorB; for (var i = 0; i < vectorX.Count; i++) { AssertHelpers.AlmostEqual(test[i], vectorX[i], 9); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } } }
//------------------------------------------------------------------------------ // <copyright file="BlockBlobWriter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers { using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Blob; internal sealed class BlockBlobWriter : TransferReaderWriterBase { private volatile bool hasWork; private volatile State state; private CountdownEvent countdownEvent; private string[] blockIdSequence; private AzureBlobLocation destLocation; private CloudBlockBlob blockBlob; public BlockBlobWriter( TransferScheduler scheduler, SyncTransferController controller, CancellationToken cancellationToken) : base(scheduler, controller, cancellationToken) { this.destLocation = this.SharedTransferData.TransferJob.Destination as AzureBlobLocation; this.blockBlob = this.destLocation.Blob as CloudBlockBlob; Debug.Assert(null != this.blockBlob, "The destination is not a block blob while initializing a BlockBlobWriter instance."); this.state = State.FetchAttributes; this.hasWork = true; } private enum State { FetchAttributes, UploadBlob, Commit, Error, Finished }; public override bool PreProcessed { get; protected set; } public override bool HasWork { get { return this.hasWork && (!this.PreProcessed || ((this.state == State.UploadBlob) && this.SharedTransferData.AvailableData.Any()) || ((this.state == State.Commit) && (null != this.SharedTransferData.Attributes))); } } public override bool IsFinished { get { return State.Error == this.state || State.Finished == this.state; } } public override async Task DoWorkInternalAsync() { switch (this.state) { case State.FetchAttributes: await this.FetchAttributesAsync(); break; case State.UploadBlob: await this.UploadBlobAsync(); break; case State.Commit: await this.CommitAsync(); break; case State.Error: default: break; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (null != this.countdownEvent) { this.countdownEvent.Dispose(); this.countdownEvent = null; } } } private async Task FetchAttributesAsync() { Debug.Assert( this.state == State.FetchAttributes, "FetchAttributesAsync called, but state isn't FetchAttributes", "Current state is {0}", this.state); this.hasWork = false; if (this.SharedTransferData.TotalLength > Constants.MaxBlockBlobFileSize) { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.BlobFileSizeTooLargeException, Utils.BytesToHumanReadableSize(this.SharedTransferData.TotalLength), Resources.BlockBlob, Utils.BytesToHumanReadableSize(Constants.MaxBlockBlobFileSize)); throw new TransferException( TransferErrorCode.UploadSourceFileSizeTooLarge, exceptionMessage); } AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition( this.destLocation.AccessCondition, this.destLocation.CheckedAccessCondition); try { await this.destLocation.Blob.FetchAttributesAsync( accessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.Controller.TransferContext), this.CancellationToken); } catch (StorageException e) { this.HandleFetchAttributesResult(e); return; } this.HandleFetchAttributesResult(null); } private void HandleFetchAttributesResult(Exception e) { bool existingBlob = true; if (null != e) { StorageException se = e as StorageException; if (null != se) { // Getting a storage exception is expected if the blob doesn't // exist. In this case we won't error out, but set the // existingBlob flag to false to indicate we're uploading // a new blob instead of overwriting an existing blob. if (null != se.RequestInformation && se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { existingBlob = false; } else if (null != se && (0 == string.Compare(se.Message, Constants.BlobTypeMismatch, StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch); } else { throw se; } } else { throw e; } } this.destLocation.CheckedAccessCondition = true; if (string.IsNullOrEmpty(this.destLocation.BlockIdPrefix)) { // BlockIdPrefix is never set before that this is the first time to transfer this file. // In block blob upload, it stores uploaded but not committed blocks on Azure Storage. // In DM, we use block id to identify the blocks uploaded so we only need to upload it once. // Keep BlockIdPrefix in upload job object for restarting the transfer if anything happens. this.destLocation.BlockIdPrefix = Guid.NewGuid().ToString("N") + "-"; } // If destination file exists, query user whether to overwrite it. this.Controller.CheckOverwrite( existingBlob, this.SharedTransferData.SourceLocation, this.destLocation.Blob.Uri.ToString()); this.Controller.UpdateProgressAddBytesTransferred(0); if (existingBlob) { if (this.destLocation.Blob.Properties.BlobType == BlobType.Unspecified) { throw new InvalidOperationException(Resources.FailedToGetBlobTypeException); } if (this.destLocation.Blob.Properties.BlobType != BlobType.BlockBlob) { throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch); } Debug.Assert( this.destLocation.Blob.Properties.BlobType == BlobType.BlockBlob, "BlobType should be BlockBlob if we reach here."); } // Calculate number of blocks. int numBlocks = (int)Math.Ceiling( this.SharedTransferData.TotalLength / (double)this.Scheduler.TransferOptions.BlockSize); // Create sequence array. this.blockIdSequence = new string[numBlocks]; for (int i = 0; i < numBlocks; ++i) { string blockIdSuffix = i.ToString("D6", CultureInfo.InvariantCulture); byte[] blockIdInBytes = System.Text.Encoding.UTF8.GetBytes(this.destLocation.BlockIdPrefix + blockIdSuffix); string blockId = Convert.ToBase64String(blockIdInBytes); this.blockIdSequence[i] = blockId; } SingleObjectCheckpoint checkpoint = this.SharedTransferData.TransferJob.CheckPoint; int leftBlockCount = (int)Math.Ceiling( (this.SharedTransferData.TotalLength - checkpoint.EntryTransferOffset) / (double)this.Scheduler.TransferOptions.BlockSize) + checkpoint.TransferWindow.Count; if (0 == leftBlockCount) { this.state = State.Commit; } else { this.countdownEvent = new CountdownEvent(leftBlockCount); this.state = State.UploadBlob; } this.PreProcessed = true; this.hasWork = true; } private async Task UploadBlobAsync() { Debug.Assert( State.UploadBlob == this.state || State.Error == this.state, "UploadBlobAsync called but state is not UploadBlob nor Error.", "Current state is {0}", this.state); TransferData transferData = this.GetFirstAvailable(); if (null != transferData) { using (transferData) { transferData.Stream = new MemoryStream(transferData.MemoryBuffer, 0, transferData.Length); await this.blockBlob.PutBlockAsync( this.GetBlockId(transferData.StartOffset), transferData.Stream, null, Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition, true), Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.Controller.TransferContext), this.CancellationToken); } lock (this.SharedTransferData.TransferJob.CheckPoint.TransferWindowLock) { this.SharedTransferData.TransferJob.CheckPoint.TransferWindow.Remove(transferData.StartOffset); } this.FinishBlock(transferData.Length); } // Do not set hasWork to true because it's always true in State.UploadBlob // Otherwise it may cause CommitAsync be called multiple times: // 1. UploadBlobAsync downloads all content, but doesn't set hasWork to true yet // 2. Call CommitAysnc, set hasWork to false // 3. UploadBlobAsync set hasWork to true. // 4. Call CommitAsync again since hasWork is true. } private async Task CommitAsync() { Debug.Assert( this.state == State.Commit, "CommitAsync called, but state isn't Commit", "Current state is {0}", this.state); this.hasWork = false; Utils.SetAttributes(this.blockBlob, this.SharedTransferData.Attributes); BlobRequestOptions blobRequestOptions = Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions); OperationContext operationContext = Utils.GenerateOperationContext(this.Controller.TransferContext); await this.blockBlob.PutBlockListAsync( this.blockIdSequence, Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition), blobRequestOptions, operationContext, this.CancellationToken); // REST API PutBlockList cannot clear existing Content-Type of block blob, so if it's needed to clear existing // Content-Type, REST API SetBlobProperties must be called explicitly: // 1. The attributes are inherited from others and Content-Type is null or empty. // 2. User specifies Content-Type to string.Empty while uploading. if (this.SharedTransferData.Attributes.OverWriteAll && string.IsNullOrEmpty(this.SharedTransferData.Attributes.ContentType) || (!this.SharedTransferData.Attributes.OverWriteAll && this.SharedTransferData.Attributes.ContentType == string.Empty)) { await this.blockBlob.SetPropertiesAsync( Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition), blobRequestOptions, operationContext, this.CancellationToken); } this.SetFinish(); } private void SetFinish() { this.state = State.Finished; this.NotifyFinished(null); this.hasWork = false; } private void FinishBlock(long length) { Debug.Assert( this.state == State.UploadBlob || this.state == State.Error, "FinishBlock called, but state isn't Upload or Error", "Current state is {0}", this.state); // If a parallel operation caused the controller to be placed in // error state exit, make sure not to accidentally change it to // the Commit state. if (this.state == State.Error) { return; } this.Controller.UpdateProgressAddBytesTransferred(length); if (this.countdownEvent.Signal()) { this.state = State.Commit; } } private string GetBlockId(long startOffset) { Debug.Assert(startOffset % this.Scheduler.TransferOptions.BlockSize == 0, "Block startOffset should be multiples of block size."); int count = (int)(startOffset / this.Scheduler.TransferOptions.BlockSize); return this.blockIdSequence[count]; } } }
//! \file AudioMV2.cs //! \date Sat Dec 03 05:42:52 2016 //! \brief CVNS engine audio format. // // Copyright (C) 2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.ComponentModel.Composition; using System.IO; using GameRes.Utility; namespace GameRes.Formats.Purple { [Export(typeof(AudioFormat))] public class Mv2Audio : AudioFormat { public override string Tag { get { return "MV2"; } } public override string Description { get { return "CVNS engine compressed audio format"; } } public override uint Signature { get { return 0x5832564D; } } // 'MV2X' public override bool CanWrite { get { return false; } } public override SoundInput TryOpen (IBinaryStream file) { using (var decoder = new Mv2Decoder (file)) { decoder.Unpack(); var pcm = new MemoryStream (decoder.Data); var sound = new RawPcmInput (pcm, decoder.Format); file.Dispose(); return sound; } } } internal sealed class Mv2Decoder : MvDecoderBase { int m_shift; int m_samples; public Mv2Decoder (IBinaryStream input) : base (input) { var header = input.ReadHeader (0x12); m_channel_size = header.ToInt32 (4); m_format.FormatTag = 1; m_format.BitsPerSample = 16; m_format.Channels = header[0xC]; m_format.SamplesPerSecond = header.ToUInt16 (0xA); m_format.BlockAlign = (ushort)(m_format.Channels*m_format.BitsPerSample/8); m_format.AverageBytesPerSecond = m_format.BlockAlign * m_format.SamplesPerSecond; m_output = new byte[m_format.BlockAlign * m_channel_size]; m_shift = header[0xD]; m_samples = header.ToInt32 (0xE); } int pre2_idx; int[] pre_sample1; int[] pre_sample2; int[] pre_sample3; public void Unpack () { SetPosition (0x12); pre_sample1 = new int[0x400]; pre_sample2 = new int[0x400 * m_format.Channels]; pre_sample3 = new int[0x140 * m_format.Channels]; pre2_idx = 0; int dst_pos = 0; for (int i = 0; i < m_samples && dst_pos < m_output.Length; ++i) { for (int c = 0; c < m_format.Channels; ++c) { int n1 = GetBits (10); if (-1 == n1) return; int n2 = GetBits (9); if (-1 == n2) return; FillSample1 (n1, n2); int t = 0; // within pre_sample1 for (int j = 0; j < 10; ++j) { FilterSamples (t, t, c); t += 0x20; } int shift = 6 - m_shift; int dst = dst_pos + 2 * c; for (int j = 0; j < 0x140 && dst < m_output.Length; ++j) { short sample = Clamp (pre_sample3[j] >> shift); LittleEndian.Pack (sample, m_output, dst); dst += m_format.BlockAlign; } } dst_pos += 2 * m_format.Channels * 0x140; } } void FillSample1 (int n1, int n2) { for (int i = 0; i < 0x140; ++i) pre_sample1[i] = 0; n2 = SampleTable[n2]; for (int i = 0; i < n1; ++i) { int count = GetCount(); if (count > 0) { int coef = GetBits (count); if (coef < 1 << (count-1)) coef += 1 - (1 << count); pre_sample1[i] = n2 * coef; } else { i += GetBits (3); } } } void FilterSamples (int dst, int src, int channel) { int idx2 = pre2_idx + (channel << 10); int coef1_idx = 0; for (int j = 0; j < 64; ++j) { int pre1_idx = src; int sample = 0; for (int k = 0; k < 8; ++k) { for (int m = 0; m < 4; ++m) { sample += MvDecoder.Coef1Table[coef1_idx++] * pre_sample1[pre1_idx++] >> 10; } } pre_sample2[idx2 + j] = sample; } for (int j = 0; j < 0x20; ++j) { int m = idx2 + j; int coef2_idx = j; int x = 0; for (int k = 0; k < 4; ++k) { x += pre_sample2[m & 0x3FF] * Coef2Table[coef2_idx] >> 10; coef2_idx += 32; m += 96; x += pre_sample2[m & 0x3FF] * Coef2Table[coef2_idx] >> 10; coef2_idx += 32; m += 32; x -= pre_sample2[m & 0x3FF] * Coef2Table[coef2_idx] >> 10; coef2_idx += 32; m += 96; x -= pre_sample2[m & 0x3FF] * Coef2Table[coef2_idx] >> 10; coef2_idx += 32; m += 32; } pre_sample3[dst++] = x; } pre2_idx = ((ushort)pre2_idx - 0x40) & 0x3FF; } static readonly int[] SampleTable = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 10, 11, 12, 14, 16, 18, 20, 23, 26, 29, 33, 38, 42, 48, 54, 61, 69, 78, 88, 100, 113, 128, 144, 163, 184, 207, 234, 265, 299, 337, 381, 430, 486, 548, 619, 699, 789, 891, 1006, 1136, 1282, 1448, 1634, 1845, 2083, 2352, 2655, 2998, 3385, 3821, 4314, 4870, 5499, 6208, 7009, 7912, 8933, 10085, 11386, 12854, 14512, 16384, 18496, 20882, 23575, 26615, 30048, 33923, 38298, 43237, 48813, 55108, 62216, 70239, 79298, 89524, 101070, 114104, 128820, 145433, 164189, 185363, 209269, 236257, 266726, 301124, 339958, 383801, 433297, 489178, 552264, 623487, 703894, 794672, 897156, 1012857, 1143480, 1290948, 1457434, 1645392, 1857589, -47447340, 47512876, -47447340, 47512876, -47447340, 47512876, -47447340, 47512876, -47447340, 47512876, -47447340, 47512876, -47447340, 47512876, -47447340, 47512876, -53869905, 60685810, -65076904, 67043178, -66256946, 63176952, -57475509, 49676897, -39846646, 28640110, -16188356, 3277812, 9894914, -22543391, 34536547, -45022410, -59178359, 66846423, -64094308, 51839458, -31523607, 6554579, 19528709, -42531961, 59243895, -66780887, 64159844, -51773922, 31589143, -6489043, -19463173, 42597497, -63176095, 65142734, -44958222, 9831325, 28703756, -57539850, 67043080, -53805400, 22545206, 16317442, -49675410, 66387531, -60555414, 34472623, 3341343, -39910460, -65797576, 55771335, -12976979, -37223444, 65863112, -55705799, 13042515, 37288980, -65797576, 55771335, -12976979, -37223444, 65863112, -55705799, 13042515, 37288980, -66977266, 39911861, 22608908, -65076561, 49676536, 9894972, -60619978, 57540658, -3212142, -53869667, 63242090, -16188150, -45022239, 66387624, -28574305, -34470914, -66780702, 19464841, 51903533, -59178908, -6552697, 64224489, -42467625, -31587333, 66846238, -19399305, -51837997, 59244444, 6618233, -64158953, 42533161, 31652869, -65076811, -3275978, 66387210, -22479374, -57539644, 45023382, 39975938, -60620552, -16252003, 67042719, -9765551, -63175826, 34472280, 49740812, -53870542, -28638239, -61996665, -25623630, 62062201, 25689166, -61996665, -25623630, 62062201, 25689166, -61996665, -25623630, 62062201, 25689166, -61996665, -25623630, 62062201, 25689166, -57540264, -45022220, 39911474, 60685343, -16187829, -66976970, -9829642, 63241714, 34536508, -49676138, -53869570, 28639480, 65141859, -3211873, -66321745, -22543506, -51838679, -59177989, 6554082, 64224631, 42597421, -31522916, -66780281, -19463401, 51904215, 59243525, -6488546, -64159095, -42531885, 31588452, 66845817, 19528937, -45022984, -66321468, -28638410, 34537422, 67042450, 39976035, -22478998, -65076490, -49675295, 9830744, 60685727, 57605122, 3341810, -53870155, -63175692, -16252241, -37224249, -65797293, -55770132, -13041096, 37289785, 65862829, 55835668, 13106632, -37224249, -65797293, -55770132, -13041096, 37289785, 65862829, 55835668, 13106632, -28639082, -57539921, -66976799, -53869628, -22543775, 16252978, 49741298, 66387043, 60685324, 34536714, -3211512, -39911080, -63175882, -65076226, -45022354, -9829963, -19464092, -42532382, -59178217, -66780205, -64158725, -51838073, -31587703, -6553303, 19529628, 42597918, 59243753, 66845741, 64224261, 51903609, 31653239, 6618839, -9830350, -22544136, -34471499, -45022623, -53869834, -60619922, -65076284, -66976780, -66321410, -63175711, -57539683, -49675466, -39910737, -28638706, -16252584, -3276650, }; static readonly short[] Coef2Table = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -2, -2, -2, -2, -1, -1, -1, 0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 31, 32, 32, 32, 32, 32, 32, 31, 31, 30, 29, 28, 27, 25, 23, 22, 20, 17, 15, 12, 9, 6, 2, 0, -4, -8, -12, -17, -21, -26, -31, -36, -41, -46, -52, -57, -63, -69, -74, -80, -86, -91, -97, -102, -108, -113, -118, -123, -128, -132, -136, -140, -144, -147, -149, -151, -153, -154, -155, -155, -155, -154, -152, -149, -146, -142, -138, -132, -126, -119, -111, -102, -93, -82, -71, -58, -45, -31, -16, -1, 15, 33, 51, 70, 90, 111, 133, 155, 178, 202, 227, 252, 278, 304, 331, 358, 385, 413, 442, 470, 499, 527, 556, 585, 614, 643, 671, 700, 728, 756, 783, 810, 836, 862, 887, 911, 934, 957, 979, 1000, 1020, 1038, 1056, 1073, 1088, 1102, 1115, 1127, 1138, 1147, 1154, 1161, 1166, 1169, 1171, 1172, 1171, 1169, 1166, 1161, 1154, 1147, 1138, 1127, 1115, 1102, 1088, 1073, 1056, 1038, 1020, 1000, 979, 957, 934, 911, 887, 862, 836, 810, 783, 756, 728, 700, 671, 643, 614, 585, 556, 527, 499, 470, 442, 413, 385, 358, 331, 304, 278, 252, 227, 202, 178, 155, 133, 111, 90, 70, 51, 33, 15, -1, -16, -31, -45, -58, -71, -82, -93, -102, -111, -119, -126, -132, -138, -142, -146, -149, -152, -154, -155, -155, -155, -154, -153, -151, -149, -147, -144, -140, -136, -132, -128, -123, -118, -113, -108, -102, -97, -91, -86, -80, -74, -69, -63, -57, -52, -46, -41, -36, -31, -26, -21, -17, -12, -8, -4, 0, 2, 6, 9, 12, 15, 17, 20, 22, 23, 25, 27, 28, 29, 30, 31, 31, 32, 32, 32, 32, 32, 32, 31, 31, 30, 29, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 3, 2, 1, 1, 0, 0, 0, 0, -1, -1, -1, -2, -2, -2, -2, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; } }
//! \file ImageTGA.cs //! \date Fri Jul 04 07:24:38 2014 //! \brief Targa image implementation. // // Copyright (C) 2014-2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using System.ComponentModel.Composition; namespace GameRes { public class TgaMetaData : ImageMetaData { public short ImageType; public short ColormapType; public uint ColormapOffset; public ushort ColormapFirst; public ushort ColormapLength; public short ColormapDepth; public short Descriptor; } [Export(typeof(ImageFormat))] public class TgaFormat : ImageFormat { public override string Tag { get { return "TGA"; } } public override string Description { get { return "Truevision TGA image"; } } public override uint Signature { get { return 0; } } public override ImageData Read (Stream stream, ImageMetaData metadata) { var meta = metadata as TgaMetaData; if (null == meta) throw new System.ArgumentException ("TgaFormat.Read should be supplied with TgaMetaData", "metadata"); var reader = new Reader (stream, meta); var pixels = reader.Unpack(); return ImageData.Create (meta, reader.Format, reader.Palette, pixels, reader.Stride); } public override void Write (Stream stream, ImageData image) { using (var file = new BinaryWriter (stream, System.Text.Encoding.ASCII, true)) { file.Write ((byte)0); // idlength file.Write ((byte)0); // colourmaptype file.Write ((byte)2); // datatypecode file.Write ((short)0); // colourmaporigin file.Write ((short)0); // colourmaplength file.Write ((byte)0); // colourmapdepth file.Write ((short)image.OffsetX); file.Write ((short)image.OffsetY); file.Write ((ushort)image.Width); file.Write ((ushort)image.Height); var bitmap = image.Bitmap; int bpp = 0; int stride = 0; byte descriptor = 0; if (PixelFormats.Bgr24 == bitmap.Format) { bpp = 24; stride = (int)image.Width*3; } else if (PixelFormats.Bgr32 == bitmap.Format) { bpp = 32; stride = (int)image.Width*4; } else { bpp = 32; stride = (int)image.Width*4; if (PixelFormats.Bgra32 != bitmap.Format) { var converted_bitmap = new FormatConvertedBitmap(); converted_bitmap.BeginInit(); converted_bitmap.Source = image.Bitmap; converted_bitmap.DestinationFormat = PixelFormats.Bgra32; converted_bitmap.EndInit(); bitmap = converted_bitmap; } } file.Write ((byte)bpp); file.Write (descriptor); byte[] row_data = new byte[stride]; Int32Rect rect = new Int32Rect (0, (int)image.Height, (int)image.Width, 1); for (uint row = 0; row < image.Height; ++row) { --rect.Y; bitmap.CopyPixels (rect, row_data, stride, 0); file.Write (row_data); } } } public override ImageMetaData ReadMetaData (Stream stream) { using (var file = new ArcView.Reader (stream)) { short id_length = file.ReadByte(); short colormap_type = file.ReadByte(); if (colormap_type > 1) return null; short image_type = file.ReadByte(); ushort colormap_first = file.ReadUInt16(); ushort colormap_length = file.ReadUInt16(); short colormap_depth = file.ReadByte(); int pos_x = file.ReadInt16(); int pos_y = file.ReadInt16(); uint width = file.ReadUInt16(); uint height = file.ReadUInt16(); int bpp = file.ReadByte(); if (bpp != 32 && bpp != 24 && bpp != 16 && bpp != 15 && bpp != 8) return null; short descriptor = file.ReadByte(); uint colormap_offset = (uint)(18 + id_length); switch (image_type) { default: return null; case 1: // Uncompressed, color-mapped images. case 9: // Runlength encoded color-mapped images. case 32: // Compressed color-mapped data, using Huffman, Delta, and // runlength encoding. case 33: // Compressed color-mapped data, using Huffman, Delta, and // runlength encoding. 4-pass quadtree-type process. if (colormap_depth != 24 && colormap_depth != 32) return null; break; case 2: // Uncompressed, RGB images. case 3: // Uncompressed, black and white images. case 10: // Runlength encoded RGB images. case 11: // Compressed, black and white images. break; } return new TgaMetaData { OffsetX = pos_x, OffsetY = pos_y, Width = width, Height = height, BPP = bpp, ImageType = image_type, ColormapType = colormap_type, ColormapOffset = colormap_offset, ColormapFirst = colormap_first, ColormapLength = colormap_length, ColormapDepth = colormap_depth, Descriptor = descriptor, }; } } internal class Reader { Stream m_input; TgaMetaData m_meta; int m_width; int m_height; int m_stride; byte[] m_data; long m_image_offset; public PixelFormat Format { get; private set; } public BitmapPalette Palette { get; private set; } public int Stride { get { return m_stride; } } public byte[] Data { get { return m_data; } } public Reader (Stream stream, TgaMetaData meta) { m_input = stream; m_meta = meta; switch (meta.BPP) { default: throw new InvalidFormatException(); case 8: if (1 == meta.ColormapType) Format = PixelFormats.Indexed8; else Format = PixelFormats.Gray8; break; case 15: Format = PixelFormats.Bgr555; break; case 16: Format = PixelFormats.Bgr555; break; case 32: Format = PixelFormats.Bgra32; break; case 24: if (8 == (meta.Descriptor & 0xf)) Format = PixelFormats.Bgr32; else Format = PixelFormats.Bgr24; break; } int colormap_size = meta.ColormapLength * meta.ColormapDepth / 8; m_width = (int)meta.Width; m_height = (int)meta.Height; m_stride = m_width * ((Format.BitsPerPixel+7) / 8); m_image_offset = meta.ColormapOffset; if (1 == meta.ColormapType) { m_image_offset += colormap_size; m_input.Position = meta.ColormapOffset; ReadColormap (meta.ColormapLength, meta.ColormapDepth); } m_data = new byte[m_stride*m_height]; } private void ReadColormap (int length, int depth) { if (24 != depth && 32 != depth) throw new NotImplementedException(); int pixel_size = depth / 8; var palette_data = new byte[length * pixel_size]; if (palette_data.Length != m_input.Read (palette_data, 0, palette_data.Length)) throw new InvalidFormatException(); var palette = new Color[length]; for (int i = 0; i < palette.Length; ++i) { byte b = palette_data[i*pixel_size]; byte g = palette_data[i*pixel_size+1]; byte r = palette_data[i*pixel_size+2]; palette[i] = Color.FromRgb (r, g, b); } Palette = new BitmapPalette (palette); } public byte[] Unpack () { switch (m_meta.ImageType) { case 9: // Runlength encoded color-mapped images. case 32: // Compressed color-mapped data, using Huffman, Delta, and // runlength encoding. case 33: // Compressed color-mapped data, using Huffman, Delta, and // runlength encoding. 4-pass quadtree-type process. throw new NotImplementedException(); default: throw new InvalidFormatException(); case 1: // Uncompressed, color-mapped images. case 2: // Uncompressed, RGB images. case 3: // Uncompressed, black and white images. ReadRaw(); break; case 10: // Runlength encoded RGB images. case 11: // Compressed, black and white images. ReadRLE ((m_meta.BPP+7)/8); break; } return Data; } void ReadRaw () { m_input.Position = m_image_offset; if (0 != (m_meta.Descriptor & 0x20)) { if (m_data.Length != m_input.Read (m_data, 0, m_data.Length)) throw new InvalidFormatException(); } else { for (int row = m_height-1; row >= 0; --row) { if (m_stride != m_input.Read (m_data, row*m_stride, m_stride)) throw new InvalidFormatException(); } } } void ReadRLE (int pixel_size) { m_input.Position = m_image_offset; for (int dst = 0; dst < m_data.Length;) { int packet = m_input.ReadByte(); if (-1 == packet) break; int count = (packet & 0x7f) + 1; if (0 != (packet & 0x80)) { if (pixel_size != m_input.Read (m_data, dst, pixel_size)) break; int src = dst; dst += pixel_size; for (int i = 1; i < count && dst < m_data.Length; ++i) { Buffer.BlockCopy (m_data, src, m_data, dst, pixel_size); dst += pixel_size; } } else { count *= pixel_size; if (count != m_input.Read (m_data, dst, count)) break; dst += count; } } if (0 == (m_meta.Descriptor & 0x20)) { byte[] flipped = new byte[m_stride*m_height]; int dst = 0; for (int src = m_stride*(m_height-1); src >= 0; src -= m_stride) { Buffer.BlockCopy (m_data, src, flipped, dst, m_stride); dst += m_stride; } m_data = flipped; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; using System.Linq; using Crestron; using Crestron.Logos.SplusLibrary; using Crestron.Logos.SplusObjects; using Crestron.SimplSharp; namespace UserModule_BSS_AUDIO_SOUNDWEB_LONDON_NODE { public class UserModuleClass_BSS_AUDIO_SOUNDWEB_LONDON_NODE : SplusObject { static CCriticalSection g_criticalSection = new CCriticalSection(); Crestron.Logos.SplusObjects.BufferInput COMRX__DOLLAR__; Crestron.Logos.SplusObjects.BufferInput MODULESTX__DOLLAR__; Crestron.Logos.SplusObjects.StringOutput COMTX__DOLLAR__; Crestron.Logos.SplusObjects.StringOutput MODULESRX__DOLLAR__; StringParameter NODE__DOLLAR__; private void SEND ( SplusExecutionContext __context__, CrestronString STR1 ) { __context__.SourceCodeLine = 126; _SplusNVRAM.CHECKSUM = (ushort) ( 0 ) ; __context__.SourceCodeLine = 127; _SplusNVRAM.SENDSTRING .UpdateValue ( "" ) ; __context__.SourceCodeLine = 128; ushort __FN_FORSTART_VAL__1 = (ushort) ( 1 ) ; ushort __FN_FOREND_VAL__1 = (ushort)Functions.Length( STR1 ); int __FN_FORSTEP_VAL__1 = (int)1; for ( _SplusNVRAM.I = __FN_FORSTART_VAL__1; (__FN_FORSTEP_VAL__1 > 0) ? ( (_SplusNVRAM.I >= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I <= __FN_FOREND_VAL__1) ) : ( (_SplusNVRAM.I <= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I >= __FN_FOREND_VAL__1) ) ; _SplusNVRAM.I += (ushort)__FN_FORSTEP_VAL__1) { __context__.SourceCodeLine = 130; _SplusNVRAM.CHECKSUM = (ushort) ( (_SplusNVRAM.CHECKSUM ^ Byte( STR1 , (int)( _SplusNVRAM.I ) )) ) ; __context__.SourceCodeLine = 131; if ( Functions.TestForTrue ( ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt (Byte( STR1 , (int)( _SplusNVRAM.I ) ) == 2) ) || Functions.TestForTrue ( Functions.BoolToInt (Byte( STR1 , (int)( _SplusNVRAM.I ) ) == 3) )) ) ) || Functions.TestForTrue ( Functions.BoolToInt (Byte( STR1 , (int)( _SplusNVRAM.I ) ) == 6) )) ) ) || Functions.TestForTrue ( Functions.BoolToInt (Byte( STR1 , (int)( _SplusNVRAM.I ) ) == 21) )) ) ) || Functions.TestForTrue ( Functions.BoolToInt (Byte( STR1 , (int)( _SplusNVRAM.I ) ) == 27) )) )) ) ) { __context__.SourceCodeLine = 133; MakeString ( _SplusNVRAM.SENDSTRING , "{0}\u001B{1}", _SplusNVRAM.SENDSTRING , Functions.Chr ( (int) ( (Byte( STR1 , (int)( _SplusNVRAM.I ) ) + 128) ) ) ) ; } else { __context__.SourceCodeLine = 137; MakeString ( _SplusNVRAM.SENDSTRING , "{0}{1}", _SplusNVRAM.SENDSTRING , Functions.Chr ( (int) ( Byte( STR1 , (int)( _SplusNVRAM.I ) ) ) ) ) ; } __context__.SourceCodeLine = 128; } __context__.SourceCodeLine = 140; if ( Functions.TestForTrue ( ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt (_SplusNVRAM.CHECKSUM == 2) ) || Functions.TestForTrue ( Functions.BoolToInt (_SplusNVRAM.CHECKSUM == 3) )) ) ) || Functions.TestForTrue ( Functions.BoolToInt (_SplusNVRAM.CHECKSUM == 6) )) ) ) || Functions.TestForTrue ( Functions.BoolToInt (_SplusNVRAM.CHECKSUM == 21) )) ) ) || Functions.TestForTrue ( Functions.BoolToInt (_SplusNVRAM.CHECKSUM == 27) )) )) ) ) { __context__.SourceCodeLine = 142; MakeString ( COMTX__DOLLAR__ , "\u0002{0}\u001B{1}\u0003", _SplusNVRAM.SENDSTRING , Functions.Chr ( (int) ( (_SplusNVRAM.CHECKSUM + 128) ) ) ) ; } else { __context__.SourceCodeLine = 146; MakeString ( COMTX__DOLLAR__ , "\u0002{0}{1}\u0003", _SplusNVRAM.SENDSTRING , Functions.Chr ( (int) ( _SplusNVRAM.CHECKSUM ) ) ) ; } } private CrestronString RECEIVE ( SplusExecutionContext __context__, CrestronString STR2 ) { __context__.SourceCodeLine = 153; _SplusNVRAM.RECEIVESTRING .UpdateValue ( "" ) ; __context__.SourceCodeLine = 154; ushort __FN_FORSTART_VAL__1 = (ushort) ( 1 ) ; ushort __FN_FOREND_VAL__1 = (ushort)Functions.Length( STR2 ); int __FN_FORSTEP_VAL__1 = (int)1; for ( _SplusNVRAM.J = __FN_FORSTART_VAL__1; (__FN_FORSTEP_VAL__1 > 0) ? ( (_SplusNVRAM.J >= __FN_FORSTART_VAL__1) && (_SplusNVRAM.J <= __FN_FOREND_VAL__1) ) : ( (_SplusNVRAM.J <= __FN_FORSTART_VAL__1) && (_SplusNVRAM.J >= __FN_FOREND_VAL__1) ) ; _SplusNVRAM.J += (ushort)__FN_FORSTEP_VAL__1) { __context__.SourceCodeLine = 156; if ( Functions.TestForTrue ( ( Functions.BoolToInt (Byte( STR2 , (int)( _SplusNVRAM.J ) ) == 27)) ) ) { __context__.SourceCodeLine = 158; _SplusNVRAM.RECEIVESTRING .UpdateValue ( _SplusNVRAM.RECEIVESTRING + Functions.Chr ( (int) ( (Byte( STR2 , (int)( (_SplusNVRAM.J + 1) ) ) - 128) ) ) ) ; __context__.SourceCodeLine = 159; _SplusNVRAM.J = (ushort) ( (_SplusNVRAM.J + 1) ) ; } else { __context__.SourceCodeLine = 163; _SplusNVRAM.RECEIVESTRING .UpdateValue ( _SplusNVRAM.RECEIVESTRING + Functions.Chr ( (int) ( Byte( STR2 , (int)( _SplusNVRAM.J ) ) ) ) ) ; } __context__.SourceCodeLine = 154; } __context__.SourceCodeLine = 166; while ( Functions.TestForTrue ( ( Functions.BoolToInt (Byte( _SplusNVRAM.RECEIVESTRING , (int)( 1 ) ) == 6)) ) ) { __context__.SourceCodeLine = 168; _SplusNVRAM.RECEIVESTRING .UpdateValue ( Functions.Right ( _SplusNVRAM.RECEIVESTRING , (int) ( (Functions.Length( _SplusNVRAM.RECEIVESTRING ) - 1) ) ) ) ; __context__.SourceCodeLine = 166; } __context__.SourceCodeLine = 170; return ( _SplusNVRAM.RECEIVESTRING ) ; } object MODULESTX__DOLLAR___OnChange_0 ( Object __EventInfo__ ) { Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__; try { SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__); __context__.SourceCodeLine = 216; if ( Functions.TestForTrue ( ( _SplusNVRAM.XOK1) ) ) { __context__.SourceCodeLine = 218; _SplusNVRAM.XOK1 = (ushort) ( 0 ) ; __context__.SourceCodeLine = 219; while ( Functions.TestForTrue ( ( Functions.Length( MODULESTX__DOLLAR__ )) ) ) { __context__.SourceCodeLine = 221; _SplusNVRAM.MARKER1 = (ushort) ( Functions.Find( "\u0003\u0003\u0003\u0003\u0003" , MODULESTX__DOLLAR__ ) ) ; __context__.SourceCodeLine = 222; _SplusNVRAM.MARKER2 = (ushort) ( (_SplusNVRAM.MARKER1 + 5) ) ; __context__.SourceCodeLine = 223; if ( Functions.TestForTrue ( ( Functions.BoolToInt ( _SplusNVRAM.MARKER2 <= Functions.Length( MODULESTX__DOLLAR__ ) )) ) ) { __context__.SourceCodeLine = 225; while ( Functions.TestForTrue ( ( Functions.BoolToInt (Byte( MODULESTX__DOLLAR__ , (int)( _SplusNVRAM.MARKER2 ) ) == 3)) ) ) { __context__.SourceCodeLine = 227; _SplusNVRAM.MARKER1 = (ushort) ( (_SplusNVRAM.MARKER1 + 1) ) ; __context__.SourceCodeLine = 228; _SplusNVRAM.MARKER2 = (ushort) ( (_SplusNVRAM.MARKER2 + 1) ) ; __context__.SourceCodeLine = 229; if ( Functions.TestForTrue ( ( Functions.BoolToInt ( _SplusNVRAM.MARKER2 > Functions.Length( MODULESTX__DOLLAR__ ) )) ) ) { __context__.SourceCodeLine = 231; break ; } __context__.SourceCodeLine = 225; } } __context__.SourceCodeLine = 235; if ( Functions.TestForTrue ( ( _SplusNVRAM.MARKER1) ) ) { __context__.SourceCodeLine = 237; _SplusNVRAM.MARKER1 = (ushort) ( (_SplusNVRAM.MARKER1 + 4) ) ; __context__.SourceCodeLine = 238; _SplusNVRAM.TEMPSTRING1 .UpdateValue ( Functions.Remove ( Functions.Mid ( MODULESTX__DOLLAR__ , (int) ( 1 ) , (int) ( _SplusNVRAM.MARKER1 ) ) , MODULESTX__DOLLAR__ ) ) ; __context__.SourceCodeLine = 239; MakeString ( _SplusNVRAM.TEMPSTRING1 , "{0}{1}{2}", Functions.Left ( _SplusNVRAM.TEMPSTRING1 , (int) ( 1 ) ) , NODE__DOLLAR__ , Functions.Right ( _SplusNVRAM.TEMPSTRING1 , (int) ( (Functions.Length( _SplusNVRAM.TEMPSTRING1 ) - 3) ) ) ) ; __context__.SourceCodeLine = 240; SEND ( __context__ , Functions.Left( _SplusNVRAM.TEMPSTRING1 , (int)( (Functions.Length( _SplusNVRAM.TEMPSTRING1 ) - 5) ) )) ; __context__.SourceCodeLine = 241; Functions.ClearBuffer ( _SplusNVRAM.TEMPSTRING1 ) ; } __context__.SourceCodeLine = 219; } __context__.SourceCodeLine = 244; _SplusNVRAM.XOK1 = (ushort) ( 1 ) ; } } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler( __SignalEventArg__ ); } return this; } object COMRX__DOLLAR___OnChange_1 ( Object __EventInfo__ ) { Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__; try { SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__); ushort SDUMP = 0; __context__.SourceCodeLine = 252; if ( Functions.TestForTrue ( ( _SplusNVRAM.XOK2) ) ) { __context__.SourceCodeLine = 254; _SplusNVRAM.XOK2 = (ushort) ( 0 ) ; __context__.SourceCodeLine = 255; while ( Functions.TestForTrue ( ( Functions.Length( COMRX__DOLLAR__ )) ) ) { __context__.SourceCodeLine = 257; if ( Functions.TestForTrue ( ( Functions.BoolToInt (Byte( COMRX__DOLLAR__ , (int)( 1 ) ) == 6)) ) ) { __context__.SourceCodeLine = 259; _SplusNVRAM.TEMPSTRING2 .UpdateValue ( Functions.Remove ( "\u0006" , COMRX__DOLLAR__ ) ) ; } else { __context__.SourceCodeLine = 261; if ( Functions.TestForTrue ( ( Functions.BoolToInt (Byte( COMRX__DOLLAR__ , (int)( 1 ) ) == 2)) ) ) { __context__.SourceCodeLine = 263; if ( Functions.TestForTrue ( ( Functions.Find( "\u0003" , COMRX__DOLLAR__ )) ) ) { __context__.SourceCodeLine = 265; _SplusNVRAM.TEMPSTRING2 .UpdateValue ( Functions.Remove ( "\u0003" , COMRX__DOLLAR__ ) ) ; __context__.SourceCodeLine = 272; _SplusNVRAM.TEMPSTRING3 .UpdateValue ( RECEIVE ( __context__ , _SplusNVRAM.TEMPSTRING2) ) ; __context__.SourceCodeLine = 274; if ( Functions.TestForTrue ( ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt (Byte( _SplusNVRAM.TEMPSTRING3 , (int)( 3 ) ) == Byte( NODE__DOLLAR__ , (int)( 1 ) )) ) && Functions.TestForTrue ( Functions.BoolToInt (Byte( _SplusNVRAM.TEMPSTRING3 , (int)( 4 ) ) == Byte( NODE__DOLLAR__ , (int)( 2 ) )) )) )) ) ) { __context__.SourceCodeLine = 275; MODULESRX__DOLLAR__ .UpdateValue ( _SplusNVRAM.TEMPSTRING3 + "\u0003\u0003\u0003\u0003" ) ; } } } else { __context__.SourceCodeLine = 280; SDUMP = (ushort) ( Functions.GetC( COMRX__DOLLAR__ ) ) ; } } __context__.SourceCodeLine = 283; Functions.ClearBuffer ( _SplusNVRAM.TEMPSTRING2 ) ; __context__.SourceCodeLine = 284; Functions.ClearBuffer ( _SplusNVRAM.TEMPSTRING3 ) ; __context__.SourceCodeLine = 255; } __context__.SourceCodeLine = 286; _SplusNVRAM.XOK2 = (ushort) ( 1 ) ; } } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler( __SignalEventArg__ ); } return this; } public override object FunctionMain ( object __obj__ ) { try { SplusExecutionContext __context__ = SplusFunctionMainStartCode(); __context__.SourceCodeLine = 306; _SplusNVRAM.XOK1 = (ushort) ( 1 ) ; __context__.SourceCodeLine = 307; _SplusNVRAM.XOK2 = (ushort) ( 1 ) ; } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler(); } return __obj__; } public override void LogosSplusInitialize() { SocketInfo __socketinfo__ = new SocketInfo( 1, this ); InitialParametersClass.ResolveHostName = __socketinfo__.ResolveHostName; _SplusNVRAM = new SplusNVRAM( this ); _SplusNVRAM.TEMPSTRING1 = new CrestronString( Crestron.Logos.SplusObjects.CrestronStringEncoding.eEncodingASCII, 80, this ); _SplusNVRAM.SENDSTRING = new CrestronString( Crestron.Logos.SplusObjects.CrestronStringEncoding.eEncodingASCII, 80, this ); _SplusNVRAM.TEMPSTRING2 = new CrestronString( Crestron.Logos.SplusObjects.CrestronStringEncoding.eEncodingASCII, 80, this ); _SplusNVRAM.TEMPSTRING3 = new CrestronString( Crestron.Logos.SplusObjects.CrestronStringEncoding.eEncodingASCII, 80, this ); _SplusNVRAM.RECEIVESTRING = new CrestronString( Crestron.Logos.SplusObjects.CrestronStringEncoding.eEncodingASCII, 80, this ); COMTX__DOLLAR__ = new Crestron.Logos.SplusObjects.StringOutput( COMTX__DOLLAR____AnalogSerialOutput__, this ); m_StringOutputList.Add( COMTX__DOLLAR____AnalogSerialOutput__, COMTX__DOLLAR__ ); MODULESRX__DOLLAR__ = new Crestron.Logos.SplusObjects.StringOutput( MODULESRX__DOLLAR____AnalogSerialOutput__, this ); m_StringOutputList.Add( MODULESRX__DOLLAR____AnalogSerialOutput__, MODULESRX__DOLLAR__ ); COMRX__DOLLAR__ = new Crestron.Logos.SplusObjects.BufferInput( COMRX__DOLLAR____AnalogSerialInput__, 1000, this ); m_StringInputList.Add( COMRX__DOLLAR____AnalogSerialInput__, COMRX__DOLLAR__ ); MODULESTX__DOLLAR__ = new Crestron.Logos.SplusObjects.BufferInput( MODULESTX__DOLLAR____AnalogSerialInput__, 1000, this ); m_StringInputList.Add( MODULESTX__DOLLAR____AnalogSerialInput__, MODULESTX__DOLLAR__ ); NODE__DOLLAR__ = new StringParameter( NODE__DOLLAR____Parameter__, this ); m_ParameterList.Add( NODE__DOLLAR____Parameter__, NODE__DOLLAR__ ); MODULESTX__DOLLAR__.OnSerialChange.Add( new InputChangeHandlerWrapper( MODULESTX__DOLLAR___OnChange_0, false ) ); COMRX__DOLLAR__.OnSerialChange.Add( new InputChangeHandlerWrapper( COMRX__DOLLAR___OnChange_1, false ) ); _SplusNVRAM.PopulateCustomAttributeList( true ); NVRAM = _SplusNVRAM; } public override void LogosSimplSharpInitialize() { } public UserModuleClass_BSS_AUDIO_SOUNDWEB_LONDON_NODE ( string InstanceName, string ReferenceID, Crestron.Logos.SplusObjects.CrestronStringEncoding nEncodingType ) : base( InstanceName, ReferenceID, nEncodingType ) {} const uint COMRX__DOLLAR____AnalogSerialInput__ = 0; const uint MODULESTX__DOLLAR____AnalogSerialInput__ = 1; const uint COMTX__DOLLAR____AnalogSerialOutput__ = 0; const uint MODULESRX__DOLLAR____AnalogSerialOutput__ = 1; const uint NODE__DOLLAR____Parameter__ = 10; [SplusStructAttribute(-1, true, false)] public class SplusNVRAM : SplusStructureBase { public SplusNVRAM( SplusObject __caller__ ) : base( __caller__ ) {} [SplusStructAttribute(0, false, true)] public ushort XOK1 = 0; [SplusStructAttribute(1, false, true)] public CrestronString TEMPSTRING1; [SplusStructAttribute(2, false, true)] public ushort CHECKSUM = 0; [SplusStructAttribute(3, false, true)] public ushort I = 0; [SplusStructAttribute(4, false, true)] public CrestronString SENDSTRING; [SplusStructAttribute(5, false, true)] public ushort XOK2 = 0; [SplusStructAttribute(6, false, true)] public CrestronString TEMPSTRING2; [SplusStructAttribute(7, false, true)] public CrestronString TEMPSTRING3; [SplusStructAttribute(8, false, true)] public ushort J = 0; [SplusStructAttribute(9, false, true)] public CrestronString RECEIVESTRING; [SplusStructAttribute(10, false, true)] public ushort MARKER1 = 0; [SplusStructAttribute(11, false, true)] public ushort MARKER2 = 0; } SplusNVRAM _SplusNVRAM = null; public class __CEvent__ : CEvent { public __CEvent__() {} public void Close() { base.Close(); } public int Reset() { return base.Reset() ? 1 : 0; } public int Set() { return base.Set() ? 1 : 0; } public int Wait( int timeOutInMs ) { return base.Wait( timeOutInMs ) ? 1 : 0; } } public class __CMutex__ : CMutex { public __CMutex__() {} public void Close() { base.Close(); } public void ReleaseMutex() { base.ReleaseMutex(); } public int WaitForMutex() { return base.WaitForMutex() ? 1 : 0; } } public int IsNull( object obj ){ return (obj == null) ? 1 : 0; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a network interface. /// </summary> public partial class InstanceNetworkInterfaceSpecification { private bool? _associatePublicIpAddress; private bool? _deleteOnTermination; private string _description; private int? _deviceIndex; private List<string> _groups = new List<string>(); private string _networkInterfaceId; private string _privateIpAddress; private List<PrivateIpAddressSpecification> _privateIpAddresses = new List<PrivateIpAddressSpecification>(); private int? _secondaryPrivateIpAddressCount; private string _subnetId; /// <summary> /// Gets and sets the property AssociatePublicIpAddress. /// <para> /// Indicates whether to assign a public IP address to an instance you launch in a VPC. /// The public IP address can only be assigned to a network interface for eth0, and can /// only be assigned to a new network interface, not an existing one. You cannot specify /// more than one network interface in the request. If launching into a default subnet, /// the default value is <code>true</code>. /// </para> /// </summary> public bool AssociatePublicIpAddress { get { return this._associatePublicIpAddress.GetValueOrDefault(); } set { this._associatePublicIpAddress = value; } } // Check to see if AssociatePublicIpAddress property is set internal bool IsSetAssociatePublicIpAddress() { return this._associatePublicIpAddress.HasValue; } /// <summary> /// Gets and sets the property DeleteOnTermination. /// <para> /// If set to <code>true</code>, the interface is deleted when the instance is terminated. /// You can specify <code>true</code> only if creating a new network interface when launching /// an instance. /// </para> /// </summary> public bool DeleteOnTermination { get { return this._deleteOnTermination.GetValueOrDefault(); } set { this._deleteOnTermination = value; } } // Check to see if DeleteOnTermination property is set internal bool IsSetDeleteOnTermination() { return this._deleteOnTermination.HasValue; } /// <summary> /// Gets and sets the property Description. /// <para> /// The description of the network interface. Applies only if creating a network interface /// when launching an instance. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property DeviceIndex. /// <para> /// The index of the device on the instance for the network interface attachment. If you /// are specifying a network interface in a <a>RunInstances</a> request, you must provide /// the device index. /// </para> /// </summary> public int DeviceIndex { get { return this._deviceIndex.GetValueOrDefault(); } set { this._deviceIndex = value; } } // Check to see if DeviceIndex property is set internal bool IsSetDeviceIndex() { return this._deviceIndex.HasValue; } /// <summary> /// Gets and sets the property Groups. /// <para> /// The IDs of the security groups for the network interface. Applies only if creating /// a network interface when launching an instance. /// </para> /// </summary> public List<string> Groups { get { return this._groups; } set { this._groups = value; } } // Check to see if Groups property is set internal bool IsSetGroups() { return this._groups != null && this._groups.Count > 0; } /// <summary> /// Gets and sets the property NetworkInterfaceId. /// <para> /// The ID of the network interface. /// </para> /// </summary> public string NetworkInterfaceId { get { return this._networkInterfaceId; } set { this._networkInterfaceId = value; } } // Check to see if NetworkInterfaceId property is set internal bool IsSetNetworkInterfaceId() { return this._networkInterfaceId != null; } /// <summary> /// Gets and sets the property PrivateIpAddress. /// <para> /// The private IP address of the network interface. Applies only if creating a network /// interface when launching an instance. /// </para> /// </summary> public string PrivateIpAddress { get { return this._privateIpAddress; } set { this._privateIpAddress = value; } } // Check to see if PrivateIpAddress property is set internal bool IsSetPrivateIpAddress() { return this._privateIpAddress != null; } /// <summary> /// Gets and sets the property PrivateIpAddresses. /// <para> /// One or more private IP addresses to assign to the network interface. Only one private /// IP address can be designated as primary. /// </para> /// </summary> public List<PrivateIpAddressSpecification> PrivateIpAddresses { get { return this._privateIpAddresses; } set { this._privateIpAddresses = value; } } // Check to see if PrivateIpAddresses property is set internal bool IsSetPrivateIpAddresses() { return this._privateIpAddresses != null && this._privateIpAddresses.Count > 0; } /// <summary> /// Gets and sets the property SecondaryPrivateIpAddressCount. /// <para> /// The number of secondary private IP addresses. You can't specify this option and specify /// more than one private IP address using the private IP addresses option. /// </para> /// </summary> public int SecondaryPrivateIpAddressCount { get { return this._secondaryPrivateIpAddressCount.GetValueOrDefault(); } set { this._secondaryPrivateIpAddressCount = value; } } // Check to see if SecondaryPrivateIpAddressCount property is set internal bool IsSetSecondaryPrivateIpAddressCount() { return this._secondaryPrivateIpAddressCount.HasValue; } /// <summary> /// Gets and sets the property SubnetId. /// <para> /// The ID of the subnet associated with the network string. Applies only if creating /// a network interface when launching an instance. /// </para> /// </summary> public string SubnetId { get { return this._subnetId; } set { this._subnetId = value; } } // Check to see if SubnetId property is set internal bool IsSetSubnetId() { return this._subnetId != null; } } }
/// QAS Pro Web > (c) Experian > www.edq.com /// Intranet > Bulk Verification > BulkVerifySearch /// Verify the addresses entered > Original address, verification level and verified address if found. namespace Experian.Qas.Prowebintegration { using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Experian.Qas.Proweb; /// <summary> /// Scenario "Bulk Search on the Web" - Bulk Verification /// Verify the addresses in a batch /// display the verify result /// /// Main arrival routes: /// - Initial Bulk Verification: arriving from input page /// /// This page is based on BulkBasePage, which provides functionality common to the scenario /// </summary> public partial class BulkVerifySearch : BulkBase { /* Members and constants */ // Search result (contains either picklist or matched address or nothing) protected BulkSearchResult m_BulkSearchResult = null; // Field name - original input address lines - to ensure we don't re-verify the same address protected const string FIELD_ORIGINAL_INPUT = "OriginalLine"; // Field name - does this picklist item require additional information (refinement) protected const string FIELD_MUST_REFINE = "MustRefine"; /* Methods */ /// <summary> /// Pick up values transfered from other pages /// </summary> private void Page_Load(object sender, System.EventArgs e) { // The following method will do the search and prepare the result for display. BulkVerifyAddress(); } /// <summary> /// Perform a bulk verification search on the input lines /// </summary> /// <param name="tSearchResult">To populate with search results</param> /// <param name="bGoFinalPage">Set true to avoid user interaction & always move to final page </param> /// <returns>Move on to final address page?</returns> protected bool BulkVerifyAddress() { // Results CanSearch canSearch = null; try { // Retrieve settings from web.config string sLayout = GetLayout(); // Verify the address AddressLookup.CurrentEngine.EngineType = Engine.EngineTypes.Verification; AddressLookup.CurrentEngine.Flatten = true; canSearch = AddressLookup.CanSearch(DataID, sLayout, null); if (!canSearch.IsOk) { base.SetRoute(Constants.Routes.PreSearchFailed); base.SetErrorInfo(canSearch.ErrorMessage); } else { m_BulkSearchResult = AddressLookup.BulkSearch(DataID, GetBulkInputAddress, PromptSet.Types.Default, sLayout); base.SetRoute (Constants.Routes.Okay); } } catch (Exception x) { base.SetRoute(Constants.Routes.Failed); base.SetErrorInfo(x.Message); } return true; } protected IList<string> GetBulkInputAddress { get { IList<string> searches; string[] asInputAddress; asInputAddress = Request.Form.GetValues(Constants.FIELD_INPUT_LINES); Regex match = new Regex ("[\\r\\n\\\\]+"); searches = new List<string>(match.Split(asInputAddress[0].Trim())); base.SetRoute(Constants.Routes.Failed); base.SetErrorInfo(searches[0]); return searches; } } /// <summary> /// Provide member-wise string array comparison /// </summary> /// <param name="asLHS">First argument, left-hand side</param> /// <param name="asRHS">Second argument, right-hand side</param> /// <returns>Are the two string arrays equal, member-by-member</returns> public static bool Equals(string[] asLHS, string[] asRHS) { if (asLHS.Length != asRHS.Length) { return false; } // Same length. Now compare them, member-by-member for (int iIndex = 0; iIndex < asLHS.Length; ++iIndex) { if (asLHS[iIndex] != asRHS[iIndex]) { return false; } } return true; } /// <summary> /// Must the picklist item be refined (text added) to form a final address? /// </summary> protected static bool MustRefine(PicklistItem item) { return (item.IsIncompleteAddress || item.IsUnresolvableRange || item.IsPhantomPrimaryPoint); } /** Page events **/ #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion /** Page parameters **/ // Country data identifier (i.e. AUS) protected string DataID { get { return Request[Constants.FIELD_DATA_ID]; } } // Read-only properties public BulkSearchItem[] BulkSearchItems { get { return m_BulkSearchResult.BulkSearchItems.ToArray(); } } public string BulkOriginalAddress(int iIndex) { if (iIndex >= m_BulkSearchResult.BulkSearchItems.Count) { return "Index out of range for original address " + iIndex.ToString(); } else { return m_BulkSearchResult.BulkSearchItems[iIndex].InputAddress; } } public VerificationLevel BulkVerifyLevel(int iIndex) { if (iIndex >= m_BulkSearchResult.BulkSearchItems.Count) { return VerificationLevel.None; } else { return m_BulkSearchResult.BulkSearchItems[iIndex].VerifyLevel; } } public FormattedAddress BulkFormattedAddress(int iIndex) { if (iIndex >= m_BulkSearchResult.BulkSearchItems.Count) { return null; } else { return m_BulkSearchResult.BulkSearchItems[iIndex].Address; } } public int Count { get { if (m_BulkSearchResult == null || m_BulkSearchResult.BulkSearchItems == null) return 0; else return m_BulkSearchResult.BulkSearchItems.Count; } } public int FormattedAddressLength(int iIndex) { if (iIndex >= m_BulkSearchResult.BulkSearchItems.Count) { return 0; } else { if (m_BulkSearchResult.BulkSearchItems[iIndex].Address != null) { return m_BulkSearchResult.BulkSearchItems[iIndex].Address.AddressLines.Count; } else { return 0; } } } public int ErrorCode() { return m_BulkSearchResult.ErrorCode; } public string ErrorMessage() { return m_BulkSearchResult.ErrorMessage; } } }
// Copyright (C) 2014 dot42 // // Original filename: PatternParser.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Diagnostics; namespace System.Text.RegularExpressions.Internal { internal class PatternParser { private enum EscapeState { None, Escape, // \ NumberedBackReference, // \number (0-79) StartNamedBackReference, // \k NamedBackReference // \k< } private enum CommentsState { None, CommentsLine, // # if IgnorePatternWhitespace = on CommentsGroup, // (# } private enum PatternState { Other, // SubPattern, Modifiers StartCharacterClass, // [ or [^ CharacterClass, // [... or [^... StartGroup, // ( StartExtendedGroup, // (? // NonCaptureGroup, // (?: -> Other NamedCaptureGroupQuote, // (?' StartNamedCaptureGroupAngleBracket, // (?< // PositiveLookBehind, // (?<= -> Other // NegativeLookBehind, // (?<! -> Other NamedCaptureGroupAngleBracket // (?< and not the two above. } private readonly string pattern; private readonly bool ignorePatternWhitespace; private readonly bool explicitCapture; private int currentIndex = 0; private List<ParserItem> parserItems = new List<ParserItem>(); private EscapeState escapeState = EscapeState.None; private CommentsState commentsState = CommentsState.None; private PatternState patternState = PatternState.Other; private PatternState previousPatternState = PatternState.Other; private int groupLevel = 0; // () private int escapeStartIndex = -1; private int startGroupIndex = -1; private int previousStartGroupIndex = -1; private int startNamedIndex = -1; private int number = 0; public PatternParser(string pattern, bool ignorePatternWhitespace, bool explicitCapture) { this.pattern = pattern; this.ignorePatternWhitespace = ignorePatternWhitespace; this.explicitCapture = explicitCapture; } public List<ParserItem> Parse() { while (currentIndex < pattern.Length) { var newToken = pattern[currentIndex]; EvalEscapeState(newToken); currentIndex++; } if (escapeState == EscapeState.NumberedBackReference) { //handle escape EvalEscapeState(' '); } if (groupLevel != 0) throw new Exception("Unbalanced () found"); if (patternState == PatternState.StartCharacterClass || patternState == PatternState.CharacterClass ) throw new Exception("Unbalanced [] found"); if (patternState != PatternState.Other) throw new Exception("Pattern state ended in invalid state : " + (int)patternState); if (escapeState != EscapeState.None) throw new Exception("Escape state ended in invalid state : " + (int)escapeState); return parserItems; } private void EvalEscapeState(char token) { switch (escapeState) { case EscapeState.None: if(token == '\\') { escapeState = EscapeState.Escape; escapeStartIndex = currentIndex; } else { EvalCommentsState(token, false); } break; case EscapeState.Escape: // \ if (token == 'k') { escapeState = EscapeState.StartNamedBackReference; } else if (char.IsDigit(token)) { escapeState = EscapeState.NumberedBackReference; number = int.Parse(token.ToString()); EvalCommentsState(token, true); } else { EvalCommentsState(token, true); escapeState = EscapeState.None; } break; case EscapeState.NumberedBackReference: // \number if (char.IsDigit(token)) { number = 10 * number + int.Parse(token.ToString()); } else { NumberedBackReferenceFound(escapeStartIndex, currentIndex, number); escapeState = EscapeState.None; EvalCommentsState(token, false); } break; case EscapeState.StartNamedBackReference: if(token == '<') { escapeState = EscapeState.NamedBackReference; startNamedIndex = currentIndex+1; } else { escapeState = EscapeState.None; EvalCommentsState(token, false); } break; case EscapeState.NamedBackReference: // \k<name> if(token == '>') { NamedBackReferenceFound(escapeStartIndex, currentIndex+1, GetName(startNamedIndex, currentIndex)); escapeState = EscapeState.None; } //else we are inside the name, continue break; } } private void EvalCommentsState(char token, bool escaped) { switch (commentsState) { case CommentsState.None: if (!escaped) { if (token == '#') { if (patternState == PatternState.StartGroup) { commentsState = CommentsState.CommentsGroup; } else if (ignorePatternWhitespace) { commentsState = CommentsState.CommentsLine; } else { EvalGroupState(token, escaped); } } else { EvalGroupState(token, escaped); } } else { EvalGroupState(token, escaped); } break; case CommentsState.CommentsLine: if(token == 'n' && escaped) { commentsState = CommentsState.None; } break; case CommentsState.CommentsGroup: if (token == ')' && !escaped) { CommentsGroupFound(startGroupIndex, currentIndex+1); groupLevel--; patternState = previousPatternState; startGroupIndex = previousStartGroupIndex; commentsState = CommentsState.None; } break; } } private void EvalGroupState(char token, bool escaped) { if (!escaped) { if (patternState != PatternState.StartCharacterClass && patternState != PatternState.CharacterClass) { switch (token) { case '(': previousPatternState = patternState; patternState = PatternState.StartGroup; previousStartGroupIndex = startGroupIndex; startGroupIndex = currentIndex; groupLevel++; if (previousPatternState == PatternState.StartGroup) // (( { NumberedCaptureGroupFound(previousStartGroupIndex, currentIndex); } return; case ')': groupLevel--; return; default: //see switch below break; } } switch (patternState) { case PatternState.Other: // Pattern, Modifiers switch (token) { case '[': patternState = PatternState.StartCharacterClass; break; } break; case PatternState.StartCharacterClass: if (token != '^') patternState = PatternState.CharacterClass; break; case PatternState.CharacterClass: if (token == ']') patternState = PatternState.Other; break; case PatternState.StartGroup: // ( if (token == '?') { patternState = PatternState.StartExtendedGroup; } else { if (previousPatternState == PatternState.StartExtendedGroup) { ConditionFound(currentIndex); } else { NumberedCaptureGroupFound(startGroupIndex, currentIndex); } patternState = token == '[' ? PatternState.StartCharacterClass : PatternState.Other; } break; case PatternState.StartExtendedGroup: // (? // NonCaptureGroup: // (?: -> Other switch (token) { case '\'': patternState = PatternState.NamedCaptureGroupQuote; startNamedIndex = currentIndex + 1; break; case '<': patternState = PatternState.StartNamedCaptureGroupAngleBracket; startNamedIndex = currentIndex + 1; break; default: patternState = PatternState.Other; break; } break; case PatternState.NamedCaptureGroupQuote: // (?' if (token == '\'') { NamedCaptureGroupFound(startGroupIndex, currentIndex + 1, GetName(startNamedIndex, currentIndex)); patternState = PatternState.Other; } //else we are inside the name break; case PatternState.StartNamedCaptureGroupAngleBracket: // (?< // PositiveLookBehind: // (?<= -> Other // NegativeLookBehind: // (?<! -> Other if (token == '=' || token == '!') { patternState = PatternState.Other; } else { patternState = PatternState.NamedCaptureGroupAngleBracket; } break; case PatternState.NamedCaptureGroupAngleBracket: if (token == '>') { NamedCaptureGroupFound(startGroupIndex, currentIndex + 1, GetName(startNamedIndex, currentIndex)); patternState = PatternState.Other; } //else we are inside the name break; default: throw new NotSupportedException("Unknown group state"); } } else { switch (patternState) { case PatternState.StartCharacterClass: patternState = PatternState.CharacterClass; break; case PatternState.StartExtendedGroup: patternState = PatternState.Other; break; case PatternState.StartGroup: if (previousPatternState == PatternState.StartExtendedGroup) { ConditionFound(currentIndex-1); } else { NumberedCaptureGroupFound(startGroupIndex, currentIndex-1); } patternState = PatternState.Other; break; case PatternState.StartNamedCaptureGroupAngleBracket: patternState = PatternState.NamedCaptureGroupAngleBracket; break; } } } private string GetName(int startIndex, int endIndex) { return pattern.Substring(startIndex, endIndex - startIndex); } private void NumberedCaptureGroupFound(int startIndex, int endIndex) { Debug.WriteLine("NumberedCaptureGroupFound [startAt={0}]: {1}", startIndex, GetName(startIndex, endIndex)); if (explicitCapture) { parserItems.Add(new NumberedAsNonCaptureGroup(startIndex, endIndex)); } else { parserItems.Add(new NumberedCaptureGroup(startIndex, endIndex)); } } private void NamedCaptureGroupFound(int startIndex, int endIndex, string name) { Debug.WriteLine("NamedCaptureGroupFound [startAt={0} {1}]: {2}", startIndex, name, GetName(startIndex, endIndex)); parserItems.Add(new NamedCaptureGroup(startIndex, endIndex, name)); } private void CommentsGroupFound(int startIndex, int endIndex) { Debug.WriteLine("CommentsGroupFound: " + GetName(startIndex, endIndex)); parserItems.Add(new CommentsGroup(startIndex, endIndex)); } private void ConditionFound(int startIndex) { Debug.WriteLine("ConditionFound at index: {0}", startIndex); parserItems.Add(new Condition(startIndex, -1)); } private void NumberedBackReferenceFound(int startIndex, int endIndex, int refNumber) { Debug.WriteLine("NumberedBackReferenceFound [{1}]: {0}", GetName(startIndex, endIndex), number); parserItems.Add(new NumberedBackReference(startIndex, endIndex, refNumber)); } private void NamedBackReferenceFound(int startIndex, int endIndex, string name) { Debug.WriteLine("NamedBackReferenceFound [{1}]: {0}", GetName(startIndex, endIndex), name); parserItems.Add(new NamedBackReference(startIndex, endIndex, name)); } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleWorkflow.Model { /// <summary> /// Container for the parameters to the TerminateWorkflowExecution operation. /// <para> Records a <c>WorkflowExecutionTerminated</c> event and forces closure of the workflow execution identified by the given domain, /// runId, and workflowId. The child policy, registered with the workflow type or specified when starting this execution, is applied to any open /// child workflow executions of this workflow execution. </para> <para><b>IMPORTANT:</b> If the identified workflow execution was in progress, /// it is terminated immediately. </para> <para><b>NOTE:</b> If a runId is not specified, then the WorkflowExecutionTerminated event is recorded /// in the history of the current open workflow with the matching workflowId in the domain. </para> <para><b>NOTE:</b> You should consider using /// RequestCancelWorkflowExecution action instead because it allows the workflow to gracefully close while TerminateWorkflowExecution does not. /// </para> <para> <b>Access Control</b> </para> <para>You can use IAM policies to control this action's access to Amazon SWF resources as /// follows:</para> /// <ul> /// <li>Use a <c>Resource</c> element with the domain name to limit the action to only specified domains.</li> /// <li>Use an <c>Action</c> element to allow or deny permission to call this action.</li> /// <li>You cannot use an IAM policy to constrain this action's parameters.</li> /// /// </ul> /// <para>If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified /// constraints, the action fails by throwing <c>OperationNotPermitted</c> . For details and example IAM policies, see Using IAM to Manage /// Access to Amazon SWF Workflows.</para> /// </summary> /// <seealso cref="Amazon.SimpleWorkflow.AmazonSimpleWorkflow.TerminateWorkflowExecution"/> public class TerminateWorkflowExecutionRequest : AmazonWebServiceRequest { private string domain; private string workflowId; private string runId; private string reason; private string details; private string childPolicy; /// <summary> /// The domain of the workflow execution to terminate. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 256</description> /// </item> /// </list> /// </para> /// </summary> public string Domain { get { return this.domain; } set { this.domain = value; } } /// <summary> /// Sets the Domain property /// </summary> /// <param name="domain">The value to set for the Domain property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateWorkflowExecutionRequest WithDomain(string domain) { this.domain = domain; return this; } // Check to see if Domain property is set internal bool IsSetDomain() { return this.domain != null; } /// <summary> /// The workflowId of the workflow execution to terminate. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 256</description> /// </item> /// </list> /// </para> /// </summary> public string WorkflowId { get { return this.workflowId; } set { this.workflowId = value; } } /// <summary> /// Sets the WorkflowId property /// </summary> /// <param name="workflowId">The value to set for the WorkflowId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateWorkflowExecutionRequest WithWorkflowId(string workflowId) { this.workflowId = workflowId; return this; } // Check to see if WorkflowId property is set internal bool IsSetWorkflowId() { return this.workflowId != null; } /// <summary> /// The runId of the workflow execution to terminate. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 64</description> /// </item> /// </list> /// </para> /// </summary> public string RunId { get { return this.runId; } set { this.runId = value; } } /// <summary> /// Sets the RunId property /// </summary> /// <param name="runId">The value to set for the RunId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateWorkflowExecutionRequest WithRunId(string runId) { this.runId = runId; return this; } // Check to see if RunId property is set internal bool IsSetRunId() { return this.runId != null; } /// <summary> /// An optional descriptive reason for terminating the workflow execution. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 256</description> /// </item> /// </list> /// </para> /// </summary> public string Reason { get { return this.reason; } set { this.reason = value; } } /// <summary> /// Sets the Reason property /// </summary> /// <param name="reason">The value to set for the Reason property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateWorkflowExecutionRequest WithReason(string reason) { this.reason = reason; return this; } // Check to see if Reason property is set internal bool IsSetReason() { return this.reason != null; } /// <summary> /// Optional details for terminating the workflow execution. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 32768</description> /// </item> /// </list> /// </para> /// </summary> public string Details { get { return this.details; } set { this.details = value; } } /// <summary> /// Sets the Details property /// </summary> /// <param name="details">The value to set for the Details property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateWorkflowExecutionRequest WithDetails(string details) { this.details = details; return this; } // Check to see if Details property is set internal bool IsSetDetails() { return this.details != null; } /// <summary> /// If set, specifies the policy to use for the child workflow executions of the workflow execution being terminated. This policy overrides the /// child policy specified for the workflow execution at registration time or when starting the execution. The supported child policies are: /// <ul> <li><b>TERMINATE:</b> the child executions will be terminated.</li> <li><b>REQUEST_CANCEL:</b> a request to cancel will be attempted /// for each child execution by recording a <c>WorkflowExecutionCancelRequested</c> event in its history. It is up to the decider to take /// appropriate actions when it receives an execution history with this event. </li> <li><b>ABANDON:</b> no action will be taken. The child /// executions will continue to run.</li> </ul> <note>A child policy for this workflow execution must be specified either as a default for the /// workflow type or through this parameter. If neither this parameter is set nor a default child policy was specified at registration time, a /// fault will be returned.</note> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>TERMINATE, REQUEST_CANCEL, ABANDON</description> /// </item> /// </list> /// </para> /// </summary> public string ChildPolicy { get { return this.childPolicy; } set { this.childPolicy = value; } } /// <summary> /// Sets the ChildPolicy property /// </summary> /// <param name="childPolicy">The value to set for the ChildPolicy property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateWorkflowExecutionRequest WithChildPolicy(string childPolicy) { this.childPolicy = childPolicy; return this; } // Check to see if ChildPolicy property is set internal bool IsSetChildPolicy() { return this.childPolicy != null; } } }
// <copyright file="Cookie.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { /// <summary> /// Represents a cookie in the browser. /// </summary> [Serializable] [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class Cookie { private string cookieName; private string cookieValue; private string cookiePath; private string cookieDomain; private DateTime? cookieExpiry; /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, domain, path and expiration date. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="domain">The domain of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <param name="expiry">The expiration date of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string domain, string path, DateTime? expiry) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Cookie name cannot be null or empty string", "name"); } if (value == null) { throw new ArgumentNullException("value", "Cookie value cannot be null"); } if (name.IndexOf(';') != -1) { throw new ArgumentException("Cookie names cannot contain a ';': " + name, "name"); } this.cookieName = name; this.cookieValue = value; if (!string.IsNullOrEmpty(path)) { this.cookiePath = path; } this.cookieDomain = StripPort(domain); if (expiry != null) { this.cookieExpiry = expiry; } } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, path and expiration date. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <param name="expiry">The expiration date of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string path, DateTime? expiry) : this(name, value, null, path, expiry) { } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, and path. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string path) : this(name, value, path, null) { } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name and value. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value) : this(name, value, null, null) { } /// <summary> /// Gets the name of the cookie. /// </summary> [JsonProperty("name")] public string Name { get { return this.cookieName; } } /// <summary> /// Gets the value of the cookie. /// </summary> [JsonProperty("value")] public string Value { get { return this.cookieValue; } } /// <summary> /// Gets the domain of the cookie. /// </summary> [JsonProperty("domain", NullValueHandling = NullValueHandling.Ignore)] public string Domain { get { return this.cookieDomain; } } /// <summary> /// Gets the path of the cookie. /// </summary> [JsonProperty("path", NullValueHandling = NullValueHandling.Ignore)] public virtual string Path { get { return this.cookiePath; } } /// <summary> /// Gets a value indicating whether the cookie is secure. /// </summary> [JsonProperty("secure")] public virtual bool Secure { get { return false; } } /// <summary> /// Gets the expiration date of the cookie. /// </summary> public DateTime? Expiry { get { return this.cookieExpiry; } } /// <summary> /// Gets the cookie expiration date in seconds from the defined zero date (01 January 1970 00:00:00 UTC). /// </summary> /// <remarks>This property only exists so that the JSON serializer can serialize a /// cookie without resorting to a custom converter.</remarks> [JsonProperty("expiry", NullValueHandling = NullValueHandling.Ignore)] internal long? ExpirySeconds { get { if (this.cookieExpiry == null) { return null; } DateTime zeroDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); TimeSpan span = this.cookieExpiry.Value.ToUniversalTime().Subtract(zeroDate); return Convert.ToInt64(span.TotalSeconds); } } /// <summary> /// Converts a Dictionary to a Cookie. /// </summary> /// <param name="rawCookie">The Dictionary object containing the cookie parameters.</param> /// <returns>A <see cref="Cookie"/> object with the proper parameters set.</returns> public static Cookie FromDictionary(Dictionary<string, object> rawCookie) { if (rawCookie == null) { throw new ArgumentNullException("rawCookie", "Dictionary cannot be null"); } string name = rawCookie["name"].ToString(); string value = rawCookie["value"].ToString(); string path = "/"; if (rawCookie.ContainsKey("path") && rawCookie["path"] != null) { path = rawCookie["path"].ToString(); } string domain = string.Empty; if (rawCookie.ContainsKey("domain") && rawCookie["domain"] != null) { domain = rawCookie["domain"].ToString(); } DateTime? expires = null; if (rawCookie.ContainsKey("expiry") && rawCookie["expiry"] != null) { long seconds = 0; if (long.TryParse(rawCookie["expiry"].ToString(), out seconds)) { try { expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds).ToLocalTime(); } catch (ArgumentOutOfRangeException) { expires = DateTime.MaxValue.ToLocalTime(); } } } bool secure = false; if (rawCookie.ContainsKey("secure") && rawCookie["secure"] != null) { secure = bool.Parse(rawCookie["secure"].ToString()); } return new ReturnedCookie(name, value, domain, path, expires, secure); } /// <summary> /// Creates and returns a string representation of the cookie. /// </summary> /// <returns>A string representation of the cookie.</returns> public override string ToString() { return this.cookieName + "=" + this.cookieValue + (this.cookieExpiry == null ? string.Empty : "; expires=" + this.cookieExpiry.Value.ToUniversalTime().ToString("ddd MM dd yyyy hh:mm:ss UTC", CultureInfo.InvariantCulture)) + (string.IsNullOrEmpty(this.cookiePath) ? string.Empty : "; path=" + this.cookiePath) + (string.IsNullOrEmpty(this.cookieDomain) ? string.Empty : "; domain=" + this.cookieDomain); //// + (isSecure ? ";secure;" : ""); } /// <summary> /// Determines whether the specified <see cref="System.Object">Object</see> is equal /// to the current <see cref="System.Object">Object</see>. /// </summary> /// <param name="obj">The <see cref="System.Object">Object</see> to compare with the /// current <see cref="System.Object">Object</see>.</param> /// <returns><see langword="true"/> if the specified <see cref="System.Object">Object</see> /// is equal to the current <see cref="System.Object">Object</see>; otherwise, /// <see langword="false"/>.</returns> public override bool Equals(object obj) { // Two cookies are equal if the name and value match Cookie cookie = obj as Cookie; if (this == obj) { return true; } if (cookie == null) { return false; } if (!this.cookieName.Equals(cookie.cookieName)) { return false; } return !(this.cookieValue != null ? !this.cookieValue.Equals(cookie.cookieValue) : cookie.Value != null); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns>A hash code for the current <see cref="System.Object">Object</see>.</returns> public override int GetHashCode() { return this.cookieName.GetHashCode(); } private static string StripPort(string domain) { return string.IsNullOrEmpty(domain) ? null : domain.Split(':')[0]; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // zlib.h -- interface of the 'zlib' general purpose compression library // version 1.2.1, November 17th, 2003 // // Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // using System.Diagnostics; namespace System.IO.Compression { internal class InflaterManaged : IInflater { // const tables used in decoding: // Extra bits for length code 257 - 285. private static readonly byte[] s_extraLengthBits = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; // The base length for length code 257 - 285. // The formula to get the real length for a length code is lengthBase[code - 257] + (value stored in extraBits) private static readonly int[] s_lengthBase = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258}; // The base distance for distance code 0 - 29 // The real distance for a distance code is distanceBasePosition[code] + (value stored in extraBits) private static readonly int[] s_distanceBasePosition = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; // code lengths for code length alphabet is stored in following order private static readonly byte[] s_codeOrder = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; private static readonly byte[] s_staticDistanceTreeTable = { 0x00,0x10,0x08,0x18,0x04,0x14,0x0c,0x1c,0x02,0x12,0x0a,0x1a, 0x06,0x16,0x0e,0x1e,0x01,0x11,0x09,0x19,0x05,0x15,0x0d,0x1d, 0x03,0x13,0x0b,0x1b,0x07,0x17,0x0f,0x1f, }; private OutputWindow _output; private InputBuffer _input; private HuffmanTree _literalLengthTree; private HuffmanTree _distanceTree; private InflaterState _state; private bool _hasFormatReader; private int _bfinal; private BlockType _blockType; // uncompressed block private byte[] _blockLengthBuffer = new byte[4]; private int _blockLength; // compressed block private int _length; private int _distanceCode; private int _extraBits; private int _loopCounter; private int _literalLengthCodeCount; private int _distanceCodeCount; private int _codeLengthCodeCount; private int _codeArraySize; private int _lengthCode; private byte[] _codeList; // temporary array to store the code length for literal/Length and distance private byte[] _codeLengthTreeCodeLength; private HuffmanTree _codeLengthTree; private IFileFormatReader _formatReader; // class to decode header and footer (e.g. gzip) public InflaterManaged() { _output = new OutputWindow(); _input = new InputBuffer(); _codeList = new byte[HuffmanTree.MaxLiteralTreeElements + HuffmanTree.MaxDistTreeElements]; _codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements]; Reset(); } internal InflaterManaged(IFileFormatReader reader) { _output = new OutputWindow(); _input = new InputBuffer(); _codeList = new byte[HuffmanTree.MaxLiteralTreeElements + HuffmanTree.MaxDistTreeElements]; _codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements]; if (reader != null) { _formatReader = reader; _hasFormatReader = true; } Reset(); } public void SetFileFormatReader(IFileFormatReader reader) { _formatReader = reader; _hasFormatReader = true; Reset(); } private void Reset() { if (_hasFormatReader) { _state = InflaterState.ReadingHeader; // start by reading Header info } else { _state = InflaterState.ReadingBFinal; // start by reading BFinal bit } } public void SetInput(byte[] inputBytes, int offset, int length) { _input.SetInput(inputBytes, offset, length); // append the bytes } public bool Finished() { return (_state == InflaterState.Done || _state == InflaterState.VerifyingFooter); } public int AvailableOutput { get { return _output.AvailableBytes; } } public bool NeedsInput() { return _input.NeedsInput(); } public int Inflate(byte[] bytes, int offset, int length) { // copy bytes from output to outputbytes if we have available bytes // if buffer is not filled up. keep decoding until no input are available // if decodeBlock returns false. Throw an exception. int count = 0; do { int copied = _output.CopyTo(bytes, offset, length); if (copied > 0) { if (_hasFormatReader) { _formatReader.UpdateWithBytesRead(bytes, offset, copied); } offset += copied; count += copied; length -= copied; } if (length == 0) { // filled in the bytes array break; } // Decode will return false when more input is needed } while (!Finished() && Decode()); if (_state == InflaterState.VerifyingFooter) { // finished reading CRC // In this case finished is true and output window has all the data. // But some data in output window might not be copied out. if (_output.AvailableBytes == 0) { _formatReader.Validate(); } } return count; } //Each block of compressed data begins with 3 header bits // containing the following data: // first bit BFINAL // next 2 bits BTYPE // Note that the header bits do not necessarily begin on a byte // boundary, since a block does not necessarily occupy an integral // number of bytes. // BFINAL is set if and only if this is the last block of the data // set. // BTYPE specifies how the data are compressed, as follows: // 00 - no compression // 01 - compressed with fixed Huffman codes // 10 - compressed with dynamic Huffman codes // 11 - reserved (error) // The only difference between the two compressed cases is how the // Huffman codes for the literal/length and distance alphabets are // defined. // // This function returns true for success (end of block or output window is full,) // false if we are short of input // private bool Decode() { bool eob = false; bool result = false; if (Finished()) { return true; } if (_hasFormatReader) { if (_state == InflaterState.ReadingHeader) { if (!_formatReader.ReadHeader(_input)) { return false; } _state = InflaterState.ReadingBFinal; } else if (_state == InflaterState.StartReadingFooter || _state == InflaterState.ReadingFooter) { if (!_formatReader.ReadFooter(_input)) return false; _state = InflaterState.VerifyingFooter; return true; } } if (_state == InflaterState.ReadingBFinal) { // reading bfinal bit // Need 1 bit if (!_input.EnsureBitsAvailable(1)) return false; _bfinal = _input.GetBits(1); _state = InflaterState.ReadingBType; } if (_state == InflaterState.ReadingBType) { // Need 2 bits if (!_input.EnsureBitsAvailable(2)) { _state = InflaterState.ReadingBType; return false; } _blockType = (BlockType)_input.GetBits(2); if (_blockType == BlockType.Dynamic) { _state = InflaterState.ReadingNumLitCodes; } else if (_blockType == BlockType.Static) { _literalLengthTree = HuffmanTree.StaticLiteralLengthTree; _distanceTree = HuffmanTree.StaticDistanceTree; _state = InflaterState.DecodeTop; } else if (_blockType == BlockType.Uncompressed) { _state = InflaterState.UncompressedAligning; } else { throw new InvalidDataException(SR.UnknownBlockType); } } if (_blockType == BlockType.Dynamic) { if (_state < InflaterState.DecodeTop) { // we are reading the header result = DecodeDynamicBlockHeader(); } else { result = DecodeBlock(out eob); // this can returns true when output is full } } else if (_blockType == BlockType.Static) { result = DecodeBlock(out eob); } else if (_blockType == BlockType.Uncompressed) { result = DecodeUncompressedBlock(out eob); } else { throw new InvalidDataException(SR.UnknownBlockType); } // // If we reached the end of the block and the block we were decoding had // bfinal=1 (final block) // if (eob && (_bfinal != 0)) { if (_hasFormatReader) _state = InflaterState.StartReadingFooter; else _state = InflaterState.Done; } return result; } // Format of Non-compressed blocks (BTYPE=00): // // Any bits of input up to the next byte boundary are ignored. // The rest of the block consists of the following information: // // 0 1 2 3 4... // +---+---+---+---+================================+ // | LEN | NLEN |... LEN bytes of literal data...| // +---+---+---+---+================================+ // // LEN is the number of data bytes in the block. NLEN is the // one's complement of LEN. private bool DecodeUncompressedBlock(out bool end_of_block) { end_of_block = false; while (true) { switch (_state) { case InflaterState.UncompressedAligning: // intial state when calling this function // we must skip to a byte boundary _input.SkipToByteBoundary(); _state = InflaterState.UncompressedByte1; goto case InflaterState.UncompressedByte1; case InflaterState.UncompressedByte1: // decoding block length case InflaterState.UncompressedByte2: case InflaterState.UncompressedByte3: case InflaterState.UncompressedByte4: int bits = _input.GetBits(8); if (bits < 0) { return false; } _blockLengthBuffer[_state - InflaterState.UncompressedByte1] = (byte)bits; if (_state == InflaterState.UncompressedByte4) { _blockLength = _blockLengthBuffer[0] + ((int)_blockLengthBuffer[1]) * 256; int blockLengthComplement = _blockLengthBuffer[2] + ((int)_blockLengthBuffer[3]) * 256; // make sure complement matches if ((ushort)_blockLength != (ushort)(~blockLengthComplement)) { throw new InvalidDataException(SR.InvalidBlockLength); } } _state += 1; break; case InflaterState.DecodingUncompressed: // copying block data // Directly copy bytes from input to output. int bytesCopied = _output.CopyFrom(_input, _blockLength); _blockLength -= bytesCopied; if (_blockLength == 0) { // Done with this block, need to re-init bit buffer for next block _state = InflaterState.ReadingBFinal; end_of_block = true; return true; } // We can fail to copy all bytes for two reasons: // Running out of Input // running out of free space in output window if (_output.FreeBytes == 0) { return true; } return false; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.UnknownState); } } } private bool DecodeBlock(out bool end_of_block_code_seen) { end_of_block_code_seen = false; int freeBytes = _output.FreeBytes; // it is a little bit faster than frequently accessing the property while (freeBytes > 258) { // 258 means we can safely do decoding since maximum repeat length is 258 int symbol; switch (_state) { case InflaterState.DecodeTop: // decode an element from the literal tree // TODO: optimize this!!! symbol = _literalLengthTree.GetNextSymbol(_input); if (symbol < 0) { // running out of input return false; } if (symbol < 256) { // literal _output.Write((byte)symbol); --freeBytes; } else if (symbol == 256) { // end of block end_of_block_code_seen = true; // Reset state _state = InflaterState.ReadingBFinal; return true; // *********** } else { // length/distance pair symbol -= 257; // length code started at 257 if (symbol < 8) { symbol += 3; // match length = 3,4,5,6,7,8,9,10 _extraBits = 0; } else if (symbol == 28) { // extra bits for code 285 is 0 symbol = 258; // code 285 means length 258 _extraBits = 0; } else { if (symbol < 0 || symbol >= s_extraLengthBits.Length) { throw new InvalidDataException(SR.GenericInvalidData); } _extraBits = s_extraLengthBits[symbol]; Debug.Assert(_extraBits != 0, "We handle other cases seperately!"); } _length = symbol; goto case InflaterState.HaveInitialLength; } break; case InflaterState.HaveInitialLength: if (_extraBits > 0) { _state = InflaterState.HaveInitialLength; int bits = _input.GetBits(_extraBits); if (bits < 0) { return false; } if (_length < 0 || _length >= s_lengthBase.Length) { throw new InvalidDataException(SR.GenericInvalidData); } _length = s_lengthBase[_length] + bits; } _state = InflaterState.HaveFullLength; goto case InflaterState.HaveFullLength; case InflaterState.HaveFullLength: if (_blockType == BlockType.Dynamic) { _distanceCode = _distanceTree.GetNextSymbol(_input); } else { // get distance code directly for static block _distanceCode = _input.GetBits(5); if (_distanceCode >= 0) { _distanceCode = s_staticDistanceTreeTable[_distanceCode]; } } if (_distanceCode < 0) { // running out input return false; } _state = InflaterState.HaveDistCode; goto case InflaterState.HaveDistCode; case InflaterState.HaveDistCode: // To avoid a table lookup we note that for distanceCode >= 2, // extra_bits = (distanceCode-2) >> 1 int offset; if (_distanceCode > 3) { _extraBits = (_distanceCode - 2) >> 1; int bits = _input.GetBits(_extraBits); if (bits < 0) { return false; } offset = s_distanceBasePosition[_distanceCode] + bits; } else { offset = _distanceCode + 1; } Debug.Assert(freeBytes >= 258, "following operation is not safe!"); _output.WriteLengthDistance(_length, offset); freeBytes -= _length; _state = InflaterState.DecodeTop; break; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.UnknownState); } } return true; } // Format of the dynamic block header: // 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286) // 5 Bits: HDIST, # of Distance codes - 1 (1 - 32) // 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19) // // (HCLEN + 4) x 3 bits: code lengths for the code length // alphabet given just above, in the order: 16, 17, 18, // 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 // // These code lengths are interpreted as 3-bit integers // (0-7); as above, a code length of 0 means the // corresponding symbol (literal/length or distance code // length) is not used. // // HLIT + 257 code lengths for the literal/length alphabet, // encoded using the code length Huffman code // // HDIST + 1 code lengths for the distance alphabet, // encoded using the code length Huffman code // // The code length repeat codes can cross from HLIT + 257 to the // HDIST + 1 code lengths. In other words, all code lengths form // a single sequence of HLIT + HDIST + 258 values. private bool DecodeDynamicBlockHeader() { switch (_state) { case InflaterState.ReadingNumLitCodes: _literalLengthCodeCount = _input.GetBits(5); if (_literalLengthCodeCount < 0) { return false; } _literalLengthCodeCount += 257; _state = InflaterState.ReadingNumDistCodes; goto case InflaterState.ReadingNumDistCodes; case InflaterState.ReadingNumDistCodes: _distanceCodeCount = _input.GetBits(5); if (_distanceCodeCount < 0) { return false; } _distanceCodeCount += 1; _state = InflaterState.ReadingNumCodeLengthCodes; goto case InflaterState.ReadingNumCodeLengthCodes; case InflaterState.ReadingNumCodeLengthCodes: _codeLengthCodeCount = _input.GetBits(4); if (_codeLengthCodeCount < 0) { return false; } _codeLengthCodeCount += 4; _loopCounter = 0; _state = InflaterState.ReadingCodeLengthCodes; goto case InflaterState.ReadingCodeLengthCodes; case InflaterState.ReadingCodeLengthCodes: while (_loopCounter < _codeLengthCodeCount) { int bits = _input.GetBits(3); if (bits < 0) { return false; } _codeLengthTreeCodeLength[s_codeOrder[_loopCounter]] = (byte)bits; ++_loopCounter; } for (int i = _codeLengthCodeCount; i < s_codeOrder.Length; i++) { _codeLengthTreeCodeLength[s_codeOrder[i]] = 0; } // create huffman tree for code length _codeLengthTree = new HuffmanTree(_codeLengthTreeCodeLength); _codeArraySize = _literalLengthCodeCount + _distanceCodeCount; _loopCounter = 0; // reset loop count _state = InflaterState.ReadingTreeCodesBefore; goto case InflaterState.ReadingTreeCodesBefore; case InflaterState.ReadingTreeCodesBefore: case InflaterState.ReadingTreeCodesAfter: while (_loopCounter < _codeArraySize) { if (_state == InflaterState.ReadingTreeCodesBefore) { if ((_lengthCode = _codeLengthTree.GetNextSymbol(_input)) < 0) { return false; } } // The alphabet for code lengths is as follows: // 0 - 15: Represent code lengths of 0 - 15 // 16: Copy the previous code length 3 - 6 times. // The next 2 bits indicate repeat length // (0 = 3, ... , 3 = 6) // Example: Codes 8, 16 (+2 bits 11), // 16 (+2 bits 10) will expand to // 12 code lengths of 8 (1 + 6 + 5) // 17: Repeat a code length of 0 for 3 - 10 times. // (3 bits of length) // 18: Repeat a code length of 0 for 11 - 138 times // (7 bits of length) if (_lengthCode <= 15) { _codeList[_loopCounter++] = (byte)_lengthCode; } else { if (!_input.EnsureBitsAvailable(7)) { // it doesn't matter if we require more bits here _state = InflaterState.ReadingTreeCodesAfter; return false; } int repeatCount; if (_lengthCode == 16) { if (_loopCounter == 0) { // can't have "prev code" on first code throw new InvalidDataException(); } byte previousCode = _codeList[_loopCounter - 1]; repeatCount = _input.GetBits(2) + 3; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = previousCode; } } else if (_lengthCode == 17) { repeatCount = _input.GetBits(3) + 3; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = 0; } } else { // code == 18 repeatCount = _input.GetBits(7) + 11; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = 0; } } } _state = InflaterState.ReadingTreeCodesBefore; // we want to read the next code. } break; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.UnknownState); } byte[] literalTreeCodeLength = new byte[HuffmanTree.MaxLiteralTreeElements]; byte[] distanceTreeCodeLength = new byte[HuffmanTree.MaxDistTreeElements]; // Create literal and distance tables Array.Copy(_codeList, 0, literalTreeCodeLength, 0, _literalLengthCodeCount); Array.Copy(_codeList, _literalLengthCodeCount, distanceTreeCodeLength, 0, _distanceCodeCount); // Make sure there is an end-of-block code, otherwise how could we ever end? if (literalTreeCodeLength[HuffmanTree.EndOfBlockCode] == 0) { throw new InvalidDataException(); } _literalLengthTree = new HuffmanTree(literalTreeCodeLength); _distanceTree = new HuffmanTree(distanceTreeCodeLength); _state = InflaterState.DecodeTop; return true; } public void Dispose() { } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 474141 $ * $Date: 2006-11-13 05:43:37 +0100 (lun., 13 nov. 2006) $ * * 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.Configuration; using IBatisNet.Common.Logging.Impl; namespace IBatisNet.Common.Logging { /// <summary> /// Uses the specified <see cref="ILoggerFactoryAdapter" /> to create <see cref="ILog" /> instances /// that are used to log messages. Inspired by log4net. /// </summary> public sealed class LogManager { private static ILoggerFactoryAdapter _adapter = null; private static object _loadLock = new object(); private static readonly string IBATIS_SECTION_LOGGING = "iBATIS/logging"; /// <summary> /// Initializes a new instance of the <see cref="LogManager" /> class. /// </summary> /// <remarks> /// Uses a private access modifier to prevent instantiation of this class. /// </remarks> private LogManager() { } /// <summary> /// Gets or sets the adapter. /// </summary> /// <remarks> /// <para> /// The IBatisNet.Common assembly ships with the following built-in <see cref="ILoggerFactoryAdapter" /> implementations: /// </para> /// <list type="table"> /// <item><term><see cref="ConsoleOutLoggerFA" /></term><description>Writes output to Console.Out</description></item> /// <item><term><see cref="TraceLoggerFA" /></term><description>Writes output to the System.Diagnostics.Trace sub-system</description></item> /// <item><term><see cref="NoOpLoggerFA" /></term><description>Ignores all messages</description></item> /// </list> /// </remarks> /// <value>The adapter.</value> public static ILoggerFactoryAdapter Adapter { get { if (_adapter == null) { lock (_loadLock) { if (_adapter == null) { _adapter = BuildLoggerFactoryAdapter(); } } } return _adapter; } set { lock (_loadLock) { _adapter = value; } } } /// <summary> /// Gets the logger. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static ILog GetLogger(Type type) { return Adapter.GetLogger(type); } /// <summary> /// Gets the logger. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public static ILog GetLogger(string name) { return Adapter.GetLogger(name); } /// <summary> /// Builds the logger factory adapter. /// </summary> /// <returns></returns> private static ILoggerFactoryAdapter BuildLoggerFactoryAdapter() { LogSetting setting = null; try { //#if dotnet2 setting = (LogSetting)ConfigurationManager.GetSection(IBATIS_SECTION_LOGGING); //#else // setting = (LogSetting)ConfigurationSettings.GetConfig( IBATIS_SECTION_LOGGING ); //#endif } catch (Exception ex) { ILoggerFactoryAdapter defaultFactory = BuildDefaultLoggerFactoryAdapter(); ILog log = defaultFactory.GetLogger(typeof(LogManager)); log.Warn("Unable to read configuration. Using default logger.", ex); return defaultFactory; } if (setting != null && !typeof(ILoggerFactoryAdapter).IsAssignableFrom(setting.FactoryAdapterType)) { ILoggerFactoryAdapter defaultFactory = BuildDefaultLoggerFactoryAdapter(); ILog log = defaultFactory.GetLogger(typeof(LogManager)); log.Warn("Type " + setting.FactoryAdapterType.FullName + " does not implement ILoggerFactoryAdapter. Using default logger"); return defaultFactory; } ILoggerFactoryAdapter instance = null; if (setting != null) { if (setting.Properties.Count > 0) { try { object[] args = { setting.Properties }; instance = (ILoggerFactoryAdapter)Activator.CreateInstance(setting.FactoryAdapterType, args); } catch (Exception ex) { ILoggerFactoryAdapter defaultFactory = BuildDefaultLoggerFactoryAdapter(); ILog log = defaultFactory.GetLogger(typeof(LogManager)); log.Warn("Unable to create instance of type " + setting.FactoryAdapterType.FullName + ". Using default logger.", ex); return defaultFactory; } } else { try { instance = (ILoggerFactoryAdapter)Activator.CreateInstance(setting.FactoryAdapterType); } catch (Exception ex) { ILoggerFactoryAdapter defaultFactory = BuildDefaultLoggerFactoryAdapter(); ILog log = defaultFactory.GetLogger(typeof(LogManager)); log.Warn("Unable to create instance of type " + setting.FactoryAdapterType.FullName + ". Using default logger.", ex); return defaultFactory; } } } else { ILoggerFactoryAdapter defaultFactory = BuildDefaultLoggerFactoryAdapter(); ILog log = defaultFactory.GetLogger(typeof(LogManager)); log.Warn("Unable to read configuration IBatisNet/logging. Using default logger."); return defaultFactory; } return instance; } /// <summary> /// Builds the default logger factory adapter. /// </summary> /// <returns></returns> private static ILoggerFactoryAdapter BuildDefaultLoggerFactoryAdapter() { return new NoOpLoggerFA(); } } }
// 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.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Text; namespace System.IO { public static partial class Path { public static readonly char DirectorySeparatorChar = '\\'; public static readonly char VolumeSeparatorChar = ':'; public static readonly char PathSeparator = ';'; private const string DirectorySeparatorCharAsString = "\\"; private static readonly char[] InvalidFileNameChars = { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/' }; // Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space. // string.WhitespaceChars will trim more aggressively than what the underlying FS does (for ex, NTFS, FAT). private static readonly char[] TrimEndChars = { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20, (char)0x85, (char)0xA0 }; // The max total path is 260, and the max individual component length is 255. // For example, D:\<256 char file name> isn't legal, even though it's under 260 chars. internal static readonly int MaxPath = 260; private static readonly int MaxComponentLength = 255; private const int MaxLongPath = 32000; private static bool IsDirectoryOrVolumeSeparator(char c) { return PathInternal.IsDirectorySeparator(c) || VolumeSeparatorChar == c; } // Expands the given path to a fully qualified path. [Pure] [System.Security.SecuritySafeCritical] public static string GetFullPath(string path) { string fullPath = GetFullPathInternal(path); // Emulate FileIOPermissions checks, retained for compatibility PathInternal.CheckInvalidPathChars(fullPath, true); int startIndex = PathInternal.IsExtended(fullPath) ? PathInternal.ExtendedPathPrefix.Length + 2 : 2; if (fullPath.Length > startIndex && fullPath.IndexOf(':', startIndex) != -1) { throw new NotSupportedException(SR.Argument_PathFormatNotSupported); } return fullPath; } /// <summary> /// Checks for known bad extended paths (paths that start with \\?\) /// </summary> /// <param name="fullCheck">Check for invalid characters if true.</param> /// <returns>'true' if the path passes validity checks.</returns> private static bool ValidateExtendedPath(string path, bool fullCheck) { if (path.Length == PathInternal.ExtendedPathPrefix.Length) { // Effectively empty and therefore invalid return false; } if (path.StartsWith(PathInternal.UncExtendedPathPrefix, StringComparison.Ordinal)) { // UNC specific checks if (path.Length == PathInternal.UncExtendedPathPrefix.Length || path[PathInternal.UncExtendedPathPrefix.Length] == DirectorySeparatorChar) { // Effectively empty and therefore invalid (\\?\UNC\ or \\?\UNC\\) return false; } int serverShareSeparator = path.IndexOf(DirectorySeparatorChar, PathInternal.UncExtendedPathPrefix.Length); if (serverShareSeparator == -1 || serverShareSeparator == path.Length - 1) { // Need at least a Server\Share return false; } } // Segments can't be empty "\\" or contain *just* "." or ".." char twoBack = '?'; char oneBack = DirectorySeparatorChar; char currentCharacter; bool periodSegment = false; for (int i = PathInternal.ExtendedPathPrefix.Length; i < path.Length; i++) { currentCharacter = path[i]; switch (currentCharacter) { case '\\': if (oneBack == DirectorySeparatorChar || periodSegment) throw new ArgumentException(SR.Arg_PathIllegal); periodSegment = false; break; case '.': periodSegment = (oneBack == DirectorySeparatorChar || (twoBack == DirectorySeparatorChar && oneBack == '.')); break; default: periodSegment = false; break; } twoBack = oneBack; oneBack = currentCharacter; } if (periodSegment) { return false; } if (fullCheck) { // Look for illegal path characters. PathInternal.CheckInvalidPathChars(path); } return true; } [System.Security.SecurityCritical] // auto-generated private unsafe static string NormalizePath(string path, bool fullCheck, int maxPathLength, bool expandShortPaths) { Contract.Requires(path != null, "path can't be null"); // If the path is in extended syntax, we don't need to normalize, but we still do some basic validity checks if (PathInternal.IsExtended(path)) { if (!ValidateExtendedPath(path, fullCheck)) { throw new ArgumentException(SR.Arg_PathIllegal); } // \\?\GLOBALROOT gives access to devices out of the scope of the current user, we // don't want to allow this for security reasons. // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#nt_namespaces if (path.StartsWith(@"\\?\globalroot", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(SR.Arg_PathGlobalRoot); return path; } // If we're doing a full path check, trim whitespace and look for // illegal path characters. if (fullCheck) { // Trim whitespace off the end of the string. // Win32 normalization trims only U+0020. path = path.TrimEnd(TrimEndChars); // Look for illegal path characters. PathInternal.CheckInvalidPathChars(path); } int index = 0; // We prefer to allocate on the stack for workingset/perf gain. If the // starting path is less than MaxPath then we can stackalloc; otherwise we'll // use a StringBuilder (PathHelper does this under the hood). The latter may // happen in 2 cases: // 1. Starting path is greater than MaxPath but it normalizes down to MaxPath. // This is relevant for paths containing escape sequences. In this case, we // attempt to normalize down to MaxPath, but the caller pays a perf penalty // since StringBuilder is used. // 2. IsolatedStorage, which supports paths longer than MaxPath (value given // by maxPathLength. PathHelper newBuffer = null; if (path.Length + 1 <= MaxPath) { char* m_arrayPtr = stackalloc char[MaxPath]; newBuffer = new PathHelper(m_arrayPtr, MaxPath); } else { newBuffer = new PathHelper(path.Length + MaxPath, maxPathLength); } uint numSpaces = 0; uint numDots = 0; bool fixupDirectorySeparator = false; // Number of significant chars other than potentially suppressible // dots and spaces since the last directory or volume separator char uint numSigChars = 0; int lastSigChar = -1; // Index of last significant character. // Whether this segment of the path (not the complete path) started // with a volume separator char. Reject "c:...". bool startedWithVolumeSeparator = false; bool firstSegment = true; int lastDirectorySeparatorPos = 0; bool mightBeShortFileName = false; // LEGACY: This code is here for backwards compatibility reasons. It // ensures that \\foo.cs\bar.cs stays \\foo.cs\bar.cs instead of being // turned into \foo.cs\bar.cs. if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[0])) { newBuffer.Append('\\'); index++; lastSigChar = 0; } // Normalize the string, stripping out redundant dots, spaces, and // slashes. while (index < path.Length) { char currentChar = path[index]; // We handle both directory separators and dots specially. For // directory separators, we consume consecutive appearances. // For dots, we consume all dots beyond the second in // succession. All other characters are added as is. In // addition we consume all spaces after the last other char // in a directory name up until the directory separator. if (PathInternal.IsDirectorySeparator(currentChar)) { // If we have a path like "123.../foo", remove the trailing dots. // However, if we found "c:\temp\..\bar" or "c:\temp\...\bar", don't. // Also remove trailing spaces from both files & directory names. // This was agreed on with the OS team to fix undeletable directory // names ending in spaces. // If we saw a '\' as the previous last significant character and // are simply going to write out dots, suppress them. // If we only contain dots and slashes though, only allow // a string like [dot]+ [space]*. Ignore everything else. // Legal: "\.. \", "\...\", "\. \" // Illegal: "\.. .\", "\. .\", "\ .\" if (numSigChars == 0) { // Dot and space handling if (numDots > 0) { // Look for ".[space]*" or "..[space]*" int start = lastSigChar + 1; if (path[start] != '.') throw new ArgumentException(SR.Arg_PathIllegal); // Only allow "[dot]+[space]*", and normalize the // legal ones to "." or ".." if (numDots >= 2) { // Reject "C:..." if (startedWithVolumeSeparator && numDots > 2) throw new ArgumentException(SR.Arg_PathIllegal); if (path[start + 1] == '.') { // Search for a space in the middle of the // dots and throw for (int i = start + 2; i < start + numDots; i++) { if (path[i] != '.') throw new ArgumentException(SR.Arg_PathIllegal); } numDots = 2; } else { if (numDots > 1) throw new ArgumentException(SR.Arg_PathIllegal); numDots = 1; } } if (numDots == 2) { newBuffer.Append('.'); } newBuffer.Append('.'); fixupDirectorySeparator = false; // Continue in this case, potentially writing out '\'. } if (numSpaces > 0 && firstSegment) { // Handle strings like " \\server\share". if (index + 1 < path.Length && PathInternal.IsDirectorySeparator(path[index + 1])) { newBuffer.Append(DirectorySeparatorChar); } } } numDots = 0; numSpaces = 0; // Suppress trailing spaces if (!fixupDirectorySeparator) { fixupDirectorySeparator = true; newBuffer.Append(DirectorySeparatorChar); } numSigChars = 0; lastSigChar = index; startedWithVolumeSeparator = false; firstSegment = false; // For short file names, we must try to expand each of them as // soon as possible. We need to allow people to specify a file // name that doesn't exist using a path with short file names // in it, such as this for a temp file we're trying to create: // C:\DOCUME~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp // We could try doing this afterwards piece by piece, but it's // probably a lot simpler to do it here. if (mightBeShortFileName) { newBuffer.TryExpandShortFileName(); mightBeShortFileName = false; } int thisPos = newBuffer.Length - 1; if (thisPos - lastDirectorySeparatorPos > MaxComponentLength) { throw new PathTooLongException(SR.IO_PathTooLong); } lastDirectorySeparatorPos = thisPos; } // if (Found directory separator) else if (currentChar == '.') { // Reduce only multiple .'s only after slash to 2 dots. For // instance a...b is a valid file name. numDots++; // Don't flush out non-terminal spaces here, because they may in // the end not be significant. Turn "c:\ . .\foo" -> "c:\foo" // which is the conclusion of removing trailing dots & spaces, // as well as folding multiple '\' characters. } else if (currentChar == ' ') { numSpaces++; } else { // Normal character logic if (currentChar == '~' && expandShortPaths) mightBeShortFileName = true; fixupDirectorySeparator = false; // To reject strings like "C:...\foo" and "C :\foo" if (firstSegment && currentChar == VolumeSeparatorChar) { // Only accept "C:", not "c :" or ":" // Get a drive letter or ' ' if index is 0. char driveLetter = (index > 0) ? path[index - 1] : ' '; bool validPath = ((numDots == 0) && (numSigChars >= 1) && (driveLetter != ' ')); if (!validPath) throw new ArgumentException(SR.Arg_PathIllegal); startedWithVolumeSeparator = true; // We need special logic to make " c:" work, we should not fix paths like " foo::$DATA" if (numSigChars > 1) { // Common case, simply do nothing int spaceCount = 0; // How many spaces did we write out, numSpaces has already been reset. while ((spaceCount < newBuffer.Length) && newBuffer[spaceCount] == ' ') spaceCount++; if (numSigChars - spaceCount == 1) { //Safe to update stack ptr directly newBuffer.Length = 0; newBuffer.Append(driveLetter); // Overwrite spaces, we need a special case to not break " foo" as a relative path. } } numSigChars = 0; } else { numSigChars += 1 + numDots + numSpaces; } // Copy any spaces & dots since the last significant character // to here. Note we only counted the number of dots & spaces, // and don't know what order they're in. Hence the copy. if (numDots > 0 || numSpaces > 0) { int numCharsToCopy = (lastSigChar >= 0) ? index - lastSigChar - 1 : index; if (numCharsToCopy > 0) { for (int i = 0; i < numCharsToCopy; i++) { newBuffer.Append(path[lastSigChar + 1 + i]); } } numDots = 0; numSpaces = 0; } newBuffer.Append(currentChar); lastSigChar = index; } index++; } // end while if (newBuffer.Length - 1 - lastDirectorySeparatorPos > MaxComponentLength) { throw new PathTooLongException(SR.IO_PathTooLong); } // Drop any trailing dots and spaces from file & directory names, EXCEPT // we MUST make sure that "C:\foo\.." is correctly handled. // Also handle "C:\foo\." -> "C:\foo", while "C:\." -> "C:\" if (numSigChars == 0) { if (numDots > 0) { // Look for ".[space]*" or "..[space]*" int start = lastSigChar + 1; if (path[start] != '.') throw new ArgumentException(SR.Arg_PathIllegal); // Only allow "[dot]+[space]*", and normalize the // legal ones to "." or ".." if (numDots >= 2) { // Reject "C:..." if (startedWithVolumeSeparator && numDots > 2) throw new ArgumentException(SR.Arg_PathIllegal); if (path[start + 1] == '.') { // Search for a space in the middle of the // dots and throw for (int i = start + 2; i < start + numDots; i++) { if (path[i] != '.') throw new ArgumentException(SR.Arg_PathIllegal); } numDots = 2; } else { if (numDots > 1) throw new ArgumentException(SR.Arg_PathIllegal); numDots = 1; } } if (numDots == 2) { newBuffer.Append('.'); } newBuffer.Append('.'); } } // if (numSigChars == 0) // If we ended up eating all the characters, bail out. if (newBuffer.Length == 0) throw new ArgumentException(SR.Arg_PathIllegal); // Disallow URL's here. Some of our other Win32 API calls will reject // them later, so we might be better off rejecting them here. // Note we've probably turned them into "file:\D:\foo.tmp" by now. // But for compatibility, ensure that callers that aren't doing a // full check aren't rejected here. if (fullCheck) { if (newBuffer.OrdinalStartsWith("http:", false) || newBuffer.OrdinalStartsWith("file:", false)) { throw new ArgumentException(SR.Argument_PathUriFormatNotSupported); } } // If the last part of the path (file or directory name) had a tilde, // expand that too. if (mightBeShortFileName) { newBuffer.TryExpandShortFileName(); } // Call the Win32 API to do the final canonicalization step. int result = 1; if (fullCheck) { // NOTE: Win32 GetFullPathName requires the input buffer to be big enough to fit the initial // path which is a concat of CWD and the relative path, this can be of an arbitrary // size and could be > MaxPath (which becomes an artificial limit at this point), // even though the final normalized path after fixing up the relative path syntax // might be well within the MaxPath restriction. For ex, // "c:\SomeReallyLongDirName(thinkGreaterThan_MAXPATH)\..\foo.txt" which actually requires a // buffer well with in the MaxPath as the normalized path is just "c:\foo.txt" // This buffer requirement seems wrong, it could be a bug or a perf optimization // like returning required buffer length quickly or avoid stratch buffer etc. // Either way we need to workaround it here... // Ideally we would get the required buffer length first by calling GetFullPathName // once without the buffer and use that in the later call but this doesn't always work // due to Win32 GetFullPathName bug. For instance, in Win2k, when the path we are trying to // fully qualify is a single letter name (such as "a", "1", ",") GetFullPathName // fails to return the right buffer size (i.e, resulting in insufficient buffer). // To workaround this bug we will start with MaxPath buffer and grow it once if the // return value is > MaxPath. result = newBuffer.GetFullPathName(); // If we called GetFullPathName with something like "foo" and our // command window was in short file name mode (ie, by running edlin or // DOS versions of grep, etc), we might have gotten back a short file // name. So, check to see if we need to expand it. mightBeShortFileName = false; for (int i = 0; i < newBuffer.Length && !mightBeShortFileName; i++) { if (newBuffer[i] == '~' && expandShortPaths) mightBeShortFileName = true; } if (mightBeShortFileName) { bool r = newBuffer.TryExpandShortFileName(); // Consider how the path "Doesn'tExist" would expand. If // we add in the current directory, it too will need to be // fully expanded, which doesn't happen if we use a file // name that doesn't exist. if (!r) { int lastSlash = -1; for (int i = newBuffer.Length - 1; i >= 0; i--) { if (newBuffer[i] == DirectorySeparatorChar) { lastSlash = i; break; } } if (lastSlash >= 0) { // This bounds check is for safe memcpy but we should never get this far if (newBuffer.Length >= maxPathLength) throw new PathTooLongException(SR.IO_PathTooLong); int lenSavedName = newBuffer.Length - lastSlash - 1; Debug.Assert(lastSlash < newBuffer.Length, "path unexpectedly ended in a '\'"); newBuffer.Fixup(lenSavedName, lastSlash); } } } } if (result != 0) { /* Throw an ArgumentException for paths like \\, \\server, \\server\ This check can only be properly done after normalizing, so \\foo\.. will be properly rejected. */ if (newBuffer.Length > 1 && newBuffer[0] == '\\' && newBuffer[1] == '\\') { int startIndex = 2; while (startIndex < result) { if (newBuffer[startIndex] == '\\') { startIndex++; break; } else { startIndex++; } } if (startIndex == result) throw new ArgumentException(SR.Arg_PathIllegalUNC); } } // Check our result and form the managed string as necessary. if (newBuffer.Length >= maxPathLength) throw new PathTooLongException(SR.IO_PathTooLong); if (result == 0) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == 0) errorCode = Interop.mincore.Errors.ERROR_BAD_PATHNAME; throw Win32Marshal.GetExceptionForWin32Error(errorCode, path); } string returnVal = newBuffer.ToString(); if (string.Equals(returnVal, path, StringComparison.Ordinal)) { returnVal = path; } return returnVal; } [System.Security.SecuritySafeCritical] public static string GetTempPath() { StringBuilder sb = StringBuilderCache.Acquire(MaxPath); uint r = Interop.mincore.GetTempPathW(MaxPath, sb); if (r == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); return GetFullPathInternal(StringBuilderCache.GetStringAndRelease(sb)); } [System.Security.SecurityCritical] private static string InternalGetTempFileName(bool checkHost) { // checkHost was originally intended for file security checks, but is ignored. string path = GetTempPath(); StringBuilder sb = StringBuilderCache.Acquire(MaxPath); uint r = Interop.mincore.GetTempFileNameW(path, "tmp", 0, sb); if (r == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); return StringBuilderCache.GetStringAndRelease(sb); } // Tests if the given path contains a root. A path is considered rooted // if it starts with a backslash ("\") or a drive letter and a colon (":"). [Pure] public static bool IsPathRooted(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); int length = path.Length; if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])) || (length >= 2 && path[1] == VolumeSeparatorChar)) return true; } return false; } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Protocol.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Protocol { /// <summary> /// <para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestProxyAuthentication /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestProxyAuthentication", AccessFlags = 33)] public partial class RequestProxyAuthentication : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestProxyAuthentication() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <java-name> /// org/apache/http/client/protocol/ClientContextConfigurer /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContextConfigurer", AccessFlags = 33)] public partial class ClientContextConfigurer : global::Org.Apache.Http.Client.Protocol.IClientContext /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public ClientContextConfigurer(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } /// <java-name> /// setCookieSpecRegistry /// </java-name> [Dot42.DexImport("setCookieSpecRegistry", "(Lorg/apache/http/cookie/CookieSpecRegistry;)V", AccessFlags = 1)] public virtual void SetCookieSpecRegistry(global::Org.Apache.Http.Cookie.CookieSpecRegistry registry) /* MethodBuilder.Create */ { } /// <java-name> /// setAuthSchemeRegistry /// </java-name> [Dot42.DexImport("setAuthSchemeRegistry", "(Lorg/apache/http/auth/AuthSchemeRegistry;)V", AccessFlags = 1)] public virtual void SetAuthSchemeRegistry(global::Org.Apache.Http.Auth.AuthSchemeRegistry registry) /* MethodBuilder.Create */ { } /// <java-name> /// setCookieStore /// </java-name> [Dot42.DexImport("setCookieStore", "(Lorg/apache/http/client/CookieStore;)V", AccessFlags = 1)] public virtual void SetCookieStore(global::Org.Apache.Http.Client.ICookieStore store) /* MethodBuilder.Create */ { } /// <java-name> /// setCredentialsProvider /// </java-name> [Dot42.DexImport("setCredentialsProvider", "(Lorg/apache/http/client/CredentialsProvider;)V", AccessFlags = 1)] public virtual void SetCredentialsProvider(global::Org.Apache.Http.Client.ICredentialsProvider provider) /* MethodBuilder.Create */ { } /// <java-name> /// setAuthSchemePref /// </java-name> [Dot42.DexImport("setAuthSchemePref", "(Ljava/util/List;)V", AccessFlags = 1, Signature = "(Ljava/util/List<Ljava/lang/String;>;)V")] public virtual void SetAuthSchemePref(global::Java.Util.IList<string> list) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ClientContextConfigurer() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Response interceptor that populates the current CookieStore with data contained in response cookies received in the given the HTTP response.</para><para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ResponseProcessCookies /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ResponseProcessCookies", AccessFlags = 33)] public partial class ResponseProcessCookies : global::Org.Apache.Http.IHttpResponseInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ResponseProcessCookies() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Request interceptor that matches cookies available in the current CookieStore to the request being executed and generates corresponding cookierequest headers.</para><para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestAddCookies /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestAddCookies", AccessFlags = 33)] public partial class RequestAddCookies : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestAddCookies() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestTargetAuthentication /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestTargetAuthentication", AccessFlags = 33)] public partial class RequestTargetAuthentication : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestTargetAuthentication() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Context attribute names for client. </para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ClientContext /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContext", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IClientContextConstants /* scope: __dot42__ */ { /// <java-name> /// COOKIESPEC_REGISTRY /// </java-name> [Dot42.DexImport("COOKIESPEC_REGISTRY", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIESPEC_REGISTRY = "http.cookiespec-registry"; /// <java-name> /// AUTHSCHEME_REGISTRY /// </java-name> [Dot42.DexImport("AUTHSCHEME_REGISTRY", "Ljava/lang/String;", AccessFlags = 25)] public const string AUTHSCHEME_REGISTRY = "http.authscheme-registry"; /// <java-name> /// COOKIE_STORE /// </java-name> [Dot42.DexImport("COOKIE_STORE", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_STORE = "http.cookie-store"; /// <java-name> /// COOKIE_SPEC /// </java-name> [Dot42.DexImport("COOKIE_SPEC", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_SPEC = "http.cookie-spec"; /// <java-name> /// COOKIE_ORIGIN /// </java-name> [Dot42.DexImport("COOKIE_ORIGIN", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_ORIGIN = "http.cookie-origin"; /// <java-name> /// CREDS_PROVIDER /// </java-name> [Dot42.DexImport("CREDS_PROVIDER", "Ljava/lang/String;", AccessFlags = 25)] public const string CREDS_PROVIDER = "http.auth.credentials-provider"; /// <java-name> /// TARGET_AUTH_STATE /// </java-name> [Dot42.DexImport("TARGET_AUTH_STATE", "Ljava/lang/String;", AccessFlags = 25)] public const string TARGET_AUTH_STATE = "http.auth.target-scope"; /// <java-name> /// PROXY_AUTH_STATE /// </java-name> [Dot42.DexImport("PROXY_AUTH_STATE", "Ljava/lang/String;", AccessFlags = 25)] public const string PROXY_AUTH_STATE = "http.auth.proxy-scope"; /// <java-name> /// AUTH_SCHEME_PREF /// </java-name> [Dot42.DexImport("AUTH_SCHEME_PREF", "Ljava/lang/String;", AccessFlags = 25)] public const string AUTH_SCHEME_PREF = "http.auth.scheme-pref"; /// <java-name> /// USER_TOKEN /// </java-name> [Dot42.DexImport("USER_TOKEN", "Ljava/lang/String;", AccessFlags = 25)] public const string USER_TOKEN = "http.user-token"; } /// <summary> /// <para>Context attribute names for client. </para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ClientContext /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContext", AccessFlags = 1537)] public partial interface IClientContext /* scope: __dot42__ */ { } /// <summary> /// <para>Request interceptor that adds default request headers.</para><para><para></para><para></para><title>Revision:</title><para>653041 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestDefaultHeaders /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestDefaultHeaders", AccessFlags = 33)] public partial class RequestDefaultHeaders : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestDefaultHeaders() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } }
// 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; using Xunit.Abstractions; using System.IO; using System.Collections; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_RemoveRecursive", Desc = "")] public class TC_SchemaSet_RemoveRecursive : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_RemoveRecursive(ITestOutputHelper output) { _output = output; } public bool bWarningCallback = false; public bool bErrorCallback = false; public void ValidationCallback(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { _output.WriteLine("WARNING: "); bWarningCallback = true; } else if (args.Severity == XmlSeverityType.Error) { _output.WriteLine("ERROR: "); bErrorCallback = true; } _output.WriteLine(args.Message); // Print the error to the screen. } //----------------------------------------------------------------------------------- //[Variation(Desc = "v1 - RemoveRecursive with null", Priority = 0)] [InlineData()] [Theory] public void v1() { try { XmlSchemaSet sc = new XmlSchemaSet(); sc.RemoveRecursive(null); } catch (ArgumentNullException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- //[Variation(Desc = "v2 - RemoveRecursive with just added schema", Priority = 0)] [InlineData()] [Theory] public void v2() { XmlSchemaSet sc = new XmlSchemaSet(); //remove after compile XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor); sc.Compile(); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 0, "Count"); ICollection Col = sc.Schemas(); CError.Compare(Col.Count, 0, "ICollection.Count"); //remove before compile Schema1 = sc.Add(null, TestData._XsdAuthor); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 0, "Count"); Col = sc.Schemas(); CError.Compare(Col.Count, 0, "ICollection.Count"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v3 - RemoveRecursive first added schema, check the rest")] [InlineData()] [Theory] public void v3() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor); XmlSchema Schema2 = sc.Add("test", TestData._XsdNoNs); sc.Compile(); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 1, "Count"); ICollection Col = sc.Schemas(); CError.Compare(Col.Count, 1, "ICollection.Count"); CError.Compare(sc.Contains("test"), true, "Contains"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v4.6 - RemoveRecursive A(ns-a) include B(ns-a) which includes C(ns-a) ", Priority = 1, Params = new object[] { "include_v7_a.xsd" })] [InlineData("include_v7_a.xsd")] //[Variation(Desc = "v4.5 - RemoveRecursive: A with NS includes B and C with no NS", Priority = 1, Params = new object[] { "include_v6_a.xsd" })] [InlineData("include_v6_a.xsd")] //[Variation(Desc = "v4.4 - RemoveRecursive: A with NS includes B and C with no NS, B also includes C", Priority = 1, Params = new object[] { "include_v5_a.xsd" })] [InlineData("include_v5_a.xsd")] //[Variation(Desc = "v4.3 - RemoveRecursive: A with NS includes B with no NS, which includes C with no NS", Priority = 1, Params = new object[] { "include_v4_a.xsd" })] [InlineData("include_v4_a.xsd")] //[Variation(Desc = "v4.2 - RemoveRecursive: A with no NS includes B with no NS", Params = new object[] { "include_v3_a.xsd" })] [InlineData("include_v3_a.xsd")] //[Variation(Desc = "v4.1 - RemoveRecursive: A with NS includes B with no NS", Params = new object[] { "include_v1_a.xsd", })] [InlineData("include_v1_a.xsd")] [Theory] public void v4(string fileName) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); try { // remove after compile XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor); XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, fileName)); // param as filename sc.Compile(); sc.RemoveRecursive(Schema2); CError.Compare(sc.Count, 1, "Count"); ICollection Col = sc.Schemas(); CError.Compare(Col.Count, 1, "ICollection.Count"); //remove before compile Schema2 = sc.Add(null, Path.Combine(TestData._Root, fileName)); // param as filename CError.Compare(sc.Count, 2, "Count"); sc.RemoveRecursive(Schema2); CError.Compare(sc.Count, 1, "Count"); Col = sc.Schemas(); CError.Compare(Col.Count, 1, "ICollection.Count"); } catch (Exception e) { _output.WriteLine(e.ToString()); Assert.True(false); } return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v5.2 - Remove: A(ns-a) improts B (ns-b)", Priority = 1, Params = new object[] { "import_v2_a.xsd", 1 })] [InlineData("import_v2_a.xsd", 1)] //[Variation(Desc = "v5.1 - Remove: A with NS imports B with no NS", Priority = 1, Params = new object[] { "import_v1_a.xsd", 1 })] [InlineData("import_v1_a.xsd", 1)] [Theory] public void v5(object param0, object param1) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); try { XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor); //remove after compile XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename sc.Compile(); sc.RemoveRecursive(Schema2); CError.Compare(sc.Count, param1, "Count"); ICollection Col = sc.Schemas(); CError.Compare(Col.Count, param1, "ICollection.Count"); //remove before compile Schema2 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename sc.RemoveRecursive(Schema2); CError.Compare(sc.Count, param1, "Count"); Col = sc.Schemas(); CError.Compare(Col.Count, param1, "ICollection.Count"); } catch (Exception e) { _output.WriteLine(e.ToString()); Assert.True(false); } return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v6 - Remove: Add B(NONS) to a namespace, Add A(ns-a) which imports B, Remove B(ns-b) then A(ns-a)", Priority = 1)] [InlineData()] [Theory] public void v6() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); try { //after compile XmlSchema Schema1 = sc.Add("ns-b", Path.Combine(TestData._Root, "import_v4_b.xsd")); XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, "import_v5_a.xsd")); // param as filename sc.Compile(); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 2, "Count"); CError.Compare(sc.Contains("ns-b"), false, "Contains"); CError.Compare(sc.Contains(String.Empty), true, "Contains"); CError.Compare(sc.Contains("ns-a"), true, "Contains"); sc.RemoveRecursive(Schema2); ICollection Col = sc.Schemas(); CError.Compare(Col.Count, 0, "ICollection.Count"); CError.Compare(sc.Contains("ns-b"), false, "Contains"); CError.Compare(sc.Contains(String.Empty), false, "Contains"); CError.Compare(sc.Contains("ns-a"), false, "Contains"); //before compile Schema1 = sc.Add("ns-b", Path.Combine(TestData._Root, "import_v4_b.xsd")); Schema2 = sc.Add(null, Path.Combine(TestData._Root, "import_v5_a.xsd")); // param as filename sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 2, "Count"); CError.Compare(sc.Contains("ns-b"), false, "Contains"); CError.Compare(sc.Contains(String.Empty), true, "Contains"); CError.Compare(sc.Contains("ns-a"), true, "Contains"); sc.RemoveRecursive(Schema2); Col = sc.Schemas(); CError.Compare(Col.Count, 0, "ICollection.Count"); CError.Compare(sc.Contains("ns-b"), false, "Contains"); CError.Compare(sc.Contains(String.Empty), false, "Contains"); CError.Compare(sc.Contains("ns-a"), false, "Contains"); } catch (Exception e) { _output.WriteLine(e.ToString()); Assert.True(false); } return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v7.2 - Remove: A(ns-a) imports B(NO NS) imports C (ns-c)", Priority = 1, Params = new object[] { "import_v10_a.xsd", "ns-a", "", "ns-c" })] [InlineData("import_v10_a.xsd", "ns-a", "", "ns-c")] //[Variation(Desc = "v7.1 - Remove: A(ns-a) imports B(ns-b) imports C (ns-c)", Priority = 1, Params = new object[] { "import_v9_a.xsd", "ns-a", "ns-b", "ns-c" })] [InlineData("import_v9_a.xsd", "ns-a", "ns-b", "ns-c")] [Theory] public void v7(object param0, object param1, object param2, object param3) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); try { //after compile XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); sc.Compile(); CError.Compare(sc.Count, 3, "Count"); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 0, "Count"); CError.Compare(sc.Contains(param1.ToString()), false, "Contains"); CError.Compare(sc.Contains(param2.ToString()), false, "Contains"); CError.Compare(sc.Contains(param3.ToString()), false, "Contains"); //before compile Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); CError.Compare(sc.Count, 3, "Count"); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 0, "Count"); CError.Compare(sc.Contains(param1.ToString()), false, "Contains"); CError.Compare(sc.Contains(param2.ToString()), false, "Contains"); CError.Compare(sc.Contains(param3.ToString()), false, "Contains"); } catch (Exception e) { _output.WriteLine(e.ToString()); Assert.True(false); } return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v8 - Remove: A imports B and B and C, B imports C and D, C imports D and A", Priority = 1, Params = new object[] { "import_v13_a.xsd" })] [InlineData("import_v13_a.xsd")] [Theory] public void v8(object param0) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); try { //after compile XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); sc.Compile(); CError.Compare(sc.Count, 4, "Count"); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 0, "Count"); CError.Compare(sc.Contains("ns-d"), false, "Contains"); CError.Compare(sc.Contains("ns-c"), false, "Contains"); CError.Compare(sc.Contains("ns-b"), false, "Contains"); CError.Compare(sc.Contains("ns-a"), false, "Contains"); //before compile Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); CError.Compare(sc.Count, 4, "Count"); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 0, "Count"); CError.Compare(sc.Contains("ns-d"), false, "Contains"); CError.Compare(sc.Contains("ns-c"), false, "Contains"); CError.Compare(sc.Contains("ns-b"), false, "Contains"); CError.Compare(sc.Contains("ns-a"), false, "Contains"); } catch (Exception e) { _output.WriteLine(e.ToString()); Assert.True(false); } return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v9 - Import: B(ns-b) added, A(ns-a) imports B's NS", Priority = 2)] [InlineData()] [Theory] public void v9() { try { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add(null, Path.Combine(TestData._Root, "import_v16_b.xsd")); //before compile XmlSchema parent = sc.Add(null, Path.Combine(TestData._Root, "import_v16_a.xsd")); sc.Compile(); sc.RemoveRecursive(parent); CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.Contains("ns-b"), true, "Contains"); //after compile parent = sc.Add(null, Path.Combine(TestData._Root, "import_v16_a.xsd")); sc.RemoveRecursive(parent); CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.Contains("ns-b"), true, "Contains"); return; } catch (XmlSchemaException e) { _output.WriteLine("Exception : " + e.Message); } Assert.True(false); } //----------------------------------------------------------------------------------- //[Variation(Desc = "v10.8 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports A's NS, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e8.xsd" })] [InlineData("import_v13_a.xsd", "remove_v10_e8.xsd")] //[Variation(Desc = "v10.7 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports C's NS, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e7.xsd" })] [InlineData("import_v13_a.xsd", "remove_v10_e7.xsd")] //[Variation(Desc = "v10.6 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports D's NS, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e6.xsd" })] [InlineData("import_v13_a.xsd", "remove_v10_e6.xsd")] //[Variation(Desc = "v10.5 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports B's NS, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e5.xsd" })] [InlineData("import_v13_a.xsd", "remove_v10_e5.xsd")] //[Variation(Desc = "v10.4 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports A, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e4.xsd" })] [InlineData("import_v13_a.xsd", "remove_v10_e4.xsd")] //[Variation(Desc = "v10.3 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports C, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e3.xsd" })] [InlineData("import_v13_a.xsd", "remove_v10_e3.xsd")] //[Variation(Desc = "v10.2 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports D, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e2.xsd" })] [InlineData("import_v13_a.xsd", "remove_v10_e2.xsd")] //[Variation(Desc = "v10.1 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports B, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e1.xsd" })] [InlineData("import_v13_a.xsd", "remove_v10_e1.xsd")] [Theory] public void v10(object param0, object param1) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); bWarningCallback = false; bErrorCallback = false; try { //after compile XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, param1.ToString())); sc.Compile(); CError.Compare(sc.Count, 5, "Count"); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 5, "Count"); CError.Compare(bWarningCallback, true, "Warning Callback"); CError.Compare(bErrorCallback, false, "Error Callback"); //reinit bWarningCallback = false; bErrorCallback = false; sc.Remove(Schema2); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 0, "Count"); CError.Compare(bWarningCallback, false, "Warning Callback"); CError.Compare(bErrorCallback, false, "Error Callback"); //before compile Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); Schema2 = sc.Add(null, Path.Combine(TestData._Root, param1.ToString())); CError.Compare(sc.Count, 5, "Count"); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 5, "Count"); CError.Compare(bWarningCallback, true, "Warning Callback"); CError.Compare(bErrorCallback, false, "Error Callback"); } catch (Exception e) { _output.WriteLine(e.ToString()); Assert.True(false); } return; } //[Variation(Desc = "v11 - Remove: A imports B and C, B imports C, C imports B and D, Remove A", Priority = 1, Params = new object[] { "remove_v11_a.xsd" })] [InlineData("remove_v11_a.xsd")] [Theory] public void v11(object param0) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); bWarningCallback = false; bErrorCallback = false; try { //after compile XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); sc.Compile(); CError.Compare(sc.Count, 4, "Count"); sc.RemoveRecursive(Schema1); sc.Compile(); CError.Compare(sc.Count, 0, "Count"); CError.Compare(sc.GlobalElements.Count, 0, "Global Elements Count"); CError.Compare(sc.GlobalTypes.Count, 0, "Global Types Count");//should contain xs:anyType //before compile Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); CError.Compare(sc.Count, 4, "Count"); sc.RemoveRecursive(Schema1); CError.Compare(sc.Count, 0, "Count"); CError.Compare(sc.GlobalElements.Count, 0, "Global Elements Count"); CError.Compare(sc.GlobalTypes.Count, 0, "Global Types Count"); //should contain xs:anyType } catch (Exception e) { _output.WriteLine(e.ToString()); Assert.True(false); } return; } } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Text; using System.IO; using log4net.Layout; using log4net.Core; using log4net.Util; namespace log4net.Appender { /// <summary> /// Send an email when a specific logging event occurs, typically on errors /// or fatal errors. Rather than sending via smtp it writes a file into the /// directory specified by <see cref="PickupDir"/>. This allows services such /// as the IIS SMTP agent to manage sending the messages. /// </summary> /// <remarks> /// <para> /// The configuration for this appender is identical to that of the <c>SMTPAppender</c>, /// except that instead of specifying the <c>SMTPAppender.SMTPHost</c> you specify /// <see cref="PickupDir"/>. /// </para> /// <para> /// The number of logging events delivered in this e-mail depend on /// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The /// <see cref="SmtpPickupDirAppender"/> keeps only the last /// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its /// cyclic buffer. This keeps memory requirements at a reasonable level while /// still delivering useful application context. /// </para> /// </remarks> /// <author>Niall Daley</author> /// <author>Nicko Cadell</author> public class SmtpPickupDirAppender : BufferingAppenderSkeleton { #region Public Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Default constructor /// </para> /// </remarks> public SmtpPickupDirAppender() { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets a semicolon-delimited list of recipient e-mail addresses. /// </summary> /// <value> /// A semicolon-delimited list of e-mail addresses. /// </value> /// <remarks> /// <para> /// A semicolon-delimited list of e-mail addresses. /// </para> /// </remarks> public string To { get { return m_to; } set { m_to = value; } } /// <summary> /// Gets or sets the e-mail address of the sender. /// </summary> /// <value> /// The e-mail address of the sender. /// </value> /// <remarks> /// <para> /// The e-mail address of the sender. /// </para> /// </remarks> public string From { get { return m_from; } set { m_from = value; } } /// <summary> /// Gets or sets the subject line of the e-mail message. /// </summary> /// <value> /// The subject line of the e-mail message. /// </value> /// <remarks> /// <para> /// The subject line of the e-mail message. /// </para> /// </remarks> public string Subject { get { return m_subject; } set { m_subject = value; } } /// <summary> /// Gets or sets the path to write the messages to. /// </summary> /// <remarks> /// <para> /// Gets or sets the path to write the messages to. This should be the same /// as that used by the agent sending the messages. /// </para> /// </remarks> public string PickupDir { get { return m_pickupDir; } set { m_pickupDir = value; } } /// <summary> /// Gets or sets the <see cref="SecurityContext"/> used to write to the pickup directory. /// </summary> /// <value> /// The <see cref="SecurityContext"/> used to write to the pickup directory. /// </value> /// <remarks> /// <para> /// Unless a <see cref="SecurityContext"/> specified here for this appender /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the /// security context to use. The default behavior is to use the security context /// of the current thread. /// </para> /// </remarks> public SecurityContext SecurityContext { get { return m_securityContext; } set { m_securityContext = value; } } #endregion Public Instance Properties #region Override implementation of BufferingAppenderSkeleton /// <summary> /// Sends the contents of the cyclic buffer as an e-mail message. /// </summary> /// <param name="events">The logging events to send.</param> /// <remarks> /// <para> /// Sends the contents of the cyclic buffer as an e-mail message. /// </para> /// </remarks> override protected void SendBuffer(LoggingEvent[] events) { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize again. try { string filePath = null; StreamWriter writer = null; // Impersonate to open the file using(SecurityContext.Impersonate(this)) { filePath = Path.Combine(m_pickupDir, SystemInfo.NewGuid().ToString("N")); writer = File.CreateText(filePath); } if (writer == null) { ErrorHandler.Error("Failed to create output file for writing ["+filePath+"]", null, ErrorCode.FileOpenFailure); } else { using(writer) { writer.WriteLine("To: " + m_to); writer.WriteLine("From: " + m_from); writer.WriteLine("Subject: " + m_subject); writer.WriteLine(""); string t = Layout.Header; if (t != null) { writer.Write(t); } for(int i = 0; i < events.Length; i++) { // Render the event and append the text to the buffer RenderLoggingEvent(writer, events[i]); } t = Layout.Footer; if (t != null) { writer.Write(t); } writer.WriteLine(""); writer.WriteLine("."); } } } catch(Exception e) { ErrorHandler.Error("Error occurred while sending e-mail notification.", e); } } #endregion Override implementation of BufferingAppenderSkeleton #region Override implementation of AppenderSkeleton /// <summary> /// Activate the options on this appender. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> override public void ActivateOptions() { base.ActivateOptions(); if (m_securityContext == null) { m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } using(SecurityContext.Impersonate(this)) { m_pickupDir = ConvertToFullPath(m_pickupDir.Trim()); } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion Override implementation of AppenderSkeleton #region Protected Static Methods /// <summary> /// Convert a path into a fully qualified path. /// </summary> /// <param name="path">The path to convert.</param> /// <returns>The fully qualified path.</returns> /// <remarks> /// <para> /// Converts the path specified to a fully /// qualified path. If the path is relative it is /// taken as relative from the application base /// directory. /// </para> /// </remarks> protected static string ConvertToFullPath(string path) { return SystemInfo.ConvertToFullPath(path); } #endregion Protected Static Methods #region Private Instance Fields private string m_to; private string m_from; private string m_subject; private string m_pickupDir; /// <summary> /// The security context to use for privileged calls /// </summary> private SecurityContext m_securityContext; #endregion Private Instance Fields } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Speech.Recognition; using System.Speech.Synthesis; using System.Diagnostics; using System.IO; using System.Speech.Recognition.SrgsGrammar; using System.Threading; using System.Xml; using System.Collections.Concurrent; using System.Speech.AudioFormat; using eDocumentReader.Hubs.activities.system; using eDocumentReader.Hubs.activities.system.lightweight; using Microsoft.AspNet.SignalR; using eDocumentReader.Hubs.structure; namespace eDocumentReader.Hubs { public enum INPUT_STREAM_TYPE { DEFAULT_AUDIO_DEVICE, WEB_RTC } /** * Singleton class, only one speech recognizer thru out the app */ public class EBookSpeechRecognizer : AbstractDevice { public static readonly int UNAMBIGUOUS_SILENCE_TIMEOUT = 50; public static readonly int AMBIGUOUS_SILENCE_TIMEOUT = 500; private int MAX_WORDS_IN_SPEECH; //private static EBookSRDevice instance; private static SpeechRecognitionEngine recEngine; private static List<Grammar> currentStoryGrammars = new List<Grammar>(); private static List<Grammar> onGoingGrammars = new List<Grammar>(); private List<int> allDefaultStartIndexes = new List<int>(); private Boolean recOn = false; //private double speechTurnAroundTime; //private List<List<double>> turnAroundTimes = new List<List<double>>(); //private List<double> eachSpeechTimes; private string saveAudioPath; private bool loadGrammarCompleted = false; //used for debug purpose private int loadGrammarCount = 0; //used for debug purpose private int waveFileNameIndexer; private List<string> confirmSaveAudioList = new List<string>(); private List<string> unconfirmSaveAudioList = new List<string>(); private static ConcurrentQueue<byte[]> conQueue = new ConcurrentQueue<byte[]>(); private int preAudioLevel; //private double audioStartTime; private static INPUT_STREAM_TYPE audioStreamType; private EbookStream ebookStream; private bool startEnqueueAudio = true; //a flag to indicate whether to put received audio in the queue. public EBookSpeechRecognizer() { MAX_WORDS_IN_SPEECH = EBookInteractiveSystem.MAX_WORDS_IN_SPEECH; if (recEngine == null) { recEngine = new SpeechRecognitionEngine(); recEngine.EndSilenceTimeout = TimeSpan.FromMilliseconds(UNAMBIGUOUS_SILENCE_TIMEOUT); recEngine.EndSilenceTimeoutAmbiguous = TimeSpan.FromMilliseconds(AMBIGUOUS_SILENCE_TIMEOUT); recEngine.SpeechRecognized += recEngine_SpeechRecognized; recEngine.SpeechHypothesized += recEngine_SpeechHypothesized; recEngine.SpeechRecognitionRejected += recEngine_SpeechRecognitionRejected; recEngine.SpeechDetected += recEngine_SpeechDetected; recEngine.AudioStateChanged += recEngine_AudioStateChanged; recEngine.LoadGrammarCompleted += recEngine_LoadGrammarCompleted; recEngine.RecognizeCompleted += recEngine_RecognizeCompleted; recEngine.AudioLevelUpdated += recEngine_AudioLevelUpdated; } } void recEngine_AudioLevelUpdated(object sender, AudioLevelUpdatedEventArgs e) { String timeStamp = GetTimestamp(DateTime.Now); Trace.WriteLine("audio level:"+e.AudioLevel+"\t"+timeStamp); if (e.AudioLevel > EBookInteractiveSystem.initialNoiseSensitivity) { int start = 0; double unixTime = EBookUtil.GetUnixTimeMillis(); if (preAudioLevel == 0) { //audio energy level jump start = 1; //audioStartTime = EBookUtil.GetUnixTimeMillis(); } //AbstractEBookEvent.raise(new AudioLevelChangeEvent(e.AudioLevel, start, unixTime)); ActivityExecutor.add(new InternalAudioLevelChangeActivity(e.AudioLevel,start,unixTime)); } else if (e.AudioLevel == 0 && preAudioLevel > 0 && e.AudioLevel == 0) { //audio energy level drop //AbstractEBookEvent.raise(new AudioLevelChangeEvent(e.AudioLevel, -1, 0)); ActivityExecutor.add(new InternalAudioLevelChangeActivity(e.AudioLevel, -1, 0)); } preAudioLevel = e.AudioLevel; } /* * recognize the audio file from the given path. * */ public void recognizeAudioFile(string dir) { //recEngine.SetInputToWaveFile(dir); FileStream fs = new FileStream(dir,FileMode.Open); recEngine.SetInputToWaveStream(fs); } void recEngine_RecognizeCompleted(object sender, RecognizeCompletedEventArgs e) { Debug.WriteLine("Rec completed"); } void recEngine_LoadGrammarCompleted(object sender, LoadGrammarCompletedEventArgs e) { Debug.WriteLine("Load grammar completed" + "\t" + EBookUtil.GetUnixTimeMillis()); loadGrammarCount--; loadGrammarCompleted = true; } /* * Singlaton, allocate speech recognizer once */ /* public static EBookSRDevice GetInstance() { if (instance == null) { instance = new EBookSRDevice(); } return instance; } */ public void setAudioStreamType(INPUT_STREAM_TYPE type) { audioStreamType = type; } //public static void setQueue(ref ConcurrentQueue<byte[]> q) //{ // conQueue = q; //} public void initializeAudioStream() { if (audioStreamType == INPUT_STREAM_TYPE.DEFAULT_AUDIO_DEVICE) { UseDefaultAudioDevice(); } else if (audioStreamType == INPUT_STREAM_TYPE.WEB_RTC) { var context = GlobalHost.ConnectionManager.GetHubContext<EBookHub>(); context.Clients.All.useBrowserAudio(); UseAudioQueue(); } } /* * Tell speech recognizer to use the default audio device. */ public void UseDefaultAudioDevice() { Debug.WriteLine("SR is using default audio device"); recEngine.SetInputToDefaultAudioDevice(); } public void UseAudioQueue() { Debug.WriteLine("SR is using queued stream"); ebookStream = new EbookStream(ref conQueue); SpeechAudioFormatInfo info = new SpeechAudioFormatInfo(44100, AudioBitsPerSample.Sixteen, AudioChannel.Mono); recEngine.SetInputToAudioStream(ebookStream, info); } /* * Enable/disable SR * Disable SR when you absolutely don't need to recognize a speech. * You can keep the SR running when activate/deactivate grammars */ public void enableSR(bool b) { if (b) { if (!recOn) { while (!loadGrammarCompleted && loadGrammarCount != 0) { Thread.Sleep(3); } Debug.WriteLine("is load grammar complete before enable SR? " + loadGrammarCompleted + "\t" + EBookUtil.GetUnixTimeMillis()); ebookStream.enable(true); recEngine.RecognizeAsync(RecognizeMode.Multiple); recOn = true; Debug.WriteLine("Rec on"); } } else { if (recOn) { ebookStream.enable(false); recEngine.RecognizeAsyncCancel();//.RecognizeAsyncStop(); recOn = false; Debug.WriteLine("Rec off"); } } } /* * Set the audio path. * The audio path will be used to save the wave files in the 'record my voice' mode */ public void SetAudioPath(string path) { if (path != null) { Directory.CreateDirectory(path); Array.ForEach(Directory.GetFiles(@path), File.Delete); } this.saveAudioPath = path; waveFileNameIndexer = 0; confirmSaveAudioList.Clear(); unconfirmSaveAudioList.Clear(); } /* * This method will create the grammar from the given list of text and annotation, and activiate it on the fly. * This is happening in runtime, while the SR is running; it might downgrade the performance if the list increased. */ public void GenerateAndLoadGrammars(string[] listText, string[] annotations) { String timeStamp = GetTimestamp(DateTime.Now); Debug.WriteLine("Before load grammar time:" + timeStamp); for (int i = 0; i < listText.Length; i++) { if (i == 0 || (i > 0 && (listText[i - 1].Contains("?") || listText[i - 1].Contains(".") || listText[i - 1].Contains("!")))) { for (int j = i; j < listText.Length && j < i + MAX_WORDS_IN_SPEECH; j++) { string ea = ""; List<string> anno = new List<string>(); for (int k = i; k <= j; k++) { ea += listText[k] + " "; if (!anno.Contains(annotations[k])) { anno.Add(annotations[k]); } } string annotate = ""; foreach (string ann in anno) { annotate += ann + ";"; } ea = ea.TrimEnd(); SemanticResultValue temp = new SemanticResultValue(ea, i); GrammarBuilder gb = new GrammarBuilder(new SemanticResultKey("startIndex", temp)); SemanticResultValue ano = new SemanticResultValue(annotate); gb.Append(new SemanticResultKey("annotation", ano)); //gb.Append(temp); Grammar storyGrammar = new Grammar(gb); //storyGrammar.Name = i + ":" + j; recEngine.LoadGrammarAsync(storyGrammar); currentStoryGrammars.Add(storyGrammar); //choose.Add(gb); allDefaultStartIndexes.Add(i); } } } String after = GetTimestamp(DateTime.Now); Debug.WriteLine("after load grammar time:" + after); } /* * This method is to construct the new grammar from the current endpoint, and load it into SR. */ public void GenerateAndLoadOnGoingGrammars(string[] list, int beginIndex) { UnloadOnGoingGrammar(); int maxchoice = MAX_WORDS_IN_SPEECH; if (list.Length - beginIndex < MAX_WORDS_IN_SPEECH) { maxchoice = list.Length-beginIndex; } for (int i = beginIndex; i < list.Length && i < beginIndex + MAX_WORDS_IN_SPEECH; i++) { string ea = ""; for (int k = beginIndex; k <= i; k++) { ea += list[k] + " "; } ea = ea.TrimEnd(); SemanticResultValue temp = new SemanticResultValue(ea, beginIndex); GrammarBuilder gb = new GrammarBuilder(new SemanticResultKey("startIndex",temp)); Grammar storyGrammar = new Grammar(gb); recEngine.LoadGrammarAsync(storyGrammar); onGoingGrammars.Add(storyGrammar); } enableSR(true); } public void LoadCommandGrammars(List<string> list) { foreach (string each in list) { LoadCommandGrammar(each); } } /* * Load the command grammar from a file */ public void LoadCommandGrammar(string path) { Grammar grammar = new Grammar(@path); grammar.Name = "command"; grammar.Weight = EBookConstant.DEFAULT_WEIGHT; grammar.Priority = EBookConstant.DEFAULT_PRIORITY; Debug.WriteLine("loading command grammar(weight:" + grammar.Weight + " ,priority:" + grammar.Priority + ")..."); recEngine.LoadGrammarAsync(grammar); } /* * Load the given story grammar. */ public void LoadStoryGrammar(Grammar g) { Debug.WriteLine("loading story grammar("+g.Weight+","+g.Priority+")..."+ g.RuleName + "\t" + EBookUtil.GetUnixTimeMillis()); loadGrammarCompleted = false; recEngine.LoadGrammarAsync(g); currentStoryGrammars.Add(g); } /* * Unload all grammars from the SR */ public void UnloadAllGrammars() { recEngine.UnloadAllGrammars(); currentStoryGrammars.Clear(); onGoingGrammars.Clear(); } /* * Unload the active story grammar from SR */ public void UnloadStoryGrammar() { //stopSR(); if (currentStoryGrammars.Count > 0) { foreach(Grammar g in currentStoryGrammars){ recEngine.UnloadGrammar(g); Debug.WriteLine("unloading story grammar(" + g.Weight + "," + g.Priority + ")..." + g.RuleName + "\t" + EBookUtil.GetUnixTimeMillis()); } currentStoryGrammars.Clear(); } // startSR(); } public void ReloadStoryGrammars(List<Grammar> gs) { UnloadStoryGrammar(); foreach (Grammar g in gs) { LoadStoryGrammar(g); } } /* * increase the priority and weight of the grammar that start from the given index * and remove the priority and weight for the rest of the active grammars. */ public void ReloadAndChangeGrammarPriority(int index) { foreach (Grammar g in currentStoryGrammars) { if (g.RuleName.CompareTo("index_" + index) == 0) { loadGrammarCompleted = false; loadGrammarCount++; Debug.WriteLine("reloading grammar(index)..." + "\t" + EBookUtil.GetUnixTimeMillis() + "\t" + g.RuleName); recEngine.UnloadGrammar(g); g.Weight = EBookConstant.NEXT_WORD_WEIGHT; g.Priority = EBookConstant.NEXT_WORD_PRIORITY; recEngine.LoadGrammarAsync(g); } else if (g.Weight != EBookConstant.DEFAULT_WEIGHT || g.Priority != EBookConstant.DEFAULT_PRIORITY) { loadGrammarCompleted = false; loadGrammarCount++; Debug.WriteLine("reloading grammar(weight=+"+g.Weight+",p="+g.Priority+")..." + "\t" + EBookUtil.GetUnixTimeMillis() + "\t" + g.RuleName); recEngine.UnloadGrammar(g); g.Weight = EBookConstant.DEFAULT_WEIGHT; g.Priority = EBookConstant.DEFAULT_PRIORITY; recEngine.LoadGrammarAsync(g); } } } /* * Load the given grammar. */ public void LoadOnGoingGrammar(Grammar g) { loadGrammarCompleted = false; loadGrammarCount++; Debug.WriteLine("loading onGoing grammar..." + "\t" + EBookUtil.GetUnixTimeMillis()); recEngine.LoadGrammarAsync(g); onGoingGrammars.Add(g); } public void UnloadOnGoingGrammar() { if (onGoingGrammars.Count > 0) { foreach (Grammar g in onGoingGrammars) { recEngine.UnloadGrammar(g); } onGoingGrammars.Clear(); } } public void ReloadOnGoingGrammar(Grammar g) { UnloadOnGoingGrammar(); LoadOnGoingGrammar(g); } public void confirmAndSaveAudio() { foreach (string f in unconfirmSaveAudioList) { confirmSaveAudioList.Add(f); } unconfirmSaveAudioList.Clear(); } public void cleanUnconfirmAudio() { foreach (string f in unconfirmSaveAudioList) { File.Delete(f); } unconfirmSaveAudioList.Clear(); } void synthesizer_SpeakProgress(object sender, SpeakProgressEventArgs e) { //Clients.All.addNewMessageToPage("", e.CharacterPosition); } void recEngine_AudioStateChanged(object sender, AudioStateChangedEventArgs e) { string text = "\nAudio State: " + e.AudioState; String timeStamp = GetTimestamp(DateTime.Now); Trace.WriteLine(text+"\t"+timeStamp); SpeechState state = SpeechState.UNKNOWN; if (e.AudioState == AudioState.Silence) { state = SpeechState.SPEECH_END; //if (eachSpeechTimes != null) //{ // turnAroundTimes.Add(eachSpeechTimes); //} } else if (e.AudioState == AudioState.Speech) { state = SpeechState.SPEECH_START; //eachSpeechTimes = new List<double>(); //speechTurnAroundTime = EBookUtil.GetUnixTimeMillis(); } //AbstractEBookEvent.raise(new SpeechStateChangeEvent(state)); ActivityExecutor.add(new InternalSpeechStateChangeActivity(state)); } void recEngine_SpeechDetected(object sender, SpeechDetectedEventArgs e) { string text = "\nAudioPosition: " + e.AudioPosition; Trace.WriteLine(text); } void recEngine_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e) { float confidence = e.Result.Confidence; string textResult = e.Result.Text; string grammarName = e.Result.Grammar.Name; string ruleName = e.Result.Grammar.RuleName; double audioDuration = -1; if (e.Result.Audio != null) { //Looks like we can't get the audio duration for hypothesis result, BUG in Microsoft? audioDuration = e.Result.Audio.Duration.TotalMilliseconds; } KeyValuePair<string, SemanticValue>[] kvp = e.Result.Semantics.ToArray(); //AbstractEBookEvent.raise(new RecognitionResultEvent(confidence,textResult,true, // kvp,grammarName,ruleName, audioDuration,null)); ActivityExecutor.add(new InternalSpeechRecognitionResultActivity(confidence, textResult, true, kvp, grammarName, ruleName, audioDuration, null)); String timeStamp = GetTimestamp(DateTime.Now); string text = "\n" + e.Result.Confidence + "\t" + e.Result.Text + "(Hypothesis)\t" + e.Result.Semantics.Value + "\tgrammarName=" + e.Result.Grammar.Name + "\truleName=" + e.Result.Grammar.RuleName +"\t"+ timeStamp; Trace.WriteLine(text); //double timeNow = EBookUtil.GetUnixTimeMillis(); //double mun = timeNow - speechTurnAroundTime; //speechTurnAroundTime = timeNow; //eachSpeechTimes.Add(mun); } public static String GetTimestamp(DateTime value) { return value.ToString("yyyyMMddHHmmssfff"); } //String lastCompleteResult = ""; void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { float confidence = e.Result.Confidence; string textResult = e.Result.Text; //string semantics = e.Result.Semantics.Value + ""; string grammarName = e.Result.Grammar.Name; string ruleName = e.Result.Grammar.RuleName; double audioDuration = -1; if (e.Result.Audio != null) { audioDuration = e.Result.Audio.Duration.TotalMilliseconds; } //string phonetic = ""; //foreach (RecognizedWordUnit unit in e.Result.Words) //{ // phonetic += unit.Pronunciation + " "; //} //Debug.WriteLine(textResult + "[" + phonetic.TrimEnd() + "]"); Debug.WriteLine("audio duration=" + audioDuration); KeyValuePair<string, SemanticValue>[] kvp = e.Result.Semantics.ToArray(); string fileP = null; string relPath = null; //only write audio file when given path is not null if (saveAudioPath != null) { string indexerStr = waveFileNameIndexer + ""; while (indexerStr.Length < 4) { indexerStr = "0" + indexerStr; } fileP = saveAudioPath + "\\" + indexerStr + ".wav"; relPath = EBookUtil.convertAudioToRelativePath(@fileP); } //AbstractEBookEvent.raise(new RecognitionResultEvent(confidence, textResult, false, // kvp,grammarName,ruleName,audioDuration,@fileP)); ActivityExecutor.add(new InternalSpeechRecognitionResultActivity(confidence, textResult, false, kvp, grammarName, ruleName, audioDuration, relPath)); //only write audio file when given path is not null if (fileP != null) { //write audio to file FileStream stream = new FileStream(fileP, FileMode.Create); e.Result.Audio.WriteToWaveStream(stream); stream.Flush(); stream.Close(); unconfirmSaveAudioList.Add(fileP); Trace.WriteLine("write to file " + fileP); waveFileNameIndexer++; } String timeStamp = GetTimestamp(DateTime.Now); string text = "\n" + e.Result.Confidence + "\t" + e.Result.Text + "(complete)\t\t" + e.Result.Semantics.Value + "\t" + e.Result.Grammar.Name + "\t" + timeStamp; Trace.WriteLine(text); } /* * The function get called when a speech ended and the Speech Recognzier conclude * no match for the given grammars. */ void recEngine_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e) { float confidence = e.Result.Confidence; string textResult = e.Result.Text; //raise a RejectRecognitionEvent //AbstractEBookEvent.raise(new RejectRecognitionEvent()); ActivityExecutor.add(new InternalRejectRecognitionActivity()); String timeStamp = GetTimestamp(DateTime.Now); string text = "\n" + e.Result.Confidence + "\t" + e.Result.Text + "(rejected)\t\t" + e.Result.Semantics.Value + "\t" + timeStamp; Trace.WriteLine(text); } public void updateStream(float[] n, int index) { //if (index - previousIndex != 1) //{ // Debug.WriteLine("***stream out of order " + index + " " + previousIndex); //} //previousIndex = index; if (active) { //using different thread to do the conversion work to ensure the data will not be corrupted ThreadPool.QueueUserWorkItem(new WaitCallback(pushDataSync), new Object[]{n,index}); //Thread thread = new Thread(unused => pushDataSync(n, index)); //thread.Start(); } } private static int lookingIndex = 1; public void updateStreamIndex(int index) { lookingIndex = index; } private static Object locker = new Object(); private void pushDataSync(Object objs) { if (!startEnqueueAudio) return; Object[] eachObj = (Object[])objs; //need to convert float (32-bit) to 2 bytes (2 x 8-bit) float[] n = (float[])eachObj[0]; int currentIndex = (int)eachObj[1]; byte[] result = new byte[n.Length * 2]; for (int i = 0; i < n.Length; i++) { double tmp = n[i] * 32768; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; short toInt = (short)tmp; result[i * 2 + 1] = (byte)(toInt >> 8); result[i * 2] = (byte)(toInt & 0xff); } //use lock and while loop to sync the data in order bool added = false; int maxCycle = 100; int cycle = 0; //use max cycle to prevent any deadlock. while (!added && cycle<maxCycle) { lock (locker) { if (currentIndex == lookingIndex) { conQueue.Enqueue(result); lookingIndex++; added = true; } } if (!added) { Thread.Sleep(5); cycle++; } } //Debug.WriteLine("size of queue "+conQueue.Count); } public void restart() { enableSR(false); UnloadAllGrammars(); } public override string getDeviceName() { return "ASR device"; } } }
/* * Copyright (c) 2005 Mike Bridge <mike@bridgecanada.com> * * Permission is hereby granted, free of charge, to any * person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the * Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software * is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice * shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using DotNetOpenMail; using DotNetOpenMail.Utils; using NUnit.Framework; using log4net; namespace DotNetOpenMailTests { [TestFixture] public class FileAttachmentTests { private static readonly ILog log = LogManager.GetLogger(typeof(FileAttachmentTests)); public FileAttachmentTests() { } [SetUp] public void SetUp() { } [TearDown] public void TearDown() { } [Test] public void TestFileFromStream() { EmailMessage emailmessage=new EmailMessage(); emailmessage.FromAddress=TestAddressHelper.GetFromAddress(); emailmessage.AddToAddress(TestAddressHelper.GetToAddress()); emailmessage.Subject="Here's your license"; emailmessage.TextPart=new TextAttachment("This is a license.\r\n\r\n"+ "We will spend your money on a new plasma TV."); emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+ "<p>This is a license.</p>\r\n"+ "<p>We will spend your money on a new <i>plasma TV</i>.</p>\r\n"+ "</body></html>"); MemoryStream stream=new MemoryStream(); StreamWriter sw=new StreamWriter(stream); sw.WriteLine("this is some test data 1"); sw.WriteLine("this is some test data 2"); sw.WriteLine("this is some test data 3"); sw.WriteLine("this is some test data 4"); sw.Flush(); stream.Seek(0, SeekOrigin.Begin); //BinaryReader br=new BinaryReader(stream); FileAttachment fileAttachment=new FileAttachment(new StreamReader(stream)); //fileAttachment.ContentType fileAttachment.FileName="License.txt"; fileAttachment.CharSet=System.Text.Encoding.ASCII; fileAttachment.ContentType="text/plain"; emailmessage.AddMixedAttachment(fileAttachment); //emailmessage.Send(TestAddressHelper.GetSmtpServer()); } [Test] public void TestBinaryFileFromStream() { EmailMessage emailmessage=new EmailMessage(); emailmessage.FromAddress=TestAddressHelper.GetFromAddress(); emailmessage.AddToAddress(TestAddressHelper.GetToAddress()); emailmessage.Subject="Here's your file"; emailmessage.TextPart=new TextAttachment("This a jpeg."); emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+ "<p>This a jpeg.</p>\r\n"); FileInfo fileinfo=new FileInfo(@"..\..\TestFiles\grover.jpg"); //FileInfo fileinfo=new FileInfo(@"..\..\TestFiles\casingTheJoint.jpg"); FileStream filestream = fileinfo.OpenRead(); MemoryStream stream=new MemoryStream(); StreamWriter sw=new StreamWriter(stream); sw.Flush(); //BinaryReader br=new BinaryReader(stream); BinaryReader br=new BinaryReader(filestream); byte[] bytes=br.ReadBytes((int) fileinfo.Length); br.Close(); FileAttachment fileAttachment=new FileAttachment(bytes); //fileAttachment.ContentType fileAttachment.FileName="grover.jpg"; fileAttachment.ContentType="image/jpeg"; emailmessage.AddMixedAttachment(fileAttachment); emailmessage.Send(TestAddressHelper.GetSmtpServer()); } [Test] public void TestFileFromString() { EmailMessage emailmessage=new EmailMessage(); emailmessage.FromAddress=TestAddressHelper.GetFromAddress(); emailmessage.AddToAddress(TestAddressHelper.GetToAddress()); emailmessage.Subject="Here's your license"; emailmessage.TextPart=new TextAttachment("This is a license.\r\n\r\n"+ "We will spend your money on a new plasma TV."); emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+ "<p>This is a license.</p>\r\n"+ "<p>We will spend your money on a new <i>plasma TV</i>.</p>\r\n"+ "</body></html>"); String content="This is String Line 1\r\nThis is String Line 2"; FileAttachment fileAttachment=new FileAttachment(content); //fileAttachment.ContentType fileAttachment.FileName="License.txt"; fileAttachment.CharSet=System.Text.Encoding.ASCII; fileAttachment.ContentType="text/plain"; fileAttachment.Encoding=DotNetOpenMail.Encoding.EncodingType.SevenBit; emailmessage.AddMixedAttachment(fileAttachment); //emailmessage.Send(TestAddressHelper.GetSmtpServer()); } [Test] public void TestLargerBinaryFileFromStream() { String filename="casingTheJoint.jpg"; EmailMessage emailmessage=new EmailMessage(); emailmessage.FromAddress=TestAddressHelper.GetFromAddress(); emailmessage.AddToAddress(TestAddressHelper.GetToAddress()); emailmessage.Subject="Here's your file"; emailmessage.TextPart=new TextAttachment("This a zip file."); emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+ "<p>This a zip file.</p>\r\n"); FileInfo fileinfo=new FileInfo(@"..\..\TestFiles\"+filename); FileStream filestream = fileinfo.OpenRead(); MemoryStream stream=new MemoryStream(); StreamWriter sw=new StreamWriter(stream); sw.Flush(); //BinaryReader br=new BinaryReader(stream); BinaryReader br=new BinaryReader(filestream); byte[] bytes=br.ReadBytes((int) fileinfo.Length); br.Close(); FileAttachment fileAttachment=new FileAttachment(bytes); //fileAttachment.ContentType fileAttachment.FileName=filename; fileAttachment.ContentType="application/zip"; emailmessage.AddMixedAttachment(fileAttachment); emailmessage.Send(TestAddressHelper.GetSmtpServer()); } [Test] public void TestDocFile() { EmailMessage mail = new EmailMessage(); FileInfo fileinfo=new FileInfo(@"..\..\TestFiles\TestWord.doc"); Assert.IsTrue(fileinfo.Exists); FileAttachment fileAttachment = new FileAttachment(fileinfo); fileAttachment.ContentType = "application/msword"; //EmailAddress emailAddress = new EmailAddress(emailAddressParam); mail.TextPart=new TextAttachment("Here is your file"); mail.AddMixedAttachment(fileAttachment); mail.FromAddress=TestAddressHelper.GetFromAddress(); mail.AddToAddress("outlook@mymailout.com"); SmtpServer smtpServer = TestAddressHelper.GetSmtpServer(); mail.Send(smtpServer); } } }
#region Copyright (C) 2014 Dennis Bappert // The MIT License (MIT) // Copyright (c) 2014 Dennis Bappert // 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.Diagnostics; using System.Linq; using MobileDB.Exceptions; namespace MobileDB.FileSystem { public struct FileSystemPath : IEquatable<FileSystemPath>, IComparable<FileSystemPath> { public const char DirectorySeparator = '/'; private readonly string _path; static FileSystemPath() { Root = new FileSystemPath(DirectorySeparator.ToString()); } private FileSystemPath(string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentException(); _path = path; } public static FileSystemPath Root { get; private set; } public bool IsDirectory { get { return _path[_path.Length - 1] == DirectorySeparator; } } public bool IsFile { get { return !IsDirectory; } } public bool IsRoot { get { return _path.Length == 1; } } public string EntityName { get { var name = _path; if (IsRoot) return null; var endOfName = name.Length; if (IsDirectory) endOfName--; var startOfName = name.LastIndexOf(DirectorySeparator, endOfName - 1, endOfName) + 1; return name.Substring(startOfName, endOfName - startOfName); } } public FileSystemPath ParentPath { get { var parentPath = _path; if (IsRoot) throw new InvalidOperationException("There is no parent of root."); var lookaheadCount = parentPath.Length; if (IsDirectory) lookaheadCount--; var index = parentPath.LastIndexOf(DirectorySeparator, lookaheadCount - 1, lookaheadCount); Debug.Assert(index >= 0); parentPath = parentPath.Remove(index + 1); return new FileSystemPath(parentPath); } } public int CompareTo(FileSystemPath other) { return String.Compare(_path, other._path, StringComparison.Ordinal); } public bool Equals(FileSystemPath other) { return other._path.Equals(_path); } public static bool IsRooted(string s) { if (s.Length == 0) return false; return s[0] == DirectorySeparator; } public static FileSystemPath Parse(string s) { if (s == null) throw new ArgumentNullException("s"); if (!IsRooted(s)) throw new ParseException(s, "Path is not rooted"); if (s.Contains(string.Concat(DirectorySeparator, DirectorySeparator))) throw new ParseException(s, "Path contains double directory-separators."); return new FileSystemPath(s); } public FileSystemPath AppendPath(string relativePath) { if (IsRooted(relativePath)) throw new ArgumentException("The specified path should be relative.", "relativePath"); if (!IsDirectory) throw new InvalidOperationException("This FileSystemPath is not a directory."); return new FileSystemPath(_path + relativePath); } public FileSystemPath AppendPath(FileSystemPath path) { if (!IsDirectory) throw new InvalidOperationException("This FileSystemPath is not a directory."); return new FileSystemPath(_path + path._path.Substring(1)); } public FileSystemPath AppendDirectory(string directoryName) { if (directoryName.Contains(DirectorySeparator.ToString())) throw new ArgumentException("The specified name includes directory-separator(s).", "directoryName"); if (!IsDirectory) throw new InvalidOperationException("The specified FileSystemPath is not a directory."); return new FileSystemPath(_path + directoryName + DirectorySeparator); } public FileSystemPath AppendFile(string fileName) { if (fileName.Contains(DirectorySeparator.ToString())) throw new ArgumentException("The specified name includes directory-separator(s).", "fileName"); if (!IsDirectory) throw new InvalidOperationException("The specified FileSystemPath is not a directory."); return new FileSystemPath(_path + fileName); } public bool IsParentOf(FileSystemPath path) { return IsDirectory && _path.Length != path._path.Length && path._path.StartsWith(_path); } public bool IsChildOf(FileSystemPath path) { return path.IsParentOf(this); } public FileSystemPath RemoveParent(FileSystemPath parent) { if (Equals(parent)) return Root; if (!parent.IsParentOf(this)) throw new ArgumentException("The specified path is not a parent of this path."); return new FileSystemPath(_path.Remove(0, parent._path.Length - 1)); } public FileSystemPath RemoveChild(FileSystemPath child) { if (Equals(child)) return Root; if (!child.IsChildOf(this)) throw new ArgumentException("The specified path is not a child of this path."); return new FileSystemPath(_path.Substring(0, _path.Length - child._path.Length + 1)); } public string GetExtension() { if (!IsFile) throw new ArgumentException("The specified FileSystemPath is not a file."); var name = EntityName; var extensionIndex = name.LastIndexOf('.'); return extensionIndex < 0 ? null : name.Substring(extensionIndex); } public FileSystemPath ChangeExtension(string extension) { if (!IsFile) throw new ArgumentException("The specified FileSystemPath is not a file."); var name = EntityName; var extensionIndex = name.LastIndexOf('.'); return extensionIndex >= 0 ? ParentPath.AppendFile(name.Substring(0, extensionIndex) + extension) : Parse(_path + extension); } public string[] GetDirectorySegments() { var path = this; if (IsFile) path = path.ParentPath; var segments = new LinkedList<string>(); while (!path.IsRoot) { segments.AddFirst(path.EntityName); path = path.ParentPath; } return segments.ToArray(); } public override string ToString() { return _path; } public override bool Equals(object obj) { if (obj is FileSystemPath) return Equals((FileSystemPath) obj); return false; } public override int GetHashCode() { return _path.GetHashCode(); } public static bool operator ==(FileSystemPath pathA, FileSystemPath pathB) { return pathA.Equals(pathB); } public static bool operator !=(FileSystemPath pathA, FileSystemPath pathB) { return !(pathA == pathB); } } }
#region File Description //----------------------------------------------------------------------------- // InnScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using RolePlayingGameData; #endregion namespace RolePlaying { /// <summary> /// Displays the options for an inn that the party can stay at. /// </summary> class InnScreen : GameScreen { private Inn inn; #region Graphics Data private Texture2D backgroundTexture; private Texture2D plankTexture; private Texture2D selectIconTexture; private Texture2D backIconTexture; private Texture2D highlightTexture; private Texture2D arrowTexture; private Texture2D conversationTexture; private Texture2D fadeTexture; private Texture2D goldIcon; #endregion #region Position Data private readonly Vector2 stayPosition = new Vector2(620f, 250f); private readonly Vector2 leavePosition = new Vector2(620f, 300f); private readonly Vector2 costPosition = new Vector2(470, 450); private readonly Vector2 informationPosition = new Vector2(470, 490); private readonly Vector2 selectIconPosition = new Vector2(1150, 640); private readonly Vector2 backIconPosition = new Vector2(80, 640); private readonly Vector2 goldStringPosition = new Vector2(565, 648); private readonly Vector2 stayArrowPosition = new Vector2(520f, 234f); private readonly Vector2 leaveArrowPosition = new Vector2(520f, 284f); private readonly Vector2 stayHighlightPosition = new Vector2(180f, 230f); private readonly Vector2 leaveHighlightPosition = new Vector2(180f, 280f); private readonly Vector2 innKeeperPosition = new Vector2(290, 370); private readonly Vector2 conversationStripPosition = new Vector2(210f, 405f); private readonly Vector2 goldIconPosition = new Vector2(490, 640); private Vector2 plankPosition; private Vector2 backgroundPosition; private Vector2 namePosition; private Vector2 selectTextPosition; private Vector2 backTextPosition; private Rectangle screenRectangle; #endregion #region Dialog Text private List<string> welcomeMessage; private List<string> serviceRenderedMessage; private List<string> noGoldMessage; private List<string> currentDialogue; private const int maxWidth = 570; private const int maxLines = 3; private string costString; private readonly string stayString = "Stay"; private readonly string leaveString = "Leave"; private readonly string selectString = "Select"; private readonly string backString = "Leave"; #endregion #region Selection Data private int selectionMark; private int endIndex; #endregion #region Initialization /// <summary> /// Creates a new InnScreen object. /// </summary> public InnScreen(Inn inn) : base() { // check the parameter if (inn == null) { throw new ArgumentNullException("inn"); } this.IsPopup = true; this.inn = inn; welcomeMessage = Fonts.BreakTextIntoList(inn.WelcomeMessage, Fonts.DescriptionFont, maxWidth); serviceRenderedMessage = Fonts.BreakTextIntoList(inn.PaidMessage, Fonts.DescriptionFont, maxWidth); noGoldMessage = Fonts.BreakTextIntoList(inn.NotEnoughGoldMessage, Fonts.DescriptionFont, maxWidth); selectionMark = 1; ChangeDialogue(welcomeMessage); } /// <summary> /// Load the graphics content /// </summary> /// <param name="batch">SpriteBatch object</param> /// <param name="screenWidth">Width of screen</param> /// <param name="screenHeight">Height of the screen</param> public override void LoadContent() { Viewport viewport = ScreenManager.GraphicsDevice.Viewport; ContentManager content = ScreenManager.Game.Content; backgroundTexture = content.Load<Texture2D>(@"Textures\GameScreens\GameScreenBkgd"); plankTexture = content.Load<Texture2D>(@"Textures\MainMenu\MainMenuPlank03"); selectIconTexture = content.Load<Texture2D>(@"Textures\Buttons\AButton"); backIconTexture = content.Load<Texture2D>(@"Textures\Buttons\BButton"); highlightTexture = content.Load<Texture2D>(@"Textures\GameScreens\HighlightLarge"); arrowTexture = content.Load<Texture2D>(@"Textures\GameScreens\SelectionArrow"); conversationTexture = content.Load<Texture2D>(@"Textures\GameScreens\ConversationStrip"); goldIcon = content.Load<Texture2D>(@"Textures\GameScreens\GoldIcon"); fadeTexture = content.Load<Texture2D>(@"Textures\GameScreens\FadeScreen"); screenRectangle = new Rectangle(viewport.X, viewport.Y, viewport.Width, viewport.Height); plankPosition = new Vector2((viewport.Width - plankTexture.Width) / 2, 67f); backgroundPosition = new Vector2( (viewport.Width - backgroundTexture.Width) / 2, (viewport.Height - backgroundTexture.Height) / 2); namePosition = new Vector2( (viewport.Width - Fonts.HeaderFont.MeasureString(inn.Name).X) / 2, 90f); selectTextPosition = selectIconPosition; selectTextPosition.X -= Fonts.ButtonNamesFont.MeasureString(selectString).X + 10; selectTextPosition.Y += 5; backTextPosition = backIconPosition; backTextPosition.X += backIconTexture.Width + 10; backTextPosition.Y += 5; } #endregion #region Updating /// <summary> /// Handle user input. /// </summary> public override void HandleInput() { // exit the screen if (InputManager.IsActionTriggered(InputManager.Action.Back)) { ExitScreen(); return; } // move the cursor up else if (InputManager.IsActionTriggered(InputManager.Action.CursorUp)) { if (selectionMark == 2) { selectionMark = 1; } } // move the cursor down else if (InputManager.IsActionTriggered(InputManager.Action.CursorDown)) { if (selectionMark == 1) { selectionMark = 2; } } // select an option else if (InputManager.IsActionTriggered(InputManager.Action.Ok)) { if (selectionMark == 1) { int partyCharge = GetChargeForParty(Session.Party); if (Session.Party.PartyGold >= partyCharge) { AudioManager.PlayCue("Money"); Session.Party.PartyGold -= partyCharge; selectionMark = 2; ChangeDialogue(serviceRenderedMessage); HealParty(Session.Party); } else { selectionMark = 2; ChangeDialogue(noGoldMessage); } } else { ExitScreen(); return; } } } /// <summary> /// Change the current dialogue. /// </summary> private void ChangeDialogue(List<string> newDialogue) { currentDialogue = newDialogue; endIndex = maxLines; if (endIndex > currentDialogue.Count) { endIndex = currentDialogue.Count; } } /// <summary> /// Calculate the charge for the party's stay at the inn. /// </summary> private int GetChargeForParty(Party party) { // check the parameter if (party == null) { throw new ArgumentNullException("party"); } return inn.ChargePerPlayer * party.Players.Count; } /// <summary> /// Heal the party back to their correct values for level + gear. /// </summary> private void HealParty(Party party) { // check the parameter if (party == null) { throw new ArgumentNullException("party"); } // reset the statistics for each player foreach (Player player in party.Players) { player.StatisticsModifiers = new StatisticsValue(); } } #endregion #region Drawing /// <summary> /// Draw the screen. /// </summary> public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Vector2 dialogPosition = informationPosition; spriteBatch.Begin(); // Draw fade screen spriteBatch.Draw(fadeTexture, screenRectangle, Color.White); // Draw the background spriteBatch.Draw(backgroundTexture, backgroundPosition, Color.White); // Draw the wooden plank spriteBatch.Draw(plankTexture, plankPosition, Color.White); // Draw the select icon spriteBatch.Draw(selectIconTexture, selectIconPosition, Color.White); // Draw the back icon spriteBatch.Draw(backIconTexture, backIconPosition, Color.White); // Draw the inn name on the wooden plank spriteBatch.DrawString(Fonts.HeaderFont, inn.Name, namePosition, Fonts.DisplayColor); // Draw the stay and leave option texts based on the current selection if (selectionMark == 1) { spriteBatch.Draw(highlightTexture, stayHighlightPosition, Color.White); spriteBatch.Draw(arrowTexture, stayArrowPosition, Color.White); spriteBatch.DrawString( Fonts.GearInfoFont, stayString, stayPosition, Fonts.HighlightColor); spriteBatch.DrawString( Fonts.GearInfoFont, leaveString, leavePosition, Fonts.DisplayColor); } else { spriteBatch.Draw(highlightTexture, leaveHighlightPosition, Color.White); spriteBatch.Draw(arrowTexture, leaveArrowPosition, Color.White); spriteBatch.DrawString(Fonts.GearInfoFont, stayString, stayPosition, Fonts.DisplayColor); spriteBatch.DrawString(Fonts.GearInfoFont, leaveString, leavePosition, Fonts.HighlightColor); } // Draw the amount of gold spriteBatch.DrawString(Fonts.ButtonNamesFont, Fonts.GetGoldString(Session.Party.PartyGold), goldStringPosition, Color.White); // Draw the select button text spriteBatch.DrawString( Fonts.ButtonNamesFont, selectString, selectTextPosition, Color.White); // Draw the back button text spriteBatch.DrawString(Fonts.ButtonNamesFont, backString, backTextPosition, Color.White); // Draw Conversation Strip spriteBatch.Draw(conversationTexture, conversationStripPosition, Color.White); // Draw Shop Keeper spriteBatch.Draw(inn.ShopkeeperTexture, innKeeperPosition, Color.White); // Draw the cost to stay costString = "Cost: " + GetChargeForParty(Session.Party) + " Gold"; spriteBatch.DrawString(Fonts.DescriptionFont, costString, costPosition, Color.DarkRed); // Draw the innkeeper dialog for (int i = 0; i < endIndex; i++) { spriteBatch.DrawString(Fonts.DescriptionFont, currentDialogue[i], dialogPosition, Color.Black); dialogPosition.Y += Fonts.DescriptionFont.LineSpacing; } // Draw Gold Icon spriteBatch.Draw(goldIcon, goldIconPosition, Color.White); spriteBatch.End(); } #endregion } }
#region Copyright & License // // Copyright 2001-2006 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Configuration; using System.Reflection; using System.Text; using System.IO; using System.Runtime.InteropServices; using System.Collections; namespace log4net.Util { /// <summary> /// Utility class for system specific information. /// </summary> /// <remarks> /// <para> /// Utility class of static methods for system specific information. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Alexey Solofnenko</author> public sealed class SystemInfo { #region Private Constants private const string DEFAULT_NULL_TEXT = "(null)"; private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE"; #endregion #region Private Instance Constructors /// <summary> /// Private constructor to prevent instances. /// </summary> /// <remarks> /// <para> /// Only static methods are exposed from this type. /// </para> /// </remarks> private SystemInfo() { } #endregion Private Instance Constructors #region Public Static Constructor /// <summary> /// Initialize default values for private static fields. /// </summary> /// <remarks> /// <para> /// Only static methods are exposed from this type. /// </para> /// </remarks> static SystemInfo() { string nullText = DEFAULT_NULL_TEXT; string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT; #if !NETCF // Look for log4net.NullText in AppSettings string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText"); if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0) { LogLog.Debug("SystemInfo: Initializing NullText value to [" + nullTextAppSettingsKey + "]."); nullText = nullTextAppSettingsKey; } // Look for log4net.NotAvailableText in AppSettings string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText"); if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0) { LogLog.Debug("SystemInfo: Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "]."); notAvailableText = notAvailableTextAppSettingsKey; } #endif s_notAvailableText = notAvailableText; s_nullText = nullText; } #endregion #region Public Static Properties /// <summary> /// Gets the system dependent line terminator. /// </summary> /// <value> /// The system dependent line terminator. /// </value> /// <remarks> /// <para> /// Gets the system dependent line terminator. /// </para> /// </remarks> public static string NewLine { get { #if NETCF return "\r\n"; #else return System.Environment.NewLine; #endif } } /// <summary> /// Gets the base directory for this <see cref="AppDomain"/>. /// </summary> /// <value>The base directory path for the current <see cref="AppDomain"/>.</value> /// <remarks> /// <para> /// Gets the base directory for this <see cref="AppDomain"/>. /// </para> /// <para> /// The value returned may be either a local file path or a URI. /// </para> /// </remarks> public static string ApplicationBaseDirectory { get { #if NETCF return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar; #else return AppDomain.CurrentDomain.BaseDirectory; #endif } } /// <summary> /// Gets the path to the configuration file for the current <see cref="AppDomain"/>. /// </summary> /// <value>The path to the configuration file for the current <see cref="AppDomain"/>.</value> /// <remarks> /// <para> /// The .NET Compact Framework 1.0 does not have a concept of a configuration /// file. For this runtime, we use the entry assembly location as the root for /// the configuration file name. /// </para> /// <para> /// The value returned may be either a local file path or a URI. /// </para> /// </remarks> public static string ConfigurationFileLocation { get { #if NETCF return SystemInfo.EntryAssemblyLocation+".config"; #else return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; #endif } } /// <summary> /// Gets the path to the file that first executed in the current <see cref="AppDomain"/>. /// </summary> /// <value>The path to the entry assembly.</value> /// <remarks> /// <para> /// Gets the path to the file that first executed in the current <see cref="AppDomain"/>. /// </para> /// </remarks> public static string EntryAssemblyLocation { get { #if NETCF return SystemInfo.NativeEntryAssemblyLocation; #else return System.Reflection.Assembly.GetEntryAssembly().Location; #endif } } /// <summary> /// Gets the ID of the current thread. /// </summary> /// <value>The ID of the current thread.</value> /// <remarks> /// <para> /// On the .NET framework, the <c>AppDomain.GetCurrentThreadId</c> method /// is used to obtain the thread ID for the current thread. This is the /// operating system ID for the thread. /// </para> /// <para> /// On the .NET Compact Framework 1.0 it is not possible to get the /// operating system thread ID for the current thread. The native method /// <c>GetCurrentThreadId</c> is implemented inline in a header file /// and cannot be called. /// </para> /// <para> /// On the .NET Framework 2.0 the <c>Thread.ManagedThreadId</c> is used as this /// gives a stable id unrelated to the operating system thread ID which may /// change if the runtime is using fibers. /// </para> /// </remarks> public static int CurrentThreadId { get { #if NETCF return System.Threading.Thread.CurrentThread.GetHashCode(); #elif NET_2_0 return System.Threading.Thread.CurrentThread.ManagedThreadId; #else return AppDomain.GetCurrentThreadId(); #endif } } /// <summary> /// Get the host name or machine name for the current machine /// </summary> /// <value> /// The hostname or machine name /// </value> /// <remarks> /// <para> /// Get the host name or machine name for the current machine /// </para> /// <para> /// The host name (<see cref="System.Net.Dns.GetHostName"/>) or /// the machine name (<c>Environment.MachineName</c>) for /// the current machine, or if neither of these are available /// then <c>NOT AVAILABLE</c> is returned. /// </para> /// </remarks> public static string HostName { get { if (s_hostName == null) { // Get the DNS host name of the current machine try { // Lookup the host name s_hostName = System.Net.Dns.GetHostName(); } catch(System.Net.Sockets.SocketException) { } catch(System.Security.SecurityException) { // We may get a security exception looking up the hostname // You must have Unrestricted DnsPermission to access resource } // Get the NETBIOS machine name of the current machine if (s_hostName == null || s_hostName.Length == 0) { try { #if (!SSCLI && !NETCF) s_hostName = Environment.MachineName; #endif } catch(InvalidOperationException) { } catch(System.Security.SecurityException) { // We may get a security exception looking up the machine name // You must have Unrestricted EnvironmentPermission to access resource } } // Couldn't find a value if (s_hostName == null || s_hostName.Length == 0) { s_hostName = s_notAvailableText; } } return s_hostName; } } /// <summary> /// Get this application's friendly name /// </summary> /// <value> /// The friendly name of this application as a string /// </value> /// <remarks> /// <para> /// If available the name of the application is retrieved from /// the <c>AppDomain</c> using <c>AppDomain.CurrentDomain.FriendlyName</c>. /// </para> /// <para> /// Otherwise the file name of the entry assembly is used. /// </para> /// </remarks> public static string ApplicationFriendlyName { get { if (s_appFriendlyName == null) { try { #if !NETCF s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName; #endif } catch(System.Security.SecurityException) { // This security exception will occur if the caller does not have // some undefined set of SecurityPermission flags. LogLog.Debug("SystemInfo: Security exception while trying to get current domain friendly name. Error Ignored."); } if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) { try { string assemblyLocation = SystemInfo.EntryAssemblyLocation; s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation); } catch(System.Security.SecurityException) { // Caller needs path discovery permission } } if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) { s_appFriendlyName = s_notAvailableText; } } return s_appFriendlyName; } } /// <summary> /// Get the start time for the current process. /// </summary> /// <remarks> /// <para> /// This is the time at which the log4net library was loaded into the /// AppDomain. Due to reports of a hang in the call to <c>System.Diagnostics.Process.StartTime</c> /// this is not the start time for the current process. /// </para> /// <para> /// The log4net library should be loaded by an application early during its /// startup, therefore this start time should be a good approximation for /// the actual start time. /// </para> /// <para> /// Note that AppDomains may be loaded and unloaded within the /// same process without the process terminating, however this start time /// will be set per AppDomain. /// </para> /// </remarks> public static DateTime ProcessStartTime { get { return s_processStartTime; } } /// <summary> /// Text to output when a <c>null</c> is encountered. /// </summary> /// <remarks> /// <para> /// Use this value to indicate a <c>null</c> has been encountered while /// outputting a string representation of an item. /// </para> /// <para> /// The default value is <c>(null)</c>. This value can be overridden by specifying /// a value for the <c>log4net.NullText</c> appSetting in the application's /// .config file. /// </para> /// </remarks> public static string NullText { get { return s_nullText; } set { s_nullText = value; } } /// <summary> /// Text to output when an unsupported feature is requested. /// </summary> /// <remarks> /// <para> /// Use this value when an unsupported feature is requested. /// </para> /// <para> /// The default value is <c>NOT AVAILABLE</c>. This value can be overridden by specifying /// a value for the <c>log4net.NotAvailableText</c> appSetting in the application's /// .config file. /// </para> /// </remarks> public static string NotAvailableText { get { return s_notAvailableText; } set { s_notAvailableText = value; } } #endregion Public Static Properties #region Public Static Methods /// <summary> /// Gets the assembly location path for the specified assembly. /// </summary> /// <param name="myAssembly">The assembly to get the location for.</param> /// <returns>The location of the assembly.</returns> /// <remarks> /// <para> /// This method does not guarantee to return the correct path /// to the assembly. If only tries to give an indication as to /// where the assembly was loaded from. /// </para> /// </remarks> public static string AssemblyLocationInfo(Assembly myAssembly) { #if NETCF return "Not supported on Microsoft .NET Compact Framework"; #else if (myAssembly.GlobalAssemblyCache) { return "Global Assembly Cache"; } else { try { // This call requires FileIOPermission for access to the path // if we don't have permission then we just ignore it and // carry on. return myAssembly.Location; } catch(System.Security.SecurityException) { return "Location Permission Denied"; } } #endif } /// <summary> /// Gets the fully qualified name of the <see cref="Type" />, including /// the name of the assembly from which the <see cref="Type" /> was /// loaded. /// </summary> /// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param> /// <returns>The fully qualified name for the <see cref="Type" />.</returns> /// <remarks> /// <para> /// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property, /// but this method works on the .NET Compact Framework 1.0 as well as /// the full .NET runtime. /// </para> /// </remarks> public static string AssemblyQualifiedName(Type type) { return type.FullName + ", " + type.Assembly.FullName; } /// <summary> /// Gets the short name of the <see cref="Assembly" />. /// </summary> /// <param name="myAssembly">The <see cref="Assembly" /> to get the name for.</param> /// <returns>The short name of the <see cref="Assembly" />.</returns> /// <remarks> /// <para> /// The short name of the assembly is the <see cref="Assembly.FullName" /> /// without the version, culture, or public key. i.e. it is just the /// assembly's file name without the extension. /// </para> /// <para> /// Use this rather than <c>Assembly.GetName().Name</c> because that /// is not available on the Compact Framework. /// </para> /// <para> /// Because of a FileIOPermission security demand we cannot do /// the obvious Assembly.GetName().Name. We are allowed to get /// the <see cref="Assembly.FullName" /> of the assembly so we /// start from there and strip out just the assembly name. /// </para> /// </remarks> public static string AssemblyShortName(Assembly myAssembly) { string name = myAssembly.FullName; int offset = name.IndexOf(','); if (offset > 0) { name = name.Substring(0, offset); } return name.Trim(); // TODO: Do we need to unescape the assembly name string? // Doc says '\' is an escape char but has this already been // done by the string loader? } /// <summary> /// Gets the file name portion of the <see cref="Assembly" />, including the extension. /// </summary> /// <param name="myAssembly">The <see cref="Assembly" /> to get the file name for.</param> /// <returns>The file name of the assembly.</returns> /// <remarks> /// <para> /// Gets the file name portion of the <see cref="Assembly" />, including the extension. /// </para> /// </remarks> public static string AssemblyFileName(Assembly myAssembly) { #if NETCF // This is not very good because it assumes that only // the entry assembly can be an EXE. In fact multiple // EXEs can be loaded in to a process. string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly); string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation); if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0) { // assembly is entry assembly return assemblyShortName + ".exe"; } else { // assembly is not entry assembly return assemblyShortName + ".dll"; } #else return System.IO.Path.GetFileName(myAssembly.Location); #endif } /// <summary> /// Loads the type specified in the type string. /// </summary> /// <param name="relativeType">A sibling type to use to load the type.</param> /// <param name="typeName">The name of the type to load.</param> /// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param> /// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param> /// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns> /// <remarks> /// <para> /// If the type name is fully qualified, i.e. if contains an assembly name in /// the type name, the type will be loaded from the system using /// <see cref="Type.GetType(string,bool)"/>. /// </para> /// <para> /// If the type name is not fully qualified, it will be loaded from the assembly /// containing the specified relative type. If the type is not found in the assembly /// then all the loaded assemblies will be searched for the type. /// </para> /// </remarks> public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase) { return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase); } /// <summary> /// Loads the type specified in the type string. /// </summary> /// <param name="typeName">The name of the type to load.</param> /// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param> /// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param> /// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns> /// <remarks> /// <para> /// If the type name is fully qualified, i.e. if contains an assembly name in /// the type name, the type will be loaded from the system using /// <see cref="Type.GetType(string,bool)"/>. /// </para> /// <para> /// If the type name is not fully qualified it will be loaded from the /// assembly that is directly calling this method. If the type is not found /// in the assembly then all the loaded assemblies will be searched for the type. /// </para> /// </remarks> public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase) { return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase); } /// <summary> /// Loads the type specified in the type string. /// </summary> /// <param name="relativeAssembly">An assembly to load the type from.</param> /// <param name="typeName">The name of the type to load.</param> /// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param> /// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param> /// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns> /// <remarks> /// <para> /// If the type name is fully qualified, i.e. if contains an assembly name in /// the type name, the type will be loaded from the system using /// <see cref="Type.GetType(string,bool)"/>. /// </para> /// <para> /// If the type name is not fully qualified it will be loaded from the specified /// assembly. If the type is not found in the assembly then all the loaded assemblies /// will be searched for the type. /// </para> /// </remarks> public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase) { // Check if the type name specifies the assembly name if(typeName.IndexOf(',') == -1) { //LogLog.Debug("SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); #if NETCF return relativeAssembly.GetType(typeName, throwOnError); #else // Attempt to lookup the type from the relativeAssembly Type type = relativeAssembly.GetType(typeName, false, ignoreCase); if (type != null) { // Found type in relative assembly //LogLog.Debug("SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); return type; } Assembly[] loadedAssemblies = null; try { loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); } catch(System.Security.SecurityException) { // Insufficient permissions to get the list of loaded assemblies } if (loadedAssemblies != null) { // Search the loaded assemblies for the type foreach (Assembly assembly in loadedAssemblies) { type = assembly.GetType(typeName, false, ignoreCase); if (type != null) { // Found type in loaded assembly LogLog.Debug("SystemInfo: Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies."); return type; } } } // Didn't find the type if (throwOnError) { throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies"); } return null; #endif } else { // Includes explicit assembly name //LogLog.Debug("SystemInfo: Loading type ["+typeName+"] from global Type"); #if NETCF return Type.GetType(typeName, throwOnError); #else return Type.GetType(typeName, throwOnError, ignoreCase); #endif } } /// <summary> /// Generate a new guid /// </summary> /// <returns>A new Guid</returns> /// <remarks> /// <para> /// Generate a new guid /// </para> /// </remarks> public static Guid NewGuid() { #if NETCF return PocketGuid.NewGuid(); #else return Guid.NewGuid(); #endif } /// <summary> /// Create an <see cref="ArgumentOutOfRangeException"/> /// </summary> /// <param name="parameterName">The name of the parameter that caused the exception</param> /// <param name="actualValue">The value of the argument that causes this exception</param> /// <param name="message">The message that describes the error</param> /// <returns>the ArgumentOutOfRangeException object</returns> /// <remarks> /// <para> /// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class /// with a specified error message, the parameter name, and the value /// of the argument. /// </para> /// <para> /// The Compact Framework does not support the 3 parameter constructor for the /// <see cref="ArgumentOutOfRangeException"/> type. This method provides an /// implementation that works for all platforms. /// </para> /// </remarks> public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message) { #if NETCF return new ArgumentOutOfRangeException(message + " param: " + parameterName + " value: " + actualValue); #else return new ArgumentOutOfRangeException(parameterName, actualValue, message); #endif } /// <summary> /// Parse a string into an <see cref="Int32"/> value /// </summary> /// <param name="s">the string to parse</param> /// <param name="val">out param where the parsed value is placed</param> /// <returns><c>true</c> if the string was able to be parsed into an integer</returns> /// <remarks> /// <para> /// Attempts to parse the string into an integer. If the string cannot /// be parsed then this method returns <c>false</c>. The method does not throw an exception. /// </para> /// </remarks> public static bool TryParse(string s, out int val) { #if NETCF val = 0; try { val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); return true; } catch { } return false; #else // Initialise out param val = 0; try { double doubleVal; if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) { val = Convert.ToInt32(doubleVal); return true; } } catch { // Ignore exception, just return false } return false; #endif } /// <summary> /// Parse a string into an <see cref="Int64"/> value /// </summary> /// <param name="s">the string to parse</param> /// <param name="val">out param where the parsed value is placed</param> /// <returns><c>true</c> if the string was able to be parsed into an integer</returns> /// <remarks> /// <para> /// Attempts to parse the string into an integer. If the string cannot /// be parsed then this method returns <c>false</c>. The method does not throw an exception. /// </para> /// </remarks> public static bool TryParse(string s, out long val) { #if NETCF val = 0; try { val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); return true; } catch { } return false; #else // Initialise out param val = 0; try { double doubleVal; if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) { val = Convert.ToInt64(doubleVal); return true; } } catch { // Ignore exception, just return false } return false; #endif } /// <summary> /// Lookup an application setting /// </summary> /// <param name="key">the application settings key to lookup</param> /// <returns>the value for the key, or <c>null</c></returns> /// <remarks> /// <para> /// Configuration APIs are not supported under the Compact Framework /// </para> /// </remarks> public static string GetAppSetting(string key) { try { #if NETCF // Configuration APIs are not suported under the Compact Framework #elif NET_2_0 return ConfigurationManager.AppSettings[key]; #else return ConfigurationSettings.AppSettings[key]; #endif } catch(Exception ex) { // If an exception is thrown here then it looks like the config file does not parse correctly. LogLog.Error("DefaultRepositorySelector: Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); } return null; } /// <summary> /// Convert a path into a fully qualified local file path. /// </summary> /// <param name="path">The path to convert.</param> /// <returns>The fully qualified path.</returns> /// <remarks> /// <para> /// Converts the path specified to a fully /// qualified path. If the path is relative it is /// taken as relative from the application base /// directory. /// </para> /// <para> /// The path specified must be a local file path, a URI is not supported. /// </para> /// </remarks> public static string ConvertToFullPath(string path) { if (path == null) { throw new ArgumentNullException("path"); } string baseDirectory = ""; try { string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; if (applicationBaseDirectory != null) { // applicationBaseDirectory may be a URI not a local file path Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory); if (applicationBaseDirectoryUri.IsFile) { baseDirectory = applicationBaseDirectoryUri.LocalPath; } } } catch { // Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory } if (baseDirectory != null && baseDirectory.Length > 0) { // Note that Path.Combine will return the second path if it is rooted return Path.GetFullPath(Path.Combine(baseDirectory, path)); } return Path.GetFullPath(path); } /// <summary> /// Creates a new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity. /// </summary> /// <returns>A new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity</returns> /// <remarks> /// <para> /// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer. /// </para> /// </remarks> public static Hashtable CreateCaseInsensitiveHashtable() { #if NETCF return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); #else return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable(); #endif } #endregion Public Static Methods #region Private Static Methods #if NETCF private static string NativeEntryAssemblyLocation { get { StringBuilder moduleName = null; IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero); if (moduleHandle != IntPtr.Zero) { moduleName = new StringBuilder(255); if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0) { throw new NotSupportedException(NativeError.GetLastError().ToString()); } } else { throw new NotSupportedException(NativeError.GetLastError().ToString()); } return moduleName.ToString(); } } [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] private static extern IntPtr GetModuleHandle(IntPtr ModuleName); [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] private static extern Int32 GetModuleFileName( IntPtr hModule, StringBuilder ModuleName, Int32 cch); #endif #endregion Private Static Methods #region Public Static Fields /// <summary> /// Gets an empty array of types. /// </summary> /// <remarks> /// <para> /// The <c>Type.EmptyTypes</c> field is not available on /// the .NET Compact Framework 1.0. /// </para> /// </remarks> public static readonly Type[] EmptyTypes = new Type[0]; #endregion Public Static Fields #region Private Static Fields /// <summary> /// Cache the host name for the current machine /// </summary> private static string s_hostName; /// <summary> /// Cache the application friendly name /// </summary> private static string s_appFriendlyName; /// <summary> /// Text to output when a <c>null</c> is encountered. /// </summary> private static string s_nullText; /// <summary> /// Text to output when an unsupported feature is requested. /// </summary> private static string s_notAvailableText; /// <summary> /// Start time for the current process. /// </summary> private static DateTime s_processStartTime = DateTime.Now; #endregion #region Compact Framework Helper Classes #if NETCF /// <summary> /// Generate GUIDs on the .NET Compact Framework. /// </summary> public class PocketGuid { // guid variant types private enum GuidVariant { ReservedNCS = 0x00, Standard = 0x02, ReservedMicrosoft = 0x06, ReservedFuture = 0x07 } // guid version types private enum GuidVersion { TimeBased = 0x01, Reserved = 0x02, NameBased = 0x03, Random = 0x04 } // constants that are used in the class private class Const { // number of bytes in guid public const int ByteArraySize = 16; // multiplex variant info public const int VariantByte = 8; public const int VariantByteMask = 0x3f; public const int VariantByteShift = 6; // multiplex version info public const int VersionByte = 7; public const int VersionByteMask = 0x0f; public const int VersionByteShift = 4; } // imports for the crypto api functions private class WinApi { public const uint PROV_RSA_FULL = 1; public const uint CRYPT_VERIFYCONTEXT = 0xf0000000; [DllImport("CoreDll.dll")] public static extern bool CryptAcquireContext( ref IntPtr phProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags); [DllImport("CoreDll.dll")] public static extern bool CryptReleaseContext( IntPtr hProv, uint dwFlags); [DllImport("CoreDll.dll")] public static extern bool CryptGenRandom( IntPtr hProv, int dwLen, byte[] pbBuffer); } // all static methods private PocketGuid() { } /// <summary> /// Return a new System.Guid object. /// </summary> public static Guid NewGuid() { IntPtr hCryptProv = IntPtr.Zero; Guid guid = Guid.Empty; try { // holds random bits for guid byte[] bits = new byte[Const.ByteArraySize]; // get crypto provider handle if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null, WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT)) { throw new SystemException( "Failed to acquire cryptography handle."); } // generate a 128 bit (16 byte) cryptographically random number if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits)) { throw new SystemException( "Failed to generate cryptography random bytes."); } // set the variant bits[Const.VariantByte] &= Const.VariantByteMask; bits[Const.VariantByte] |= ((int)GuidVariant.Standard << Const.VariantByteShift); // set the version bits[Const.VersionByte] &= Const.VersionByteMask; bits[Const.VersionByte] |= ((int)GuidVersion.Random << Const.VersionByteShift); // create the new System.Guid object guid = new Guid(bits); } finally { // release the crypto provider handle if (hCryptProv != IntPtr.Zero) WinApi.CryptReleaseContext(hCryptProv, 0); } return guid; } } #endif #endregion Compact Framework Helper Classes } }
// 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.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudioTools.Project { internal class AssemblyReferenceNode : ReferenceNode { #region fieds /// <summary> /// The name of the assembly this refernce represents /// </summary> private System.Reflection.AssemblyName assemblyName; private AssemblyName resolvedAssemblyName; private string assemblyPath = string.Empty; /// <summary> /// Defines the listener that would listen on file changes on the nested project node. /// </summary> private FileChangeManager fileChangeListener; /// <summary> /// A flag for specifying if the object was disposed. /// </summary> private bool isDisposed; #endregion #region properties /// <summary> /// The name of the assembly this reference represents. /// </summary> /// <value></value> internal System.Reflection.AssemblyName AssemblyName => this.assemblyName; /// <summary> /// Returns the name of the assembly this reference refers to on this specific /// machine. It can be different from the AssemblyName property because it can /// be more specific. /// </summary> internal System.Reflection.AssemblyName ResolvedAssembly => this.resolvedAssemblyName; public override string Url => this.assemblyPath; public override string Caption => this.assemblyName.Name; private Automation.OAAssemblyReference assemblyRef; internal override object Object { get { if (null == this.assemblyRef) { this.assemblyRef = new Automation.OAAssemblyReference(this); } return this.assemblyRef; } } #endregion #region ctors /// <summary> /// Constructor for the ReferenceNode /// </summary> public AssemblyReferenceNode(ProjectNode root, ProjectElement element) : base(root, element) { this.GetPathNameFromProjectFile(); this.InitializeFileChangeEvents(); if (File.Exists(this.assemblyPath)) { this.fileChangeListener.ObserveItem(this.assemblyPath); } var include = this.ItemNode.GetMetadata(ProjectFileConstants.Include); this.CreateFromAssemblyName(new System.Reflection.AssemblyName(include)); } /// <summary> /// Constructor for the AssemblyReferenceNode /// </summary> public AssemblyReferenceNode(ProjectNode root, string assemblyPath) : base(root) { // Validate the input parameters. if (null == root) { throw new ArgumentNullException("root"); } if (string.IsNullOrEmpty(assemblyPath)) { throw new ArgumentNullException("assemblyPath"); } this.InitializeFileChangeEvents(); // The assemblyPath variable can be an actual path on disk or a generic assembly name. if (File.Exists(assemblyPath)) { // The assemblyPath parameter is an actual file on disk; try to load it. this.assemblyName = System.Reflection.AssemblyName.GetAssemblyName(assemblyPath); this.assemblyPath = assemblyPath; // We register with listeningto chnages onteh path here. The rest of teh cases will call into resolving the assembly and registration is done there. this.fileChangeListener.ObserveItem(this.assemblyPath); } else { // The file does not exist on disk. This can be because the file / path is not // correct or because this is not a path, but an assembly name. // Try to resolve the reference as an assembly name. this.CreateFromAssemblyName(new System.Reflection.AssemblyName(assemblyPath)); } } #endregion #region methods /// <summary> /// Links a reference node to the project and hierarchy. /// </summary> protected override void BindReferenceData() { this.ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread(); Debug.Assert(this.assemblyName != null, "The AssemblyName field has not been initialized"); // If the item has not been set correctly like in case of a new reference added it now. // The constructor for the AssemblyReference node will create a default project item. In that case the Item is null. // We need to specify here the correct project element. if (this.ItemNode == null || this.ItemNode is VirtualProjectElement) { this.ItemNode = new MsBuildProjectElement(this.ProjectMgr, this.assemblyName.FullName, ProjectFileConstants.Reference); } // Set the basic information we know about this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.assemblyName.Name); this.ItemNode.SetMetadata(ProjectFileConstants.AssemblyName, Path.GetFileName(this.assemblyPath)); this.SetReferenceProperties(); } /// <summary> /// Disposes the node /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (this.isDisposed) { return; } try { this.UnregisterFromFileChangeService(); } finally { base.Dispose(disposing); this.isDisposed = true; } } private void CreateFromAssemblyName(AssemblyName name) { this.assemblyName = name; // Use MsBuild to resolve the assemblyname this.ResolveAssemblyReference(); if (string.IsNullOrEmpty(this.assemblyPath) && (this.ItemNode is MsBuildProjectElement)) { // Try to get the assmbly name from the hintpath. this.GetPathNameFromProjectFile(); if (this.assemblyPath == null) { // Try to get the assembly name from the path this.assemblyName = System.Reflection.AssemblyName.GetAssemblyName(this.assemblyPath); } } if (null == this.resolvedAssemblyName) { this.resolvedAssemblyName = this.assemblyName; } } /// <summary> /// Checks if an assembly is already added. The method parses all references and compares the full assemblynames, or the location of the assemblies to decide whether two assemblies are the same. /// </summary> /// <returns>true if the assembly has already been added.</returns> protected override bool IsAlreadyAdded() { var referencesFolder = this.ProjectMgr.GetReferenceContainer() as ReferenceContainerNode; Debug.Assert(referencesFolder != null, "Could not find the References node"); if (referencesFolder == null) { // Return true so that our caller does not try and add us. return true; } var shouldCheckPath = !string.IsNullOrEmpty(this.Url); for (var n = referencesFolder.FirstChild; n != null; n = n.NextSibling) { var assemblyRefererenceNode = n as AssemblyReferenceNode; if (null != assemblyRefererenceNode) { // We will check if the full assemblynames are the same or if the Url of the assemblies is the same. if (StringComparer.OrdinalIgnoreCase.Equals(assemblyRefererenceNode.AssemblyName.FullName, this.assemblyName.FullName) || (shouldCheckPath && CommonUtils.IsSamePath(assemblyRefererenceNode.Url, this.Url))) { return true; } } } return false; } /// <summary> /// Determines if this is node a valid node for painting the default reference icon. /// </summary> /// <returns></returns> protected override bool CanShowDefaultIcon() { return File.Exists(this.assemblyPath); } private void GetPathNameFromProjectFile() { var result = this.ItemNode.GetMetadata(ProjectFileConstants.HintPath); if (string.IsNullOrEmpty(result)) { result = this.ItemNode.GetMetadata(ProjectFileConstants.AssemblyName); if (string.IsNullOrEmpty(result)) { this.assemblyPath = string.Empty; } else if (!result.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { result += ".dll"; this.assemblyPath = result; } } else { this.assemblyPath = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, result); } } protected override void ResolveReference() { this.ResolveAssemblyReference(); } private void SetHintPathAndPrivateValue() { // Private means local copy; we want to know if it is already set to not override the default var privateValue = this.ItemNode.GetMetadata(ProjectFileConstants.Private); // Get the list of items which require HintPath var references = this.ProjectMgr.CurrentConfig.GetItems(MsBuildGeneratedItemType.ReferenceCopyLocalPaths); // Now loop through the generated References to find the corresponding one foreach (var reference in references) { var fileName = Path.GetFileNameWithoutExtension(reference.EvaluatedInclude); if (StringComparer.OrdinalIgnoreCase.Equals(fileName, this.assemblyName.Name)) { // We found it, now set some properties based on this. // Remove the HintPath, we will re-add it below if it is needed if (!string.IsNullOrEmpty(this.assemblyPath)) { this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, null); } var hintPath = reference.GetMetadataValue(ProjectFileConstants.HintPath); if (!string.IsNullOrEmpty(hintPath)) { hintPath = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, hintPath); this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, hintPath); // If this is not already set, we default to true if (string.IsNullOrEmpty(privateValue)) { this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString()); } } break; } } } /// <summary> /// This function ensures that some properies of the reference are set. /// </summary> private void SetReferenceProperties() { this.ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread(); // Set a default HintPath for msbuild to be able to resolve the reference. this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, this.assemblyPath); // Resolve assembly referernces. This is needed to make sure that properties like the full path // to the assembly or the hint path are set. if (!this.ProjectMgr.BuildProject.Targets.ContainsKey(MsBuildTarget.ResolveAssemblyReferences)) { return; } if (this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences) != MSBuildResult.Successful) { return; } // Check if we have to resolve again the path to the assembly. if (string.IsNullOrEmpty(this.assemblyPath)) { ResolveReference(); } // Make sure that the hint path if set (if needed). SetHintPathAndPrivateValue(); } /// <summary> /// Does the actual job of resolving an assembly reference. We need a private method that does not violate /// calling virtual method from the constructor. /// </summary> private void ResolveAssemblyReference() { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return; } var group = this.ProjectMgr.CurrentConfig.GetItems(ProjectFileConstants.ReferencePath); foreach (var item in group) { var fullPath = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, item.EvaluatedInclude); var name = System.Reflection.AssemblyName.GetAssemblyName(fullPath); // Try with full assembly name and then with weak assembly name. if (StringComparer.OrdinalIgnoreCase.Equals(name.FullName, this.assemblyName.FullName) || StringComparer.OrdinalIgnoreCase.Equals(name.Name, this.assemblyName.Name)) { if (!CommonUtils.IsSamePath(fullPath, this.assemblyPath)) { // set the full path now. this.assemblyPath = fullPath; // We have a new item to listen too, since the assembly reference is resolved from a different place. this.fileChangeListener.ObserveItem(this.assemblyPath); } this.resolvedAssemblyName = name; // No hint path is needed since the assembly path will always be resolved. return; } } } /// <summary> /// Registers with File change events /// </summary> private void InitializeFileChangeEvents() { this.fileChangeListener = new FileChangeManager(this.ProjectMgr.Site); this.fileChangeListener.FileChangedOnDisk += this.OnAssemblyReferenceChangedOnDisk; } /// <summary> /// Unregisters this node from file change notifications. /// </summary> private void UnregisterFromFileChangeService() { this.fileChangeListener.FileChangedOnDisk -= this.OnAssemblyReferenceChangedOnDisk; this.fileChangeListener.Dispose(); } /// <summary> /// Event callback. Called when one of the assembly file is changed. /// </summary> /// <param name="sender">The FileChangeManager object.</param> /// <param name="e">Event args containing the file name that was updated.</param> protected virtual void OnAssemblyReferenceChangedOnDisk(object sender, FileChangedOnDiskEventArgs e) { Debug.Assert(e != null, "No event args specified for the FileChangedOnDisk event"); if (e == null) { return; } // We only care about file deletes, so check for one before enumerating references. if ((e.FileChangeFlag & _VSFILECHANGEFLAGS.VSFILECHG_Del) == 0) { return; } if (CommonUtils.IsSamePath(e.FileName, this.assemblyPath)) { this.ProjectMgr.OnInvalidateItems(this.Parent); } } /// <summary> /// Overridden method. The method updates the build dependency list before removing the node from the hierarchy. /// </summary> public override void Remove(bool removeFromStorage) { if (this.ProjectMgr == null) { return; } base.RemoveNonDocument(removeFromStorage); this.ItemNode.RemoveFromProjectFile(); // Notify hierarchy event listeners that items have been invalidated this.ProjectMgr.OnInvalidateItems(this); // Dispose the node now that is deleted. Dispose(true); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Abp.Collections.Extensions; using Abp.Extensions; using Abp.MultiTenancy; using Abp.Runtime.Session; namespace Abp.Domain.Uow { /// <summary> /// Base for all Unit Of Work classes. /// </summary> public abstract class UnitOfWorkBase : IUnitOfWork { public string Id { get; private set; } public IUnitOfWork Outer { get; set; } /// <inheritdoc/> public event EventHandler Completed; /// <inheritdoc/> public event EventHandler<UnitOfWorkFailedEventArgs> Failed; /// <inheritdoc/> public event EventHandler Disposed; /// <inheritdoc/> public UnitOfWorkOptions Options { get; private set; } /// <inheritdoc/> public IReadOnlyList<DataFilterConfiguration> Filters { get { return _filters.ToImmutableList(); } } private readonly List<DataFilterConfiguration> _filters; /// <summary> /// Gets a value indicates that this unit of work is disposed or not. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// Reference to current ABP session. /// </summary> public IAbpSession AbpSession { private get; set; } /// <summary> /// Is <see cref="Begin"/> method called before? /// </summary> private bool _isBeginCalledBefore; /// <summary> /// Is <see cref="Complete"/> method called before? /// </summary> private bool _isCompleteCalledBefore; /// <summary> /// Is this unit of work successfully completed. /// </summary> private bool _succeed; /// <summary> /// A reference to the exception if this unit of work failed. /// </summary> private Exception _exception; /// <summary> /// Constructor. /// </summary> protected UnitOfWorkBase(IUnitOfWorkDefaultOptions defaultOptions) { Id = Guid.NewGuid().ToString("N"); _filters = defaultOptions.Filters.ToList(); AbpSession = NullAbpSession.Instance; } /// <inheritdoc/> public void Begin(UnitOfWorkOptions options) { if (options == null) { throw new ArgumentNullException("options"); } PreventMultipleBegin(); Options = options; //TODO: Do not set options like that! SetFilters(options.FilterOverrides); BeginUow(); } /// <inheritdoc/> public abstract void SaveChanges(); /// <inheritdoc/> public abstract Task SaveChangesAsync(); /// <inheritdoc/> public IDisposable DisableFilter(params string[] filterNames) { //TODO: Check if filters exists? var disabledFilters = new List<string>(); foreach (var filterName in filterNames) { var filterIndex = GetFilterIndex(filterName); if (_filters[filterIndex].IsEnabled) { disabledFilters.Add(filterName); _filters[filterIndex] = new DataFilterConfiguration(filterName, false); } } disabledFilters.ForEach(ApplyDisableFilter); return new DisposeAction(() => EnableFilter(disabledFilters.ToArray())); } /// <inheritdoc/> public IDisposable EnableFilter(params string[] filterNames) { //TODO: Check if filters exists? var enabledFilters = new List<string>(); foreach (var filterName in filterNames) { var filterIndex = GetFilterIndex(filterName); if (!_filters[filterIndex].IsEnabled) { enabledFilters.Add(filterName); _filters[filterIndex] = new DataFilterConfiguration(filterName, true); } } enabledFilters.ForEach(ApplyEnableFilter); return new DisposeAction(() => DisableFilter(enabledFilters.ToArray())); } /// <inheritdoc/> public bool IsFilterEnabled(string filterName) { return GetFilter(filterName).IsEnabled; } /// <inheritdoc/> public IDisposable SetFilterParameter(string filterName, string parameterName, object value) { var filterIndex = GetFilterIndex(filterName); var newfilter = new DataFilterConfiguration(_filters[filterIndex]); //Store old value object oldValue = null; var hasOldValue = newfilter.FilterParameters.ContainsKey(filterName); if (hasOldValue) { oldValue = newfilter.FilterParameters[filterName]; } newfilter.FilterParameters[parameterName] = value; _filters[filterIndex] = newfilter; ApplyFilterParameterValue(filterName, parameterName, value); return new DisposeAction(() => { //Restore old value if (hasOldValue) { SetFilterParameter(filterName, parameterName, oldValue); } }); } /// <inheritdoc/> public void Complete() { PreventMultipleComplete(); try { CompleteUow(); _succeed = true; OnCompleted(); } catch (Exception ex) { _exception = ex; throw; } } /// <inheritdoc/> public async Task CompleteAsync() { PreventMultipleComplete(); try { await CompleteUowAsync(); _succeed = true; OnCompleted(); } catch (Exception ex) { _exception = ex; throw; } } /// <inheritdoc/> public void Dispose() { if (IsDisposed) { return; } IsDisposed = true; if (!_succeed) { OnFailed(_exception); } DisposeUow(); OnDisposed(); } /// <summary> /// Should be implemented by derived classes to start UOW. /// </summary> protected abstract void BeginUow(); /// <summary> /// Should be implemented by derived classes to complete UOW. /// </summary> protected abstract void CompleteUow(); /// <summary> /// Should be implemented by derived classes to complete UOW. /// </summary> protected abstract Task CompleteUowAsync(); /// <summary> /// Should be implemented by derived classes to dispose UOW. /// </summary> protected abstract void DisposeUow(); /// <summary> /// Concrete Unit of work classes should implement this /// method in order to disable a filter. /// Should not call base method since it throws <see cref="NotImplementedException"/>. /// </summary> /// <param name="filterName">Filter name</param> protected virtual void ApplyDisableFilter(string filterName) { throw new NotImplementedException("DisableFilter is not implemented for " + GetType().FullName); } /// <summary> /// Concrete Unit of work classes should implement this /// method in order to enable a filter. /// Should not call base method since it throws <see cref="NotImplementedException"/>. /// </summary> /// <param name="filterName">Filter name</param> protected virtual void ApplyEnableFilter(string filterName) { throw new NotImplementedException("EnableFilter is not implemented for " + GetType().FullName); } /// <summary> /// Concrete Unit of work classes should implement this /// method in order to set a parameter's value. /// Should not call base method since it throws <see cref="NotImplementedException"/>. /// </summary> /// <param name="filterName">Filter name</param> protected virtual void ApplyFilterParameterValue(string filterName, string parameterName, object value) { throw new NotImplementedException("SetFilterParameterValue is not implemented for " + GetType().FullName); } /// <summary> /// Called to trigger <see cref="Completed"/> event. /// </summary> protected virtual void OnCompleted() { Completed.InvokeSafely(this); } /// <summary> /// Called to trigger <see cref="Failed"/> event. /// </summary> /// <param name="exception">Exception that cause failure</param> protected virtual void OnFailed(Exception exception) { Failed.InvokeSafely(this, new UnitOfWorkFailedEventArgs(exception)); } /// <summary> /// Called to trigger <see cref="Disposed"/> event. /// </summary> protected virtual void OnDisposed() { Disposed.InvokeSafely(this); } private void PreventMultipleBegin() { if (_isBeginCalledBefore) { throw new AbpException("This unit of work has started before. Can not call Start method more than once."); } _isBeginCalledBefore = true; } private void PreventMultipleComplete() { if (_isCompleteCalledBefore) { throw new AbpException("Complete is called before!"); } _isCompleteCalledBefore = true; } private void SetFilters(List<DataFilterConfiguration> filterOverrides) { for (var i = 0; i < _filters.Count; i++) { var filterOverride = filterOverrides.FirstOrDefault(f => f.FilterName == _filters[i].FilterName); if (filterOverride != null) { _filters[i] = filterOverride; } } if (!AbpSession.UserId.HasValue || AbpSession.MultiTenancySide == MultiTenancySides.Host) { ChangeFilterIsEnabledIfNotOverrided(filterOverrides, AbpDataFilters.MustHaveTenant, false); } } private void ChangeFilterIsEnabledIfNotOverrided(List<DataFilterConfiguration> filterOverrides, string filterName, bool isEnabled) { if (filterOverrides.Any(f => f.FilterName == filterName)) { return; } var index = _filters.FindIndex(f => f.FilterName == filterName); if (index < 0) { return; } if (_filters[index].IsEnabled == isEnabled) { return; } _filters[index] = new DataFilterConfiguration(filterName, isEnabled); } private DataFilterConfiguration GetFilter(string filterName) { var filter = _filters.FirstOrDefault(f => f.FilterName == filterName); if (filter == null) { throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before."); } return filter; } private int GetFilterIndex(string filterName) { var filterIndex = _filters.FindIndex(f => f.FilterName == filterName); if (filterIndex < 0) { throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before."); } return filterIndex; } } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.Diagnostics; using System.Collections.Specialized; using System.IO; using System.Text; using System.Xml; using System.Xml.XPath; namespace HtmlAgilityPack { /// <summary> /// Represents an HTML navigator on an HTML document seen as a data store. /// </summary> public class HtmlNodeNavigator : XPathNavigator, IXPathNavigable { private HtmlDocument _doc = new HtmlDocument(); private HtmlNode _currentnode; private int _attindex; private HtmlNameTable _nametable = new HtmlNameTable(); internal bool Trace = false; internal HtmlNodeNavigator() { Reset(); } private void Reset() { InternalTrace(null); _currentnode = _doc.DocumentNode; _attindex = -1; } [Conditional("TRACE")] internal void InternalTrace(object Value) { if (!Trace) { return; } string name = null; StackFrame sf = new StackFrame(1, true); name = sf.GetMethod().Name; string nodename; if (_currentnode == null) { nodename = "(null)"; } else { nodename = _currentnode.Name; } string nodevalue; if (_currentnode == null) { nodevalue = "(null)"; } else { switch(_currentnode.NodeType) { case HtmlNodeType.Comment: nodevalue = ((HtmlCommentNode)_currentnode).Comment; break; case HtmlNodeType.Document: nodevalue = ""; break; case HtmlNodeType.Text: nodevalue = ((HtmlTextNode)_currentnode).Text; break; default: nodevalue = _currentnode.CloneNode(false).OuterHtml; break; } } System.Diagnostics.Trace.WriteLine("oid=" + GetHashCode() + ",n=" + nodename + ",a=" + _attindex + "," + ",v=" + nodevalue + "," + Value, "N!"+ name); } internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode) { if (currentNode == null) { throw new ArgumentNullException("currentNode"); } if (currentNode.OwnerDocument != doc) { throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild); } InternalTrace(null); _doc = doc; Reset(); _currentnode = currentNode; } private HtmlNodeNavigator(HtmlNodeNavigator nav) { if (nav == null) { throw new ArgumentNullException("nav"); } InternalTrace(null); _doc = nav._doc; _currentnode = nav._currentnode; _attindex = nav._attindex; _nametable = nav._nametable; // REVIEW: should we do this? } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> public HtmlNodeNavigator(Stream stream) { _doc.Load(stream); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks) { _doc.Load(stream, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding) { _doc.Load(stream, encoding); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) { _doc.Load(stream, encoding, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> /// <param name="buffersize">The minimum buffer size.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { _doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML data into the document.</param> public HtmlNodeNavigator(TextReader reader) { _doc.Load(reader); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> public HtmlNodeNavigator(string path) { _doc.Load(path); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks) { _doc.Load(path, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> public HtmlNodeNavigator(string path, Encoding encoding) { _doc.Load(path, encoding); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) { _doc.Load(path, encoding, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { _doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize); Reset(); } /// <summary> /// Gets the name of the current HTML node without the namespace prefix. /// </summary> public override string LocalName { get { if (_attindex != -1) { InternalTrace("att>" + _currentnode.Attributes[_attindex].Name); return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name); } else { InternalTrace("node>" + _currentnode.Name); return _nametable.GetOrAdd(_currentnode.Name); } } } /// <summary> /// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string NamespaceURI { get { InternalTrace(">"); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the qualified name of the current node. /// </summary> public override string Name { get { InternalTrace(">" + _currentnode.Name); return _nametable.GetOrAdd(_currentnode.Name); } } /// <summary> /// Gets the prefix associated with the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string Prefix { get { InternalTrace(null); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the type of the current node. /// </summary> public override XPathNodeType NodeType { get { switch(_currentnode.NodeType) { case HtmlNodeType.Comment: InternalTrace(">" + XPathNodeType.Comment); return XPathNodeType.Comment; case HtmlNodeType.Document: InternalTrace(">" + XPathNodeType.Root); return XPathNodeType.Root; case HtmlNodeType.Text: InternalTrace(">" + XPathNodeType.Text); return XPathNodeType.Text; case HtmlNodeType.Element: { if (_attindex != -1) { InternalTrace(">" + XPathNodeType.Attribute); return XPathNodeType.Attribute; } InternalTrace(">" + XPathNodeType.Element); return XPathNodeType.Element; } default: throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType); } } } /// <summary> /// Gets the text value of the current node. /// </summary> public override string Value { get { InternalTrace("nt=" + _currentnode.NodeType); switch(_currentnode.NodeType) { case HtmlNodeType.Comment: InternalTrace(">" + ((HtmlCommentNode)_currentnode).Comment); return ((HtmlCommentNode)_currentnode).Comment; case HtmlNodeType.Document: InternalTrace(">"); return ""; case HtmlNodeType.Text: InternalTrace(">" + ((HtmlTextNode)_currentnode).Text); return ((HtmlTextNode)_currentnode).Text; case HtmlNodeType.Element: { if (_attindex != -1) { InternalTrace(">" + _currentnode.Attributes[_attindex].Value); return _currentnode.Attributes[_attindex].Value; } return _currentnode.InnerText; } default: throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType); } } } /// <summary> /// Gets the base URI for the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string BaseURI { get { InternalTrace(">"); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the xml:lang scope for the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string XmlLang { get { InternalTrace(null); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets a value indicating whether the current node is an empty element. /// </summary> public override bool IsEmptyElement { get { InternalTrace(">" + !HasChildren); // REVIEW: is this ok? return !HasChildren; } } /// <summary> /// Gets the XmlNameTable associated with this implementation. /// </summary> public override XmlNameTable NameTable { get { InternalTrace(null); return _nametable; } } /// <summary> /// Gets a value indicating whether the current node has child nodes. /// </summary> public override bool HasAttributes { get { InternalTrace(">" + (_currentnode.Attributes.Count>0)); return (_currentnode.Attributes.Count>0); } } /// <summary> /// Gets a value indicating whether the current node has child nodes. /// </summary> public override bool HasChildren { get { InternalTrace(">" + (_currentnode.ChildNodes.Count>0)); return (_currentnode.ChildNodes.Count>0); } } /// <summary> /// Moves to the next sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns> public override bool MoveToNext() { if (_currentnode.NextSibling == null) { InternalTrace(">false"); return false; } InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml); InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml); _currentnode = _currentnode.NextSibling; InternalTrace(">true"); return true; } /// <summary> /// Moves to the previous sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns> public override bool MoveToPrevious() { if (_currentnode.PreviousSibling == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.PreviousSibling; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns> public override bool MoveToFirst() { if (_currentnode.ParentNode == null) { InternalTrace(">false"); return false; } if (_currentnode.ParentNode.FirstChild == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ParentNode.FirstChild; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first child of the current node. /// </summary> /// <returns>true if there is a first child node, otherwise false.</returns> public override bool MoveToFirstChild() { if (!_currentnode.HasChildNodes) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ChildNodes[0]; InternalTrace(">true"); return true; } /// <summary> /// Moves to the parent of the current node. /// </summary> /// <returns>true if there is a parent node, otherwise false.</returns> public override bool MoveToParent() { if (_currentnode.ParentNode == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ParentNode; InternalTrace(">true"); return true; } /// <summary> /// Moves to the root node to which the current node belongs. /// </summary> public override void MoveToRoot() { _currentnode = _doc.DocumentNode; InternalTrace(null); } /// <summary> /// Moves to the same position as the specified HtmlNavigator. /// </summary> /// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param> /// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns> public override bool MoveTo(XPathNavigator other) { HtmlNodeNavigator nav = other as HtmlNodeNavigator; if (nav == null) { InternalTrace(">false (nav is not an HtmlNodeNavigator)"); return false; } InternalTrace("moveto oid=" + nav.GetHashCode() + ", n:" + nav._currentnode.Name + ", a:" + nav._attindex); if (nav._doc == _doc) { _currentnode = nav._currentnode; _attindex = nav._attindex; InternalTrace(">true"); return true; } // we don't know how to handle that InternalTrace(">false (???)"); return false; } /// <summary> /// Moves to the node that has an attribute of type ID whose value matches the specified string. /// </summary> /// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param> /// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns> public override bool MoveToId(string id) { InternalTrace("id=" + id); HtmlNode node = _doc.GetElementbyId(id); if (node == null) { InternalTrace(">false"); return false; } _currentnode = node; InternalTrace(">true"); return true; } /// <summary> /// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator. /// </summary> /// <param name="other">The HtmlNavigator that you want to compare against.</param> /// <returns>true if the two navigators have the same position, otherwise, false.</returns> public override bool IsSamePosition(XPathNavigator other) { HtmlNodeNavigator nav = other as HtmlNodeNavigator; if (nav == null) { InternalTrace(">false"); return false; } InternalTrace(">" + (nav._currentnode == _currentnode)); return (nav._currentnode == _currentnode); } /// <summary> /// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator. /// </summary> /// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns> public override XPathNavigator Clone() { InternalTrace(null); return new HtmlNodeNavigator(this); } /// <summary> /// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI. /// </summary> /// <param name="localName">The local name of the HTML attribute.</param> /// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param> /// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns> public override string GetAttribute(string localName, string namespaceURI) { InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI); HtmlAttribute att = _currentnode.Attributes[localName]; if (att == null) { InternalTrace(">null"); return null; } InternalTrace(">" + att.Value); return att.Value; } /// <summary> /// Moves to the HTML attribute with matching LocalName and NamespaceURI. /// </summary> /// <param name="localName">The local name of the HTML attribute.</param> /// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param> /// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns> public override bool MoveToAttribute(string localName, string namespaceURI) { InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI); int index = _currentnode.Attributes.GetAttributeIndex(localName); if (index == -1) { InternalTrace(">false"); return false; } _attindex = index; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first HTML attribute. /// </summary> /// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns> public override bool MoveToFirstAttribute() { if (!HasAttributes) { InternalTrace(">false"); return false; } _attindex = 0; InternalTrace(">true"); return true; } /// <summary> /// Moves to the next HTML attribute. /// </summary> /// <returns></returns> public override bool MoveToNextAttribute() { InternalTrace(null); if (_attindex>=(_currentnode.Attributes.Count-1)) { InternalTrace(">false"); return false; } _attindex++; InternalTrace(">true"); return true; } /// <summary> /// Returns the value of the namespace node corresponding to the specified local name. /// Always returns string.Empty for the HtmlNavigator implementation. /// </summary> /// <param name="name">The local name of the namespace node.</param> /// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns> public override string GetNamespace(string name) { InternalTrace("name=" + name); return string.Empty; } /// <summary> /// Moves the XPathNavigator to the namespace node with the specified local name. /// Always returns false for the HtmlNavigator implementation. /// </summary> /// <param name="name">The local name of the namespace node.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToNamespace(string name) { InternalTrace("name=" + name); return false; } /// <summary> /// Moves the XPathNavigator to the first namespace node of the current element. /// Always returns false for the HtmlNavigator implementation. /// </summary> /// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { InternalTrace(null); return false; } /// <summary> /// Moves the XPathNavigator to the next namespace node. /// Always returns falsefor the HtmlNavigator implementation. /// </summary> /// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { InternalTrace(null); return false; } /// <summary> /// Gets the current HTML node. /// </summary> public HtmlNode CurrentNode { get { return _currentnode; } } /// <summary> /// Gets the current HTML document. /// </summary> public HtmlDocument CurrentDocument { get { return _doc; } } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using Scientia.HtmlRenderer.Adapters.Entities; using Scientia.HtmlRenderer.Core.Utils; namespace Scientia.HtmlRenderer.Adapters { /// <summary> /// Adapter for platform specific graphics rendering object - used to render graphics and text in platform specific context.<br/> /// The core HTML Renderer components use this class for rendering logic, extending this /// class in different platform: WinForms, WPF, Metro, PDF, etc. /// </summary> public abstract class RGraphics : IDisposable { #region Fields/Consts /// <summary> /// the global adapter /// </summary> protected readonly RAdapter Adapter; /// <summary> /// The clipping bound stack as clips are pushed/poped to/from the graphics /// </summary> protected readonly Stack<RRect> ClipStack = new Stack<RRect>(); /// <summary> /// The suspended clips /// </summary> private Stack<RRect> SuspendedClips = new Stack<RRect>(); #endregion /// <summary> /// Init. /// </summary> protected RGraphics(RAdapter adapter, RRect initialClip) { ArgChecker.AssertArgNotNull(adapter, "global"); this.Adapter = adapter; this.ClipStack.Push(initialClip); } /// <summary> /// Get color pen. /// </summary> /// <param name="color">the color to get the pen for</param> /// <returns>pen instance</returns> public RPen GetPen(RColor color) { return this.Adapter.GetPen(color); } /// <summary> /// Get solid color brush. /// </summary> /// <param name="color">the color to get the brush for</param> /// <returns>solid color brush instance</returns> public RBrush GetSolidBrush(RColor color) { return this.Adapter.GetSolidBrush(color); } /// <summary> /// Get linear gradient color brush from <paramref name="color1"/> to <paramref name="color2"/>. /// </summary> /// <param name="rect">the rectangle to get the brush for</param> /// <param name="color1">the start color of the gradient</param> /// <param name="color2">the end color of the gradient</param> /// <param name="angle">the angle to move the gradient from start color to end color in the rectangle</param> /// <returns>linear gradient color brush instance</returns> public RBrush GetLinearGradientBrush(RRect rect, RColor color1, RColor color2, double angle) { return this.Adapter.GetLinearGradientBrush(rect, color1, color2, angle); } /// <summary> /// Gets a Rectangle structure that bounds the clipping region of this Graphics. /// </summary> /// <returns>A rectangle structure that represents a bounding rectangle for the clipping region of this Graphics.</returns> public RRect GetClip() { return this.ClipStack.Peek(); } /// <summary> /// Pop the latest clip push. /// </summary> public abstract void PopClip(); /// <summary> /// Push the clipping region of this Graphics to interception of current clipping rectangle and the given rectangle. /// </summary> /// <param name="rect">Rectangle to clip to.</param> public abstract void PushClip(RRect rect); /// <summary> /// Push the clipping region of this Graphics to exclude the given rectangle from the current clipping rectangle. /// </summary> /// <param name="rect">Rectangle to exclude clipping in.</param> public abstract void PushClipExclude(RRect rect); /// <summary> /// Restore the clipping region to the initial clip. /// </summary> public void SuspendClipping() { while (this.ClipStack.Count > 1) { var clip = this.GetClip(); this.SuspendedClips.Push(clip); this.PopClip(); } } /// <summary> /// Resumes the suspended clips. /// </summary> public void ResumeClipping() { while (this.SuspendedClips.Count > 0) { var clip = this.SuspendedClips.Pop(); this.PushClip(clip); } } /// <summary> /// Set the graphics smooth mode to use anti-alias.<br/> /// Use <see cref="ReturnPreviousSmoothingMode"/> to return back the mode used. /// </summary> /// <returns>the previous smooth mode before the change</returns> public abstract Object SetAntiAliasSmoothingMode(); /// <summary> /// Return to previous smooth mode before anti-alias was set as returned from <see cref="SetAntiAliasSmoothingMode"/>. /// </summary> /// <param name="prevMode">the previous mode to set</param> public abstract void ReturnPreviousSmoothingMode(Object prevMode); /// <summary> /// Get TextureBrush object that uses the specified image and bounding rectangle. /// </summary> /// <param name="image">The Image object with which this TextureBrush object fills interiors.</param> /// <param name="dstRect">A Rectangle structure that represents the bounding rectangle for this TextureBrush object.</param> /// <param name="translateTransformLocation">The dimension by which to translate the transformation</param> public abstract RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation); /// <summary> /// Get GraphicsPath object. /// </summary> /// <returns>graphics path instance</returns> public abstract RGraphicsPath GetGraphicsPath(); /// <summary> /// Measure the width and height of string <paramref name="str"/> when drawn on device context HDC /// using the given font <paramref name="font"/>. /// </summary> /// <param name="str">the string to measure</param> /// <param name="font">the font to measure string with</param> /// <returns>the size of the string</returns> public abstract RSize MeasureString(string str, RFont font); /// <summary> /// Measure the width of string under max width restriction calculating the number of characters that can fit and the width those characters take.<br/> /// Not relevant for platforms that don't render HTML on UI element. /// </summary> /// <param name="str">the string to measure</param> /// <param name="font">the font to measure string with</param> /// <param name="maxWidth">the max width to calculate fit characters</param> /// <param name="charFit">the number of characters that will fit under <see cref="maxWidth"/> restriction</param> /// <param name="charFitWidth">the width that only the characters that fit into max width take</param> public abstract void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth); /// <summary> /// Draw the given string using the given font and foreground color at given location. /// </summary> /// <param name="str">the string to draw</param> /// <param name="font">the font to use to draw the string</param> /// <param name="color">the text color to set</param> /// <param name="point">the location to start string draw (top-left)</param> /// <param name="size">used to know the size of the rendered text for transparent text support</param> /// <param name="rtl">is to render the string right-to-left (true - RTL, false - LTR)</param> public abstract void DrawString(String str, RFont font, RColor color, RPoint point, RSize size, bool rtl); /// <summary> /// Draws a line connecting the two points specified by the coordinate pairs. /// </summary> /// <param name="pen">Pen that determines the color, width, and style of the line. </param> /// <param name="x1">The x-coordinate of the first point. </param> /// <param name="y1">The y-coordinate of the first point. </param> /// <param name="x2">The x-coordinate of the second point. </param> /// <param name="y2">The y-coordinate of the second point. </param> public abstract void DrawLine(RPen pen, double x1, double y1, double x2, double y2); /// <summary> /// Draws a rectangle specified by a coordinate pair, a width, and a height. /// </summary> /// <param name="pen">A Pen that determines the color, width, and style of the rectangle. </param> /// <param name="x">The x-coordinate of the upper-left corner of the rectangle to draw. </param> /// <param name="y">The y-coordinate of the upper-left corner of the rectangle to draw. </param> /// <param name="width">The width of the rectangle to draw. </param> /// <param name="height">The height of the rectangle to draw. </param> public abstract void DrawRectangle(RPen pen, double x, double y, double width, double height); /// <summary> /// Fills the interior of a rectangle specified by a pair of coordinates, a width, and a height. /// </summary> /// <param name="brush">Brush that determines the characteristics of the fill. </param> /// <param name="x">The x-coordinate of the upper-left corner of the rectangle to fill. </param> /// <param name="y">The y-coordinate of the upper-left corner of the rectangle to fill. </param> /// <param name="width">Width of the rectangle to fill. </param> /// <param name="height">Height of the rectangle to fill. </param> public abstract void DrawRectangle(RBrush brush, double x, double y, double width, double height); /// <summary> /// Draws the specified portion of the specified <see cref="RImage"/> at the specified location and with the specified size. /// </summary> /// <param name="image">Image to draw. </param> /// <param name="destRect">Rectangle structure that specifies the location and size of the drawn image. The image is scaled to fit the rectangle. </param> /// <param name="srcRect">Rectangle structure that specifies the portion of the <paramref name="image"/> object to draw. </param> public abstract void DrawImage(RImage image, RRect destRect, RRect srcRect); /// <summary> /// Draws the specified Image at the specified location and with the specified size. /// </summary> /// <param name="image">Image to draw. </param> /// <param name="destRect">Rectangle structure that specifies the location and size of the drawn image. </param> public abstract void DrawImage(RImage image, RRect destRect); /// <summary> /// Draws a GraphicsPath. /// </summary> /// <param name="pen">Pen that determines the color, width, and style of the path. </param> /// <param name="path">GraphicsPath to draw. </param> public abstract void DrawPath(RPen pen, RGraphicsPath path); /// <summary> /// Fills the interior of a GraphicsPath. /// </summary> /// <param name="brush">Brush that determines the characteristics of the fill. </param> /// <param name="path">GraphicsPath that represents the path to fill. </param> public abstract void DrawPath(RBrush brush, RGraphicsPath path); /// <summary> /// Fills the interior of a polygon defined by an array of points specified by Point structures. /// </summary> /// <param name="brush">Brush that determines the characteristics of the fill. </param> /// <param name="points">Array of Point structures that represent the vertices of the polygon to fill. </param> public abstract void DrawPolygon(RBrush brush, RPoint[] points); /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public abstract void Dispose(); } }
namespace SandcastleBuilder.PlugIns { partial class CompletionNotificationConfigDlg { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.lnkCodePlexSHFB = new System.Windows.Forms.LinkLabel(); this.epErrors = new System.Windows.Forms.ErrorProvider(this.components); this.txtFailureEMailAddress = new System.Windows.Forms.TextBox(); this.txtSuccessEMailAddress = new System.Windows.Forms.TextBox(); this.txtPassword = new System.Windows.Forms.TextBox(); this.txtUserName = new System.Windows.Forms.TextBox(); this.txtFromEMail = new System.Windows.Forms.TextBox(); this.pnlOptions = new System.Windows.Forms.Panel(); this.txtXSLTransform = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.chkAttachLogFileOnFailure = new System.Windows.Forms.CheckBox(); this.chkAttachLogFileOnSuccess = new System.Windows.Forms.CheckBox(); this.chkUseDefaultCredentials = new System.Windows.Forms.CheckBox(); this.udcSmtpPort = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtSmtpServer = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.epErrors)).BeginInit(); this.pnlOptions.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.udcSmtpPort)).BeginInit(); this.SuspendLayout(); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(566, 280); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(88, 32); this.btnCancel.TabIndex = 2; this.btnCancel.Text = "Cancel"; this.toolTip1.SetToolTip(this.btnCancel, "Exit without saving changes"); this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnOK // this.btnOK.Location = new System.Drawing.Point(12, 280); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(88, 32); this.btnOK.TabIndex = 1; this.btnOK.Text = "OK"; this.toolTip1.SetToolTip(this.btnOK, "Save changes to configuration"); this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // lnkCodePlexSHFB // this.lnkCodePlexSHFB.Location = new System.Drawing.Point(224, 285); this.lnkCodePlexSHFB.Name = "lnkCodePlexSHFB"; this.lnkCodePlexSHFB.Size = new System.Drawing.Size(218, 23); this.lnkCodePlexSHFB.TabIndex = 3; this.lnkCodePlexSHFB.TabStop = true; this.lnkCodePlexSHFB.Text = "Sandcastle Help File Builder"; this.lnkCodePlexSHFB.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.toolTip1.SetToolTip(this.lnkCodePlexSHFB, "http://SHFB.CodePlex.com"); this.lnkCodePlexSHFB.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkCodePlexSHFB_LinkClicked); // // epErrors // this.epErrors.ContainerControl = this; // // txtFailureEMailAddress // this.txtFailureEMailAddress.Location = new System.Drawing.Point(180, 143); this.txtFailureEMailAddress.MaxLength = 256; this.txtFailureEMailAddress.Name = "txtFailureEMailAddress"; this.txtFailureEMailAddress.Size = new System.Drawing.Size(412, 22); this.txtFailureEMailAddress.TabIndex = 14; // // txtSuccessEMailAddress // this.txtSuccessEMailAddress.Location = new System.Drawing.Point(180, 115); this.txtSuccessEMailAddress.MaxLength = 256; this.txtSuccessEMailAddress.Name = "txtSuccessEMailAddress"; this.txtSuccessEMailAddress.Size = new System.Drawing.Size(412, 22); this.txtSuccessEMailAddress.TabIndex = 12; // // txtPassword // this.txtPassword.Enabled = false; this.txtPassword.Location = new System.Drawing.Point(450, 59); this.txtPassword.MaxLength = 50; this.txtPassword.Name = "txtPassword"; this.txtPassword.Size = new System.Drawing.Size(164, 22); this.txtPassword.TabIndex = 8; // // txtUserName // this.txtUserName.Enabled = false; this.txtUserName.Location = new System.Drawing.Point(180, 59); this.txtUserName.MaxLength = 50; this.txtUserName.Name = "txtUserName"; this.txtUserName.Size = new System.Drawing.Size(164, 22); this.txtUserName.TabIndex = 6; // // txtFromEMail // this.txtFromEMail.Location = new System.Drawing.Point(180, 87); this.txtFromEMail.MaxLength = 256; this.txtFromEMail.Name = "txtFromEMail"; this.txtFromEMail.Size = new System.Drawing.Size(412, 22); this.txtFromEMail.TabIndex = 10; // // pnlOptions // this.pnlOptions.Controls.Add(this.txtXSLTransform); this.pnlOptions.Controls.Add(this.label8); this.pnlOptions.Controls.Add(this.txtFromEMail); this.pnlOptions.Controls.Add(this.label7); this.pnlOptions.Controls.Add(this.txtFailureEMailAddress); this.pnlOptions.Controls.Add(this.label4); this.pnlOptions.Controls.Add(this.txtSuccessEMailAddress); this.pnlOptions.Controls.Add(this.label6); this.pnlOptions.Controls.Add(this.chkAttachLogFileOnFailure); this.pnlOptions.Controls.Add(this.chkAttachLogFileOnSuccess); this.pnlOptions.Controls.Add(this.chkUseDefaultCredentials); this.pnlOptions.Controls.Add(this.udcSmtpPort); this.pnlOptions.Controls.Add(this.label5); this.pnlOptions.Controls.Add(this.txtPassword); this.pnlOptions.Controls.Add(this.label3); this.pnlOptions.Controls.Add(this.txtUserName); this.pnlOptions.Controls.Add(this.label2); this.pnlOptions.Controls.Add(this.txtSmtpServer); this.pnlOptions.Controls.Add(this.label1); this.pnlOptions.Location = new System.Drawing.Point(12, 12); this.pnlOptions.Name = "pnlOptions"; this.pnlOptions.Size = new System.Drawing.Size(642, 260); this.pnlOptions.TabIndex = 0; // // txtXSLTransform // this.txtXSLTransform.Location = new System.Drawing.Point(180, 225); this.txtXSLTransform.MaxLength = 256; this.txtXSLTransform.Name = "txtXSLTransform"; this.txtXSLTransform.Size = new System.Drawing.Size(412, 22); this.txtXSLTransform.TabIndex = 18; this.txtXSLTransform.Text = "{@SHFBFolder}Templates\\TransformBuildLog.xsl"; // // label8 // this.label8.Location = new System.Drawing.Point(8, 225); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(166, 23); this.label8.TabIndex = 17; this.label8.Text = "&Optional XSL Transform"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label7 // this.label7.Location = new System.Drawing.Point(8, 87); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(166, 23); this.label7.TabIndex = 9; this.label7.Text = "&From E-Mail Address"; this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label4 // this.label4.Location = new System.Drawing.Point(8, 143); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(166, 23); this.label4.TabIndex = 13; this.label4.Text = "Failure E-Mail &Address"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label6 // this.label6.Location = new System.Drawing.Point(8, 115); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(166, 23); this.label6.TabIndex = 11; this.label6.Text = "Success &E-Mail Address"; this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // chkAttachLogFileOnFailure // this.chkAttachLogFileOnFailure.Checked = true; this.chkAttachLogFileOnFailure.CheckState = System.Windows.Forms.CheckState.Checked; this.chkAttachLogFileOnFailure.Location = new System.Drawing.Point(180, 198); this.chkAttachLogFileOnFailure.Name = "chkAttachLogFileOnFailure"; this.chkAttachLogFileOnFailure.Size = new System.Drawing.Size(265, 21); this.chkAttachLogFileOnFailure.TabIndex = 16; this.chkAttachLogFileOnFailure.Text = "A&ttach build log on failed build"; this.chkAttachLogFileOnFailure.UseVisualStyleBackColor = true; // // chkAttachLogFileOnSuccess // this.chkAttachLogFileOnSuccess.Location = new System.Drawing.Point(180, 171); this.chkAttachLogFileOnSuccess.Name = "chkAttachLogFileOnSuccess"; this.chkAttachLogFileOnSuccess.Size = new System.Drawing.Size(265, 21); this.chkAttachLogFileOnSuccess.TabIndex = 15; this.chkAttachLogFileOnSuccess.Text = "Attach &build log on successful build"; this.chkAttachLogFileOnSuccess.UseVisualStyleBackColor = true; // // chkUseDefaultCredentials // this.chkUseDefaultCredentials.Checked = true; this.chkUseDefaultCredentials.CheckState = System.Windows.Forms.CheckState.Checked; this.chkUseDefaultCredentials.Location = new System.Drawing.Point(180, 35); this.chkUseDefaultCredentials.Name = "chkUseDefaultCredentials"; this.chkUseDefaultCredentials.Size = new System.Drawing.Size(190, 21); this.chkUseDefaultCredentials.TabIndex = 4; this.chkUseDefaultCredentials.Text = "Use &Default Credentials"; this.chkUseDefaultCredentials.UseVisualStyleBackColor = true; this.chkUseDefaultCredentials.CheckedChanged += new System.EventHandler(this.chkUseDefaultCredentials_CheckedChanged); // // udcSmtpPort // this.udcSmtpPort.Location = new System.Drawing.Point(572, 8); this.udcSmtpPort.Maximum = new decimal(new int[] { 999, 0, 0, 0}); this.udcSmtpPort.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.udcSmtpPort.Name = "udcSmtpPort"; this.udcSmtpPort.Size = new System.Drawing.Size(56, 22); this.udcSmtpPort.TabIndex = 3; this.udcSmtpPort.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.udcSmtpPort.Value = new decimal(new int[] { 25, 0, 0, 0}); // // label5 // this.label5.Location = new System.Drawing.Point(509, 7); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(57, 23); this.label5.TabIndex = 2; this.label5.Text = "&Port #"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label3 // this.label3.Location = new System.Drawing.Point(363, 59); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(81, 23); this.label3.TabIndex = 7; this.label3.Text = "Pass&word"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label2 // this.label2.Location = new System.Drawing.Point(86, 59); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(88, 23); this.label2.TabIndex = 5; this.label2.Text = "&User Name"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // txtSmtpServer // this.txtSmtpServer.Location = new System.Drawing.Point(180, 7); this.txtSmtpServer.MaxLength = 256; this.txtSmtpServer.Name = "txtSmtpServer"; this.txtSmtpServer.Size = new System.Drawing.Size(318, 22); this.txtSmtpServer.TabIndex = 1; // // label1 // this.label1.Location = new System.Drawing.Point(67, 7); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(107, 23); this.label1.TabIndex = 0; this.label1.Text = "SMTP &Server"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // CompletionNotificationConfigDlg // this.AcceptButton = this.btnOK; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(666, 324); this.Controls.Add(this.pnlOptions); this.Controls.Add(this.lnkCodePlexSHFB); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "CompletionNotificationConfigDlg"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Configure Completion Notification Plug-In"; ((System.ComponentModel.ISupportInitialize)(this.epErrors)).EndInit(); this.pnlOptions.ResumeLayout(false); this.pnlOptions.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.udcSmtpPort)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.ErrorProvider epErrors; private System.Windows.Forms.LinkLabel lnkCodePlexSHFB; private System.Windows.Forms.Panel pnlOptions; private System.Windows.Forms.TextBox txtFailureEMailAddress; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtSuccessEMailAddress; private System.Windows.Forms.Label label6; private System.Windows.Forms.CheckBox chkAttachLogFileOnFailure; private System.Windows.Forms.CheckBox chkAttachLogFileOnSuccess; private System.Windows.Forms.CheckBox chkUseDefaultCredentials; private System.Windows.Forms.NumericUpDown udcSmtpPort; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtUserName; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtSmtpServer; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtFromEMail; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtXSLTransform; private System.Windows.Forms.Label label8; } }
// 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.Xml.Schema; using Xunit; using Xunit.Abstractions; namespace System.Xml.Tests { public class TC_SchemaSet_Add_SchemaSet : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_Add_SchemaSet(ITestOutputHelper output) { _output = output; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v1 - sc = null", Priority = 0)] public void v1() { try { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add((XmlSchemaSet)null); } catch (ArgumentNullException) { return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v2 - sc = empty SchemaSet", Priority = 0)] public void v2() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaSet scnew = new XmlSchemaSet(); sc.Add(scnew); Assert.Equal(sc.Count, 0); return; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v3 - sc = non empty SchemaSet, add with duplicate schemas", Priority = 0)] public void v3() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaSet scnew = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); scnew.Add("xsdauthor", TestData._XsdAuthor); sc.Add(scnew); // adding schemaset with same schema should be ignored Assert.Equal(sc.Count, 1); return; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v4 - sc = self", Priority = 0)] public void v4() { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(sc); Assert.Equal(sc.Count, 1); return; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v5 - sc = scnew, scnew as some duplicate but some unique schemas")] public void v5() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaSet scnew = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); scnew.Add(null, TestData._XsdNoNs); scnew.Add(null, TestData._FileXSD1); sc.Add(scnew); Assert.Equal(sc.Count, 3); return; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v6 - sc = add second set with all new schemas")] public void v6() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaSet scnew = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); scnew.Add(null, TestData._FileXSD1); scnew.Add(null, TestData._FileXSD2); sc.Add(scnew); Assert.Equal(sc.Count, 4); return; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v7 - sc = add second set with a conflicting schema")] public void v7() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaSet scnew = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); scnew.Add(null, TestData._FileXSD1); scnew.Add(null, TestData._XsdAuthorDup); // this conflicts with _XsdAuthor sc.Add(scnew); Assert.Equal(sc.IsCompiled, false); Assert.Equal(sc.Count, 4); //ok try { sc.Compile(); // should fail } catch (XmlSchemaException) { return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v8 - sc = add second set with a conflicting schema to compiled set")] public void v8() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaSet scnew = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); sc.Compile(); Assert.Equal(sc.IsCompiled, true); scnew.Add(null, TestData._FileXSD1); scnew.Add(null, TestData._XsdAuthorDup); // this conflicts with _XsdAuthor sc.Add(scnew); Assert.Equal(sc.IsCompiled, false); Assert.Equal(sc.Count, 4); //ok try { sc.Compile(); // should fail } catch (XmlSchemaException) { return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v9 - sc = add compiled second set with a conflicting schema to compiled set")] public void v9() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaSet scnew = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); sc.Compile(); Assert.Equal(sc.IsCompiled, true); scnew.Add(null, TestData._FileXSD1); scnew.Add(null, TestData._XsdAuthorDup); // this conflicts with _XsdAuthor scnew.Compile(); try { sc.Add(scnew); } catch (XmlSchemaException) { return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v10 - set1 added to set2 with set1 containing an invalid schema")] public void v10() { XmlSchemaSet schemaSet1 = new XmlSchemaSet(); XmlSchemaSet schemaSet2 = new XmlSchemaSet(); XmlSchema schema1 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdAuthor, FileMode.Open, FileAccess.Read)), null); XmlSchema schema2 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdNoNs, FileMode.Open, FileAccess.Read)), null); schemaSet1.Add(schema1); schemaSet1.Add(schema2); // added two schemas XmlSchemaElement elem = new XmlSchemaElement(); schema1.Items.Add(elem); // make the first schema dirty //the following throws an exception try { schemaSet2.Add(schemaSet1); // shound not reach here } catch (XmlSchemaException) { Assert.Equal(schemaSet2.Count, 0); // no schema should be added Assert.Equal(schemaSet1.Count, 2); // no schema should be added Assert.Equal(schemaSet2.IsCompiled, false); // no schema should be added Assert.Equal(schemaSet1.IsCompiled, false); // no schema should be added return; } Assert.Equal(schemaSet2.Count, 0); // no schema should be added Assert.True(false); } [Fact] //[Variation(Desc = "v11 - Add three XmlSchema to Set1 then add Set1 to uncompiled Set2")] public void v11() { XmlSchemaSet schemaSet1 = new XmlSchemaSet(); XmlSchemaSet schemaSet2 = new XmlSchemaSet(); XmlSchema schema1 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdAuthor, FileMode.Open, FileAccess.Read)), null); XmlSchema schema2 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdNoNs, FileMode.Open, FileAccess.Read)), null); XmlSchema schema3 = XmlSchema.Read(new StreamReader(new FileStream(TestData._FileXSD1, FileMode.Open, FileAccess.Read)), null); schemaSet1.Add(schema1); schemaSet1.Add(schema2); // added two schemas schemaSet1.Add(schema3); // added third schemaSet1.Compile(); //the following throws an exception try { schemaSet2.Add(schemaSet1); Assert.Equal(schemaSet1.Count, 3); // no schema should be added Assert.Equal(schemaSet2.Count, 3); // no schema should be added Assert.Equal(schemaSet1.IsCompiled, true); // no schema should be added schemaSet2.Compile(); Assert.Equal(schemaSet2.IsCompiled, true); // no schema should be added // shound not reach here } catch (XmlSchemaException) { Assert.True(false); } return; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Azure.Management.RecoveryServices.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices { /// <summary> /// Definition of cloud service operations for the Recovery services /// extension. /// </summary> internal partial class ResourceGroupsOperations : IServiceOperations<RecoveryServicesManagementClient>, IResourceGroupsOperations { /// <summary> /// Initializes a new instance of the ResourceGroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ResourceGroupsOperations(RecoveryServicesManagementClient client) { this._client = client; } private RecoveryServicesManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.RecoveryServicesManagementClient. /// </summary> public RecoveryServicesManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve a list of Resource Groups /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list resource group operation. /// </returns> public async Task<ResourceGroupListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceGroupListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceGroupListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ResourceGroup resourceGroupInstance = new ResourceGroup(); result.ResourceGroups.Add(resourceGroupInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ResourceGroupProperties propertiesInstance = new ResourceGroupProperties(); resourceGroupInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceGroupInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceGroupInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); resourceGroupInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceGroupInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceGroupInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using NUnit.Framework; using Assert = ModestTree.Assert; namespace Zenject.Tests.Injection { [TestFixture] public class TestTestOptional : ZenjectUnitTestFixture { class Test1 { } class Test2 { [Inject] public Test1 val1 = null; } class Test3 { [InjectOptional] public Test1 val1 = null; } class Test0 { [InjectOptional] public int Val1 = 5; } [Test] public void TestFieldRequired() { Container.Bind<Test2>().AsSingle().NonLazy(); Assert.Throws( delegate { Container.Resolve<Test2>(); }); } [Test] public void TestFieldOptional() { Container.Bind<Test3>().AsSingle().NonLazy(); var test = Container.Resolve<Test3>(); Assert.That(test.val1 == null); } [Test] public void TestFieldOptional2() { Container.Bind<Test3>().AsSingle().NonLazy(); var test1 = new Test1(); Container.Bind<Test1>().FromInstance(test1).NonLazy(); Assert.IsEqual(Container.Resolve<Test3>().val1, test1); } [Test] public void TestFieldOptional3() { Container.Bind<Test0>().AsTransient().NonLazy(); // Should not redefine the hard coded value in this case Assert.IsEqual(Container.Resolve<Test0>().Val1, 5); Container.Bind<int>().FromInstance(3).NonLazy(); Assert.IsEqual(Container.Resolve<Test0>().Val1, 3); } class Test4 { public Test4(Test1 val1) { } } class Test5 { public Test1 Val1; public Test5( [InjectOptional] Test1 val1) { Val1 = val1; } } [Test] public void TestParameterRequired() { Container.Bind<Test4>().AsSingle().NonLazy(); Assert.Throws( delegate { Container.Resolve<Test4>(); }); } [Test] public void TestParameterOptional() { Container.Bind<Test5>().AsSingle().NonLazy(); var test = Container.Resolve<Test5>(); Assert.That(test.Val1 == null); } class Test6 { public Test6(Test2 test2) { } } [Test] public void TestChildDependencyOptional() { Container.Bind<Test6>().AsSingle().NonLazy(); Container.Bind<Test2>().AsSingle().NonLazy(); Assert.Throws( delegate { Container.Resolve<Test6>(); }); } class Test7 { public int Val1; public Test7( [InjectOptional] int val1) { Val1 = val1; } } [Test] public void TestPrimitiveParamOptionalUsesDefault() { Container.Bind<Test7>().AsSingle().NonLazy(); Assert.IsEqual(Container.Resolve<Test7>().Val1, 0); } class Test8 { public int Val1; public Test8( [InjectOptional] int val1 = 5) { Val1 = val1; } } [Test] public void TestPrimitiveParamOptionalUsesExplicitDefault() { Container.Bind<Test8>().AsSingle().NonLazy(); Assert.IsEqual(Container.Resolve<Test8>().Val1, 5); } class Test8_2 { public int Val1; public Test8_2(int val1 = 5) { Val1 = val1; } } [Test] public void TestPrimitiveParamOptionalUsesExplicitDefault2() { Container.Bind<Test8_2>().AsSingle().NonLazy(); Assert.IsEqual(Container.Resolve<Test8_2>().Val1, 5); } [Test] public void TestPrimitiveParamOptionalUsesExplicitDefault3() { Container.Bind<Test8_2>().AsSingle().NonLazy(); Container.BindInstance(2); Assert.IsEqual(Container.Resolve<Test8_2>().Val1, 2); } class Test9 { public int? Val1; public Test9( [InjectOptional] int? val1) { Val1 = val1; } } [Test] public void TestPrimitiveParamOptionalNullable() { Container.Bind<Test9>().AsSingle().NonLazy(); Assert.That(!Container.Resolve<Test9>().Val1.HasValue); } } }
namespace EIDSS.Reports.Document.Veterinary.Aggregate { partial class VetAggregateActionsReport { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VetAggregateActionsReport)); this.tableInterval = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow(); this.cellInputStartDate = new DevExpress.XtraReports.UI.XRTableCell(); this.cellDefis = new DevExpress.XtraReports.UI.XRTableCell(); this.cellInputEndDate = new DevExpress.XtraReports.UI.XRTableCell(); this.lblUnit = new DevExpress.XtraReports.UI.XRLabel(); this.Detail2 = new DevExpress.XtraReports.UI.DetailBand(); this.FlexSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.FlexSubreportSan = new DevExpress.XtraReports.UI.XRSubreport(); this.FlexSubreportPro = new DevExpress.XtraReports.UI.XRSubreport(); this.xrPageBreak1 = new DevExpress.XtraReports.UI.XRPageBreak(); this.xrPageBreak2 = new DevExpress.XtraReports.UI.XRPageBreak(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.CaseIdBarcodeCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.PlaceCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.CaseIdCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // this.PageHeader.StylePriority.UseBorders = false; this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; this.PageHeader.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.PageHeader, "PageHeader"); // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1, this.xrPageBreak2, this.xrPageBreak1, this.FlexSubreportPro, this.FlexSubreportSan, this.FlexSubreport}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.StylePriority.UseFont = false; this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0); this.ReportHeader.Controls.SetChildIndex(this.FlexSubreport, 0); this.ReportHeader.Controls.SetChildIndex(this.FlexSubreportSan, 0); this.ReportHeader.Controls.SetChildIndex(this.FlexSubreportPro, 0); this.ReportHeader.Controls.SetChildIndex(this.xrPageBreak1, 0); this.ReportHeader.Controls.SetChildIndex(this.xrPageBreak2, 0); this.ReportHeader.Controls.SetChildIndex(this.xrTable1, 0); // // xrPageInfo1 // this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.lblUnit, this.tableInterval}); this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); this.cellReportHeader.Controls.SetChildIndex(this.lblReportName, 0); this.cellReportHeader.Controls.SetChildIndex(this.tableInterval, 0); this.cellReportHeader.Controls.SetChildIndex(this.lblUnit, 0); // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); // // cellBaseLeftHeader // resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // tableInterval // this.tableInterval.Borders = DevExpress.XtraPrinting.BorderSide.None; resources.ApplyResources(this.tableInterval, "tableInterval"); this.tableInterval.Name = "tableInterval"; this.tableInterval.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.tableInterval.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow10}); this.tableInterval.StylePriority.UseBorders = false; this.tableInterval.StylePriority.UseFont = false; this.tableInterval.StylePriority.UsePadding = false; // // xrTableRow10 // this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.cellInputStartDate, this.cellDefis, this.cellInputEndDate}); this.xrTableRow10.Name = "xrTableRow10"; resources.ApplyResources(this.xrTableRow10, "xrTableRow10"); // // cellInputStartDate // resources.ApplyResources(this.cellInputStartDate, "cellInputStartDate"); this.cellInputStartDate.Name = "cellInputStartDate"; this.cellInputStartDate.StylePriority.UseFont = false; this.cellInputStartDate.StylePriority.UseTextAlignment = false; // // cellDefis // resources.ApplyResources(this.cellDefis, "cellDefis"); this.cellDefis.Name = "cellDefis"; this.cellDefis.StylePriority.UseFont = false; this.cellDefis.StylePriority.UseTextAlignment = false; // // cellInputEndDate // resources.ApplyResources(this.cellInputEndDate, "cellInputEndDate"); this.cellInputEndDate.Name = "cellInputEndDate"; this.cellInputEndDate.StylePriority.UseFont = false; this.cellInputEndDate.StylePriority.UseTextAlignment = false; // // lblUnit // this.lblUnit.Borders = DevExpress.XtraPrinting.BorderSide.None; resources.ApplyResources(this.lblUnit, "lblUnit"); this.lblUnit.Name = "lblUnit"; this.lblUnit.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.lblUnit.StylePriority.UseBorders = false; this.lblUnit.StylePriority.UseFont = false; this.lblUnit.StylePriority.UseTextAlignment = false; // // Detail2 // resources.ApplyResources(this.Detail2, "Detail2"); this.Detail2.Name = "Detail2"; this.Detail2.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // FlexSubreport // resources.ApplyResources(this.FlexSubreport, "FlexSubreport"); this.FlexSubreport.Name = "FlexSubreport"; // // FlexSubreportSan // resources.ApplyResources(this.FlexSubreportSan, "FlexSubreportSan"); this.FlexSubreportSan.Name = "FlexSubreportSan"; // // FlexSubreportPro // resources.ApplyResources(this.FlexSubreportPro, "FlexSubreportPro"); this.FlexSubreportPro.Name = "FlexSubreportPro"; // // xrPageBreak1 // resources.ApplyResources(this.xrPageBreak1, "xrPageBreak1"); this.xrPageBreak1.Name = "xrPageBreak1"; // // xrPageBreak2 // resources.ApplyResources(this.xrPageBreak2, "xrPageBreak2"); this.xrPageBreak2.Name = "xrPageBreak2"; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2}); this.xrTable1.StylePriority.UsePadding = false; this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1, this.CaseIdBarcodeCell, this.xrTableCell2, this.xrTableCell4, this.PlaceCell}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F); this.xrTableCell1.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); // // CaseIdBarcodeCell // resources.ApplyResources(this.CaseIdBarcodeCell, "CaseIdBarcodeCell"); this.CaseIdBarcodeCell.Name = "CaseIdBarcodeCell"; this.CaseIdBarcodeCell.StylePriority.UseFont = false; this.CaseIdBarcodeCell.StylePriority.UseTextAlignment = false; // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); // // xrTableCell4 // this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); // // PlaceCell // this.PlaceCell.Name = "PlaceCell"; resources.ApplyResources(this.PlaceCell, "PlaceCell"); // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.CaseIdCell, this.xrTableCell7}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell5 // this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // CaseIdCell // this.CaseIdCell.Name = "CaseIdCell"; this.CaseIdCell.StylePriority.UseFont = false; this.CaseIdCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.CaseIdCell, "CaseIdCell"); // // xrTableCell7 // this.xrTableCell7.Name = "xrTableCell7"; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); // // VetAggregateActionsReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader}); this.ExportOptions.Xls.SheetName = resources.GetString("VetAggregateActionsReport.ExportOptions.Xls.SheetName"); this.ExportOptions.Xlsx.SheetName = resources.GetString("VetAggregateActionsReport.ExportOptions.Xlsx.SheetName"); resources.ApplyResources(this, "$this"); this.Version = "14.1"; ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.XRTableRow xrTableRow10; private DevExpress.XtraReports.UI.XRTableCell cellInputStartDate; private DevExpress.XtraReports.UI.XRTableCell cellDefis; private DevExpress.XtraReports.UI.XRTableCell cellInputEndDate; private DevExpress.XtraReports.UI.XRTable tableInterval; private DevExpress.XtraReports.UI.XRLabel lblUnit; private DevExpress.XtraReports.UI.DetailBand Detail2; private DevExpress.XtraReports.UI.XRSubreport FlexSubreport; private DevExpress.XtraReports.UI.XRSubreport FlexSubreportPro; private DevExpress.XtraReports.UI.XRSubreport FlexSubreportSan; private DevExpress.XtraReports.UI.XRPageBreak xrPageBreak2; private DevExpress.XtraReports.UI.XRPageBreak xrPageBreak1; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell CaseIdBarcodeCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell PlaceCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell CaseIdCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace Hydra.Framework.Geometric { public delegate void GraphicEvents(IMapviewObject g); #region Interfaces /// <summary> /// Mapview item base class specifies map item common behavior /// </summary> public interface IMapviewObject { event GraphicEvents GraphicSelected; /// <summary> /// calculate shape bounding box. /// </summary> /// <returns> bounding box rectangle </returns> //RectangleF BoundingBox(); Rectangle BoundingBox(); /// <summary> /// get start point X /// </summary> /// <returns> X </returns> float X(); /// <summary> /// get start point Y /// </summary> /// <returns> Y </returns> float Y(); /// <summary> /// Move shape to the point p. /// </summary> /// <param name="p"> destination point </param> void Move(PointF p); void Scale(int scale); void Rotate(float radians); void RotateAt(PointF pt); void RoateAt(Point pt); /// <summary> /// Move shape by delta X,Y /// </summary> /// <param name="x"> X shift </param> /// <param name="y"> Y shift </param> void MoveBy(float x,float y); /// <summary> /// Draw shape on graphic device. /// Shape stored in "real world" coordinates, converted /// to client (graphic window) coordinate system and drawn /// on graphic device /// </summary> /// <param name="graph"> graphic device </param> /// <param name="trans"> real to client transformation </param> void Draw(Graphics graph,System.Drawing.Drawing2D.Matrix trans); /// <summary> /// Returns true if point close to the shape by specified distance /// </summary> /// <param name="pnt"> source point </param> /// <param name="dist"> distance between shape and point </param> /// <returns></returns> bool IsObjectAt(PointF pnt,float dist); /// <summary> /// Returns true if the shape is selected /// </summary> /// <returns> true or false </returns> bool IsSelected(); /// <summary> /// Returns true if the shape is in edit mode /// </summary> /// <returns></returns> bool IsEdit{get;set;} /// <summary> /// Select the shape if parameter is true. Deselect otherwice. /// </summary> /// <param name="m"> selection flag </param> void Select(bool m); /// <summary> /// Determines whether the object is visible or not /// </summary> bool Visible{get; set;} /// <summary> /// Determines whether the tool tip to be shown or not /// </summary> bool ShowToopTip{get; set;} /// <summary> /// Determines whether the object is in the current layer or not /// </summary> bool IsCurrent{get; set;} /// <summary> /// Determins whether the object is locked or not /// </summary> bool IsLocked{get; set;} bool IsDisabled{get; set;} bool IsFilled{get; set;} Color SelectColor{get;set;} Color DisabledColor{get;set;} Color NormalColor{get;set;} int LineWidth{get; set;} PointF[] Vertices{get; set;} } public interface IPersist { string ToXML{get;set;} string ToVML{get;set;} string ToGML{get;set;} string ToSVG{get;set;} } #endregion #region ENums public enum GraphicType { None, Point, Line, Rectangle, Polygon, Polyline, Elipse, Circle, Arc, Text, Freeform, Complex, Curve, Boundary, Spline, UserDefined }; public enum SubGraphicMode { None, Center_Radius, Center_Diameter, _3Point }; public enum ArcType { _3Point, Center_Radius, }; public enum GraphicTools { Mid, End, Perpendicular, Near, Center, Tangent }; public enum SVGZoomType { In, Out, Center, Extents, Window, Fit, Pan } public enum SubOperationMode { In, Intersection, Except, Union, All } public enum OperationMode { None, Selection, Delete, Move, Copy, Scale, Rotate, Mirror, Arrange, Zoom, Pan, Edit, InsertPoint, DeletePoint, Merge, Measure, UserDefined }; public enum ProjectionMode { Mercator_1SP, Mercator_2SP, Cassini_Soldner, Transverse_Mercator, Hotine_Oblique_Mercator, Oblique_Mercator, Lambert_Conical_1SP, Lambert_Conical_2SP, Oblique_Stereo, New_Zealand_Map, Airy, Cylindrical_Equidistant , Miller_Cylindrical , Albers_Conic , Cylindrical , Miller_Equidistant , Albers_Equal_Area_Conic , Eckert_IV , Mollweide , Aphylactic , Eckert_VI, North_Pole, Authalic_Latitude, Equal_Area, Orthogonal, Authalic, Equidistant, Orthographic, Axonometry_Equirectangular, Perspective, Azimuthal_Equidistant, Gall_Orthographic, Peters, Azimuthal, Gnomonic, Polyconic, Balthasart, Hammer_Aitoff_Equal_Area, Pseudoconic, Behrmann_Cylindrical_Equal_Area, Hammer, Pseudocylindrical, Bonne, Lambert_Azimuthal_Equal_Area, Robinson, Sinusoidal, Cassini, Lambert_Conformal_Conic, Lambert_Cylindrical_Equal_Area, South_Pole_Equal_Area, Colatitude_Latitude, Stereographic, Conformal_Latitude_Longitude_Tristan_Edwards, Conformal_Loxodrome_van_der_Grinten, Conic_Equidistant, Vertical_Perspective, Conic, Mercator, Werner, Cylindrical_Equal_Area, Meridian } #endregion #region Event Arguments public class ItemEventArgs : EventArgs { public long indx; public ItemEventArgs(long i) { indx = i; } } public class MapObjectArgs : EventArgs { public IMapviewObject MapviewObject; public MapObjectArgs(IMapviewObject o) { MapviewObject=o; } } public class CoordEventArgs : EventArgs { public float X; public float Y; public int R; public int G; public int B; public CoordEventArgs(float x,float y,int r,int g,int b) { X=x; Y=y; R=r; G=g; B=b; } } public class GraphicArgs : EventArgs { public GraphicType graphictype; public GraphicArgs(GraphicType g) { graphictype=g; } } public class OperationArgs : EventArgs { public OperationMode omode; public OperationArgs(OperationMode o) { omode=o; } } #endregion }
using System; using Worklight; using System.Json; using System.Threading.Tasks; using System.Collections.Generic; using System.Text; namespace WorklightSample { /// <summary> /// Sample Worklight client /// </summary> public class SampleClient { #region Fields private string pushAlias = "myAlias2"; private string appRealm = "SampleAppRealm"; private JsonObject metadata = (JsonObject)JsonObject.Parse(" {\"platform\" : \"Xamarin\" } "); #endregion #region Properties public IWorklightClient client { get; private set; } /// <summary> /// Gets a value indicating whether this instance is push supported. /// </summary> /// <value><c>true</c> if this instance is push supported; otherwise, <c>false</c>.</value> public bool IsPushSupported { get { try { return client.PushService.IsPushSupported; } catch { return false; } } } /// <summary> /// Gets a value indicating whether this instance is subscribed. /// </summary> /// <value><c>true</c> if this instance is subscribed; otherwise, <c>false</c>.</value> public bool IsSubscribed { get { try { return client.PushService.IsAliasSubscribed(pushAlias); } catch { return false; } } } #endregion #region Constuctors public SampleClient(IWorklightClient wlc) { this.client = wlc; } #endregion #region Async functions public async Task<WorklightResult> ConnectAsync() { var result = new WorklightResult(); try { var resp = await Connect(); result.Success = resp.Success; result.Message = (resp.Success) ? "Connected" : resp.Message; result.Response = resp.ResponseText; } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; } public async Task<WorklightResult> RestInvokeAsync() { var result = new WorklightResult(); try { StringBuilder uriBuilder = new StringBuilder() .Append(client.ServerUrl.AbsoluteUri) // Get the server URL .Append("/adapters") .Append("/SampleHTTPAdapter") //Name of the adapter .Append("/getStories"); // Name of the adapter procedure WorklightResourceRequest rr = client.ResourceRequest(new Uri(uriBuilder.ToString()), "GET" ); WorklightResponse resp = await rr.Send(); result.Success = resp.Success; result.Message = (resp.Success) ? "Connected" : resp.Message; result.Response = resp.ResponseText; } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; } public async Task<WorklightResult> InvokeAsync() { var result = new WorklightResult(); try { var conResp = await ConnectAsync(); if (!conResp.Success) return conResp; result = await InvokeProc(); } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; } public async Task<WorklightResult> SendActivityAsync() { var result = new WorklightResult(); try { var resp = await Task.Run<string>(()=> { client.Analytics.Send(); client.LogActivity("sample data from Xamarin app"); return "Activity Logged"; }); result.Success = true; result.Message = resp; } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; } public async Task<WorklightResult> SubscribeAsync() { var result = new WorklightResult(); try { var resp = await SubscribePush(); result.Success = resp.Success; result.Message = "Subscribed"; result.Response = resp.ResponseText; } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; } public async Task<WorklightResult> UnSubscribeAsync() { var result = new WorklightResult(); try { var resp = await UnsubscribePush(); result.Success = resp.Success; result.Message = "Unsubscribed"; result.Response = resp.ResponseText; } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; } #endregion #region Worklight Methods /// <summary> /// Connect to the server instance /// </summary> private async Task<WorklightResponse> Connect() { //lets send a message to the server client.Analytics.Log("Trying to connect to server", metadata); ChallengeHandler customCH = new CustomChallengeHandler(appRealm); client.RegisterChallengeHandler(customCH); WorklightResponse task = await client.Connect(); //lets log to the local client (not server) client.Logger("Xamarin").Trace("connection"); //write to the server the connection status client.Analytics.Log("Connect response : " + task.Success); return task; } /// <summary> /// Unsubscribes from push notifications /// </summary> /// <returns>The push.</returns> private async Task<WorklightResponse> UnsubscribePush() { try { client.Analytics.Log("Unsubscribing Push", metadata); WorklightResponse task = await client.PushService.UnsubscribeFromEventSource(pushAlias); return task; } catch (Exception ex) { return null; } } /// <summary> /// Subscribes to push notifications /// </summary> /// <param name="callBack">Call back.</param> private async Task<WorklightResponse> SubscribePush() { Console.WriteLine("Subscribing to push"); client.PushService.ReadyToSubscribe += HandleReadyToSubscribe; client.PushService.InitRegistration(); return await client.Connect (); } void HandleReadyToSubscribe(object sender, EventArgs a) { Console.WriteLine ("We are ready to subscribe to the notification service!!"); client.PushService.RegisterEventSourceNotificationCallback(pushAlias,"PushAdapter","PushEventSource",new NotificationListener ()); client.PushService.SubscribeToEventSource(pushAlias,new Dictionary<string,string>()); } /// <summary> /// Invokes the procedured /// </summary> /// <returns>The proc.</returns> private async Task<WorklightResult> InvokeProc() { var result = new WorklightResult(); try { client.Analytics.Log("trying to invoking procedure"); System.Diagnostics.Debug.WriteLine("Trying to invoke proc"); WorklightProcedureInvocationData invocationData = new WorklightProcedureInvocationData("SampleHTTPAdapter", "getStories", new object[] { "technology" }); WorklightResponse task = await client.InvokeProcedure(invocationData); client.Analytics.Log("invoke response : " + task.Success); StringBuilder retval = new StringBuilder(); result.Success = task.Success; if (task.Success) { JsonArray jsonArray = (JsonArray)task.ResponseJSON["rss"]["channel"]["item"]; foreach (JsonObject title in jsonArray) { System.Json.JsonValue titleString; title.TryGetValue("title", out titleString); retval.Append(titleString.ToString()); retval.AppendLine(); } } else { retval.Append("Failure: " + task.Message); } result.Message = retval.ToString(); } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using log4net; using NetGore; using NetGore.World; namespace DemoGame { /// <summary> /// Base class for an Inventory that contains ItemEntities. /// </summary> /// <typeparam name="T">The type of game item contained in the inventory.</typeparam> public abstract class InventoryBase<T> : IInventory<T>, IDisposable where T : ItemEntityBase { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); readonly T[] _buffer; bool _disposed = false; /// <summary> /// Initializes a new instance of the <see cref="InventoryBase{T}"/> class. /// </summary> /// <param name="slots">The number of slots in the inventory.</param> protected InventoryBase(int slots) { _buffer = new T[slots]; } /// <summary> /// Gets or sets (protected) the item in the Inventory at the given <paramref name="slot"/>. /// </summary> /// <param name="slot">Index of the slot to get the Item from.</param> /// <returns>Item in the specified Inventory slot, or null if the slot is empty or invalid.</returns> protected T this[int slot] { get { return this[new InventorySlot(slot)]; } set { this[new InventorySlot(slot)] = value; } } /// <summary> /// Gets if this object has been disposed. /// </summary> public bool IsDisposed { get { return _disposed; } } /// <summary> /// Completely removes the item in a given slot, including optionally disposing it. /// </summary> /// <param name="slot">Slot of the item to remove.</param> /// <param name="destroy">If true, the item in the slot will also be destroyed. If false, the item /// will be removed from the Inventory, but not disposed.</param> protected void ClearSlot(InventorySlot slot, bool destroy) { // Get the item at the slot T item = this[slot]; // Check for a valid item if (item == null) { const string errmsg = "Slot `{0}` already contains no item."; Debug.Fail(string.Format("Slot `{0}` already contains no item.", slot)); if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this); return; } // Remove the item reference this[slot] = null; // Destroy the item if (destroy) item.Destroy(); } /// <summary> /// When overridden in the derived class, handles when this object is disposed. /// </summary> /// <param name="disposeManaged">True if dispose was called directly; false if this object was garbage collected.</param> protected virtual void Dispose(bool disposeManaged) { } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="InventoryBase{T}"/> is reclaimed by garbage collection. /// </summary> ~InventoryBase() { if (IsDisposed) return; _disposed = true; InternalDispose(false); } /// <summary> /// When overridden in the derived class, performs additional processing to handle an Inventory slot /// changing. This is only called when the object references changes, not when any part of the object /// (such as the Item's amount) changes. It is guarenteed that if <paramref name="newItem"/> is null, /// <paramref name="oldItem"/> will not be, and vise versa. Both will never be null or non-null. /// </summary> /// <param name="slot">Slot that the change took place in.</param> /// <param name="newItem">The item that was added to the <paramref name="slot"/>, or null if the slot changed to empty.</param> /// <param name="oldItem">The item that used to be in the <paramref name="slot"/>, /// or null if the slot used to be empty.</param> protected virtual void HandleSlotChanged(InventorySlot slot, T newItem, T oldItem) { } void InternalDispose(bool disposeManaged) { foreach (var item in _buffer.Where(x => x != null)) { item.Disposed -= InventoryItemDisposedHandler; } Dispose(disposeManaged); } /// <summary> /// Tries to add an item to the inventory, returning the remainder of the item that was not added. /// </summary> /// <param name="item">Item that will be added to the Inventory.</param> /// <param name="changedSlots">Contains the <see cref="InventorySlot"/>s that the <paramref name="item"/> was added to.</param> /// <returns>The remainder of the item that was not added to the inventory. If this returns null, all of the item /// was added to the inventory. If this returns the same object as <paramref name="item"/>, then none of the /// item could be added to the inventory. Otherwise, this will return a new object instance with the amount /// equal to the portion that failed to be added.</returns> T InternalTryAdd(T item, ICollection<InventorySlot> changedSlots) { Debug.Assert(changedSlots == null || changedSlots.IsEmpty()); int newItemAmount = item.Amount; // Try to stack the item in as many slots as possible until it runs out or we run out of slots InventorySlot slot; while (TryFindStackableSlot(item, out slot)) { T invItem = this[slot]; if (invItem == null) { const string errmsg = "This should never be a null item. If it is, TryFindStackableSlot() may be broken."; Debug.Fail(errmsg); if (log.IsErrorEnabled) log.Error(errmsg); } else { // Stack as much of the item into the existing inventory item var stackAmount = (byte)Math.Min(ItemEntityBase.MaxStackSize - invItem.Amount, newItemAmount); Debug.Assert(stackAmount > 0); if (stackAmount > 0) { invItem.Amount += stackAmount; newItemAmount -= stackAmount; if (changedSlots != null && !changedSlots.Contains(slot)) changedSlots.Add(slot); // If we stacked all of the item, we're done if (newItemAmount <= 0) { Debug.Assert(newItemAmount == 0); item.Destroy(); return null; } } } } // Could not stack, or only some of the item was stacked, so add item to empty slots while (TryFindEmptySlot(out slot)) { if (newItemAmount <= ItemEntityBase.MaxStackSize) { // Place the whole item into the slot and we're done Debug.Assert(newItemAmount > 0 && newItemAmount <= byte.MaxValue); item.Amount = (byte)newItemAmount; // As there is nothing to stack the new item onto create a deep copy in a new slot. var copy = (T)item.DeepCopy(); this[slot] = copy; if (changedSlots != null) changedSlots.Add(slot); return null; } else { // There is too much of the item to fit into a single slot, so place a copy of the item into the slot // with the amount equal to the max stack size and repeat this until we run out of slots or all of the // item is added T copy = (T)item.DeepCopy(); copy.Amount = ItemEntityBase.MaxStackSize; this[slot] = copy; newItemAmount -= copy.Amount; Debug.Assert(newItemAmount > 0); } } // Failed to add all of the item, so update the amount property and return the remainder Debug.Assert(newItemAmount > 0 && newItemAmount <= byte.MaxValue); item.Amount = (byte)newItemAmount; return item; } /// <summary> /// Handles when an item is disposed while still in this <see cref="InventoryBase{T}"/>. /// </summary> /// <param name="sender">The <see cref="Entity"/> that was disposed.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void InventoryItemDisposedHandler(Entity sender, EventArgs e) { T item = (T)sender; // Try to get the slot InventorySlot slot; try { slot = GetSlot(item); } catch (ArgumentException) { const string errmsg = "Inventory item `{0}` was disposed, but was not be found in the Inventory."; Debug.Fail(string.Format(errmsg, item)); if (log.IsWarnEnabled) log.WarnFormat(errmsg, item); return; } // Remove the item from the Inventory (don't dispose since it was already disposed) RemoveAt(slot, false); } /// <summary> /// Gets the index of the first unused Inventory slot. /// </summary> /// <param name="emptySlot">If function returns true, contains the index of the first unused Inventory slot.</param> /// <returns>True if an empty slot was found, otherwise false.</returns> protected bool TryFindEmptySlot(out InventorySlot emptySlot) { // Iterate through each slot for (int i = 0; i < _buffer.Length; i++) { // Return on the first null item if (this[i] == null) { emptySlot = new InventorySlot(i); return true; } } // All slots are in use emptySlot = new InventorySlot(0); return false; } /// <summary> /// Gets the first slot that the given <paramref name="item"/> can be stacked on. /// </summary> /// <param name="item">Item that will try to stack on existing items.</param> /// <param name="stackableSlot">If function returns true, contains the index of the first slot that /// the <paramref name="item"/> can be stacked on. This slot is not guaranteed to be able to hold /// all of the item, but it does guarantee to be able to hold at least one unit of the item.</param> /// <returns>True if a stackable slot was found, otherwise false.</returns> protected bool TryFindStackableSlot(T item, out InventorySlot stackableSlot) { // Iterate through each slot for (var i = 0; i < _buffer.Length; i++) { T invItem = this[i]; // Skip empty slots if (invItem == null) continue; // Make sure the item isn't already at the stacking limit if (invItem.Amount >= ItemEntityBase.MaxStackSize) continue; // Check if the item can stack with our item if (!invItem.CanStack(item)) continue; // Stackable slot found stackableSlot = new InventorySlot(i); return true; } // No stackable slot found stackableSlot = new InventorySlot(0); return false; } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (IsDisposed) return; _disposed = true; GC.SuppressFinalize(this); InternalDispose(true); } #endregion #region IInventory<T> Members /// <summary> /// Gets or sets (protected) the item in the Inventory at the given <paramref name="slot"/>. /// </summary> /// <param name="slot">Index of the slot to get the Item from.</param> /// <returns>Item in the specified Inventory slot, or null if the slot is empty or invalid.</returns> public T this[InventorySlot slot] { get { // Check for a valid index if (!slot.IsLegalValue()) { const string errmsg = "Tried to get invalid inventory slot `{0}`"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, slot); Debug.Fail(string.Format(errmsg, slot)); return null; } return _buffer[(int)slot]; } protected set { // Check for a valid index if (!slot.IsLegalValue()) { const string errmsg = "Tried to set invalid inventory slot `{0}`"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, slot); Debug.Fail(string.Format(errmsg, slot)); return; } // Check for a change T oldItem = this[slot]; if (oldItem == value) return; // Ensure that, when setting an item into a slot, that no item is already there if (oldItem != null && value != null) { const string errmsg = "Set an item ({0}) on a slot ({1}) that already contained an item ({2})."; Debug.Fail(string.Format(errmsg, value, slot, oldItem)); if (log.IsErrorEnabled) log.ErrorFormat(errmsg, value, slot, oldItem); // Try to resolve the problem by removing the old item ClearSlot(slot, false); } // Attach (if item added) or remove (if item removed) hook to the Dispose event if (oldItem != null) { oldItem.Disposed -= InventoryItemDisposedHandler; } else { value.Disposed -= InventoryItemDisposedHandler; value.Disposed += InventoryItemDisposedHandler; } // Change the ItemEntity reference _buffer[(int)slot] = value; // Allow for additional processing HandleSlotChanged(slot, value, oldItem); } } /// <summary> /// Gets the number of inventory slots that are currently unoccupied (contains no item). /// </summary> public int FreeSlots { get { var count = 0; for (int i = 0; i < _buffer.Length; i++) { if (this[i] == null) ++count; } return count; } } /// <summary> /// Gets the items in this collection. /// </summary> public IEnumerable<T> Items { get { for (InventorySlot i = new InventorySlot(0); i < _buffer.Length; i++) { var item = this[i]; if (item != null) yield return item; } } } /// <summary> /// Gets the number of inventory slots that are currently occupied (contains an item). /// </summary> public int OccupiedSlots { get { int count = 0; for (int i = 0; i < _buffer.Length; i++) { if (this[i] != null) ++count; } return count; } } /// <summary> /// Gets the total number of slots in this inventory (both free and occupied slots). /// </summary> public int TotalSlots { get { return _buffer.Length; } } /// <summary> /// Tries to add an item to the inventory, returning the amount of the item that was successfully added. Any remainder /// of the <paramref name="item"/> that fails to be added will be destroyed instead of being returned like with /// TryAdd. /// </summary> /// <param name="item">Item that will be added to the Inventory.</param> /// <returns>The amount of the <paramref name="item"/> that was successfully added to the inventory. If this value is /// 0, none of the <paramref name="item"/> was added. If it is equal to the <paramref name="item"/>'s amount, then /// all of the item was successfully added.</returns> public int Add(T item) { // Store what the original amount of the item was int originalAmount = item.Amount; // Add the item T remainder = TryAdd(item); // Find how much of the item was added int ret = originalAmount - (remainder != null ? (int)remainder.Amount : 0); // If we had a remainder, destroy it if (remainder != null) remainder.Destroy(); Debug.Assert(ret >= 0 && ret <= originalAmount); return ret; } /// <summary> /// Tries to add an item to the inventory, returning the amount of the item that was successfully added. Any remainder /// of the <paramref name="item"/> that fails to be added will be destroyed instead of being returned like with /// TryAdd. /// </summary> /// <param name="item">Item that will be added to the Inventory.</param> /// <param name="changedSlots">Contains the <see cref="InventorySlot"/>s that the <paramref name="item"/> was added to.</param> /// <returns>The amount of the <paramref name="item"/> that was successfully added to the inventory. If this value is /// 0, none of the <paramref name="item"/> was added. If it is equal to the <paramref name="item"/>'s amount, then /// all of the item was successfully added.</returns> public int Add(T item, out IEnumerable<InventorySlot> changedSlots) { // Store what the original amount of the item was int originalAmount = item.Amount; // Add the item T remainder = TryAdd(item, out changedSlots); // Find how much of the item was added int ret = originalAmount - (remainder != null ? (int)remainder.Amount : 0); // If we had a remainder, destroy it if (remainder != null) remainder.Destroy(); Debug.Assert(ret >= 0 && ret <= originalAmount); return ret; } /// <summary> /// Checks if the specified <paramref name="item"/> can be added to the inventory completely /// and successfully, but does not actually add the item. /// </summary> /// <param name="item">Item to try to fit into the inventory.</param> /// <returns>True if the <paramref name="item"/> can be added to the inventory properly; false if the <paramref name="item"/> /// is invalid or cannot fully fit into the inventory.</returns> public bool CanAdd(T item) { // NOTE: All CanAdd() implementations use a hack to check if the items can fit // FUTURE: Can prevent creating an ItemEntity just to figure out it won't fit by passing the item template and amount // and using that to check if there is a free slot. Then, when stacking is supported, the method can create the // ItemEntity to test if it will stack. Will want to also have an out parameter to be able to reuse/dispose of the // created temporary ItemEntity. if (item == null) return false; return FreeSlots >= 1; } /// <summary> /// Checks if the specified <paramref name="items"/> can be added to the inventory completely /// and successfully, but does not actually add the items. /// </summary> /// <param name="items">Items to try to fit into the inventory.</param> /// <returns>True if the <paramref name="items"/> can be added to the inventory properly; false if the <paramref name="items"/> /// is invalid or cannot fully fit into the inventory.</returns> public bool CanAdd(IEnumerable<T> items) { // NOTE: All CanAdd() implementations use a hack to check if the items can fit if (items == null) return false; return FreeSlots >= items.Count(); } /// <summary> /// Checks if the specified <paramref name="items"/> can be added to the inventory completely /// and successfully, but does not actually add the items. /// </summary> /// <param name="items">Items to try to fit into the inventory.</param> /// <returns>True if the <paramref name="items"/> can be added to the inventory properly; false if the <paramref name="items"/> /// is invalid or cannot fully fit into the inventory.</returns> public bool CanAdd(IInventory<T> items) { // NOTE: All CanAdd() implementations use a hack to check if the items can fit if (items == null) return false; return FreeSlots >= items.OccupiedSlots; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<InventorySlot, T>> GetEnumerator() { for (var i = new InventorySlot(0); i < _buffer.Length; i++) { var item = this[i]; if (item != null) yield return new KeyValuePair<InventorySlot, T>(i, item); } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets the slot for the specified <paramref name="item"/>. /// </summary> /// <param name="item">Item to find the slot for.</param> /// <returns>Slot for the specified <paramref name="item"/>.</returns> /// <exception cref="ArgumentException">The specified item is not in the Inventory.</exception> /// <exception cref="ArgumentNullException"><paramref name="item"/> was null.</exception> public InventorySlot GetSlot(T item) { if (item == null) throw new ArgumentNullException("item"); for (var i = 0; i < _buffer.Length; i++) { if (this[i] == item) return new InventorySlot(i); } throw new ArgumentException("The specified item is not in the Inventory.", "item"); } /// <summary> /// Removes all items from the inventory. /// </summary> /// <param name="destroy">If true, then all of the items in the inventory will be destroyed. If false, /// they will only be removed from the inventory, but could still referenced by other objects.</param> public void RemoveAll(bool destroy) { for (var i = 0; i < _buffer.Length; i++) { if (this[i] != null) ClearSlot(new InventorySlot(i), destroy); } } /// <summary> /// Removes the item in the given <paramref name="slot"/> from the inventory. The removed item is /// not disposed, so if the item must be disposed (that is, it won't be used anywhere else), be /// sure to dispose of it! /// </summary> /// <param name="slot">Slot of the item to remove.</param> /// <param name="destroy">If true, the item at the given <paramref name="slot"/> will be destroyed. If false, /// the item will not be disposed and will still be referenceable.</param> public void RemoveAt(InventorySlot slot, bool destroy) { ClearSlot(slot, destroy); } /// <summary> /// Swaps the items in two inventory slots. /// </summary> /// <param name="a">The first <see cref="InventorySlot"/> to swap.</param> /// <param name="b">The second <see cref="InventorySlot"/> to swap.</param> /// <returns>True if the swapping was successful; false if either of the <see cref="InventorySlot"/>s contained /// an invalid value or if the slots were the same slot.</returns> public bool SwapSlots(InventorySlot a, InventorySlot b) { // Check for valid slots if (!a.IsLegalValue() || !b.IsLegalValue()) return false; // Don't swap to the same slot if (a == b) return false; // We do a little hack here to swap much quicker than using the indexer // Store the items in the slots var tmpA = this[a]; var tmpB = this[b]; // Only swap if there is an item in either of or both of the slots if (tmpA != null || tmpB != null) { // Swap the items in the slots in the buffer directly _buffer[(int)a] = tmpB; _buffer[(int)b] = tmpA; // Raise the slot change notification for both the swaps HandleSlotChanged(a, tmpB, tmpA); HandleSlotChanged(b, tmpA, tmpB); } return true; } /// <summary> /// Tries to add an item to the inventory, returning the remainder of the item that was not added. /// </summary> /// <param name="item">Item that will be added to the Inventory.</param> /// <returns>The remainder of the item that was not added to the inventory. If this returns null, all of the item /// was added to the inventory. Otherwise, this will return an object instance with the amount /// equal to the portion that failed to be added.</returns> public T TryAdd(T item) { return InternalTryAdd(item, null); } /// <summary> /// Tries to add an item to the inventory, returning the remainder of the item that was not added. /// </summary> /// <param name="item">Item that will be added to the Inventory.</param> /// <param name="changedSlots">Contains the <see cref="InventorySlot"/>s that the <paramref name="item"/> was added to.</param> /// <returns>The remainder of the item that was not added to the inventory. If this returns null, all of the item /// was added to the inventory. Otherwise, this will return an object instance with the amount /// equal to the portion that failed to be added.</returns> public T TryAdd(T item, out IEnumerable<InventorySlot> changedSlots) { var changeList = new List<InventorySlot>(); changedSlots = changeList; return InternalTryAdd(item, changeList); } /// <summary> /// Gets the slot for the specified <paramref name="item"/>. /// </summary> /// <param name="item">Item to find the slot for.</param> /// <returns>Slot for the specified <paramref name="item"/>, or null if the <paramref name="item"/> is invalid or not in /// the inventory.</returns> public InventorySlot? TryGetSlot(T item) { if (item == null) return null; for (var i = 0; i < _buffer.Length; i++) { if (this[i] == item) return new InventorySlot(i); } return null; } #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.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class AcceptAsync { private readonly ITestOutputHelper _log; public AcceptAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } public void OnAcceptCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnAcceptCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } public void OnConnectCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnConnectCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv4", "true")] public void AcceptAsync_IpV4_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv4 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv6", "true")] public void AcceptAsync_IPv6_Success() { Assert.True(Capability.IPv6Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv6 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv6 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithReceiveBuffer_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent accepted = new AutoResetEvent(false); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx const int acceptBufferDataSize = 256; const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize; byte[] sendBuffer = new byte[acceptBufferDataSize]; new Random().NextBytes(sendBuffer); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = accepted; acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize); Assert.True(server.AcceptAsync(acceptArgs)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Connect(IPAddress.Loopback, port); client.Send(sendBuffer); client.Shutdown(SocketShutdown.Both); } Assert.True( accepted.WaitOne(TestSettings.PassingTestTimeout), "Test completed in alotted time"); Assert.Equal( SocketError.Success, acceptArgs.SocketError); Assert.Equal( acceptBufferDataSize, acceptArgs.BytesTransferred); Assert.Equal( new ArraySegment<byte>(sendBuffer), new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred)); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithReceiveBuffer_Failure() { // // Unix platforms don't yet support receiving data with AcceptAsync. // Assert.True(Capability.IPv4Support()); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = new ManualResetEvent(false); byte[] buffer = new byte[1024]; acceptArgs.SetBuffer(buffer, 0, buffer.Length); Assert.Throws<PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs)); } } #region GC Finalizer test // This test assumes sequential execution of tests and that it is going to be executed after other tests // that used Sockets. [OuterLoop] // TODO: Issue #11345 [Fact] public void TestFinalizers() { // Making several passes through the FReachable list. for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } #endregion } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.IO; using ConsoleExamples.Examples; using Encog.Cloud.Indicator; using Encog.Cloud.Indicator.Server; using Encog.Examples.Indicator.ImportData; using Encog.ML; using Encog.ML.Data; using Encog.ML.Factory; using Encog.ML.Train; using Encog.ML.Train.Strategy; using Encog.Neural.Networks.Training.Propagation.Manhattan; using Encog.Persist; using Encog.Util.File; using Encog.Util.Simple; using Directory = System.IO.Directory; namespace Encog.Examples.Indicator.Avg { /// <summary> /// This example shows how to create an indicator based on two existing /// NinjaTrader indicators. For more information on this example, visit /// the following URL. /// /// http://www.heatonresearch.com/wiki/Neural_Network_Indicator_for_NinjaTrader_with_C_Sharp /// </summary> public class IndicatorExample : IExample, IIndicatorConnectionListener { /// <summary> /// The port to use. /// </summary> public const int Port = 5128; private IExampleInterface _app; /// <summary> /// The path to store files at. /// </summary> private string _path; public static ExampleInfo Info { get { var info = new ExampleInfo( typeof (IndicatorExample), @"indicator-sma", @"Provide an example indicator.", @"Provide a NinjaTrader example indicator built on two SMA's."); return info; } } #region IExample Members /// <summary> /// The program entry point. /// </summary> /// <param name="app">The arguments to run the program with.</param> public void Execute(IExampleInterface app) { _app = app; string[] args = app.Args; if (args.Length != 2) { Console.WriteLine(@"Usage: IndicatorExample [clear/collect/generate/train/run] [work path]"); } else { _path = args[1]; if (string.Compare(args[0], "collect", true) == 0) { Run(true); } else if (string.Compare(args[0], "train", true) == 0) { Train(); } else if (string.Compare(args[0], "run", true) == 0) { Run(false); } else if (string.Compare(args[0], "clear", true) == 0) { Clear(); } else if (string.Compare(args[0], "generate", true) == 0) { Generate(); } else if (string.Compare(args[0], "calibrate", true) == 0) { Calibrate(); } } } #endregion #region IIndicatorConnectionListener Members /// <summary> /// Called when a connection is made by a trading platform. /// </summary> /// <param name="link">The link.</param> /// <param name="hasOpened">True, if we are opening.</param> public void NotifyConnections(IndicatorLink link, bool hasOpened) { if (hasOpened) { Console.WriteLine(@"Connection from " + link.ClientSocket.RemoteEndPoint + @" established."); } else { Console.WriteLine(@"Connection from " + link.ClientSocket.RemoteEndPoint + @" terminated."); } } #endregion /// <summary> /// Perform the training option. /// </summary> public void Train() { // first, create the machine learning method var methodFactory = new MLMethodFactory(); IMLMethod method = methodFactory.Create(Config.MethodType, Config.MethodArchitecture, Config.InputWindow, 1); // second, create the data set string filename = FileUtil.CombinePath(new FileInfo(_path), Config.FilenameTrain).ToString(); IMLDataSet dataSet = EncogUtility.LoadEGB2Memory(new FileInfo(filename)); // third, create the trainer var trainFactory = new MLTrainFactory(); IMLTrain train = trainFactory.Create(method, dataSet, Config.TrainType, Config.TrainParams); // reset if improve is less than 1% over 5 cycles if (method is IMLResettable && !(train is ManhattanPropagation)) { train.AddStrategy(new RequiredImprovementStrategy(500)); } // fourth, train and evaluate. EncogUtility.TrainToError(train, Config.TargetError); method = train.Method; EncogDirectoryPersistence.SaveObject(FileUtil.CombinePath(new FileInfo(_path), Config.MethodName), method); // finally, write out what we did Console.WriteLine(@"Machine Learning Type: " + Config.MethodType); Console.WriteLine(@"Machine Learning Architecture: " + Config.MethodArchitecture); Console.WriteLine(@"Training Method: " + Config.TrainType); Console.WriteLine(@"Training Args: " + Config.TrainParams); } /// <summary> /// Perform the calibrate option. /// </summary> private void Calibrate() { var gen = new GenerateTraining(_path); gen.Calibrate(); } /// <summary> /// Perform the generate option. /// </summary> private void Generate() { Console.WriteLine(@"Generating training data... please wait..."); var gen = new GenerateTraining(_path); gen.Generate(); Console.WriteLine(@"Training data has been generated."); } /// <summary> /// Perform the clear option. /// </summary> private void Clear() { string[] list = Directory.GetFiles(_path); foreach (string file in list) { string fn = FileUtil.GetFileName(new FileInfo(file)); if (fn.StartsWith("collected") && fn.EndsWith(".csv")) { new FileInfo(file).Delete(); } } Console.WriteLine(@"Directory cleared of captured financial data."); } /// <summary> /// Run the indicator in either collection or indicator mode. /// </summary> /// <param name="collectMode">True to run the indicator in collection mode, /// false otherwise.</param> public void Run(bool collectMode) { IMLRegression method; if (collectMode) { method = null; Console.WriteLine(@"Ready to collect data from remote indicator."); } else { method = (IMLRegression) EncogDirectoryPersistence.LoadObject(FileUtil.CombinePath(new FileInfo(_path), Config.MethodName)); Console.WriteLine(@"Indicator ready."); } Console.WriteLine(@"Waiting for connections on port " + Port); var server = new IndicatorServer(); server.AddListener(this); server.AddIndicatorFactory(new MyFactory(method, _path)); server.Start(); if (collectMode) { server.WaitForIndicatorCompletion(); } else { server.WaitForShutdown(); } } #region Nested type: MyFactory public class MyFactory : IIndicatorFactory { private readonly IMLRegression _method; private readonly string _path; public MyFactory(IMLRegression theMethod, string thePath) { _method = theMethod; _path = thePath; } #region IIndicatorFactory Members public String Name { get { return "EMA"; } } public IIndicatorListener Create() { return new MyInd(_method, _path); } #endregion } #endregion } }
// Copyright (c) Sven Groot (Ookii.org) 2006 // See license.txt for details using System; using System.Collections.Generic; using System.Text; using Microsoft.Win32; using System.Collections; using System.IO; using System.ComponentModel; using Ookii.Dialogs.Wpf.Interop; using System.Windows; using System.Windows.Interop; namespace Ookii.Dialogs.Wpf { /// <summary> /// Displays a dialog box from which the user can select a file. /// </summary> /// <remarks> /// <para> /// Windows Vista provides a new style of common file dialog, with several new features (both from /// the user's and the programmers perspective). /// </para> /// <para> /// This class and derived classes will use the Vista-style file dialogs if possible, and automatically fall back to the old-style /// dialog on versions of Windows older than Vista. This class is aimed at applications that /// target both Windows Vista and older versions of Windows, and therefore does not provide any /// of the new APIs provided by Vista's file dialogs. /// </para> /// <para> /// This class precisely duplicates the public interface of <see cref="FileDialog"/> so you can just replace /// any instances of <see cref="FileDialog"/> with the <see cref="VistaFileDialog"/> without any further changes /// to your code. /// </para> /// </remarks> /// <threadsafety instance="false" static="true" /> [DefaultEvent("FileOk"), DefaultProperty("FileName")] public abstract class VistaFileDialog { internal const int HelpButtonId = 0x4001; private FileDialog _downlevelDialog; private NativeMethods.FOS _options; private string _filter; private int _filterIndex ; private string[] _fileNames; private string _defaultExt; private bool _addExtension; private string _initialDirectory; private string _title; private Window _owner; /// <summary> /// Event raised when the user clicks on the Open or Save button on a file dialog box. /// </summary> [Description("Event raised when the user clicks on the Open or Save button on a file dialog box."), Category("Action")] public event System.ComponentModel.CancelEventHandler FileOk; /// <summary> /// Creates a new instance of <see cref="VistaFileDialog" /> class. /// </summary> protected VistaFileDialog() { Reset(); } #region Public Properties /// <summary> /// Gets a value that indicates whether the current OS supports Vista-style common file dialogs. /// </summary> /// <value> /// <see langword="true" /> if Vista-style common file dialgs are supported; otherwise, <see langword="false" />. /// </value> /// <remarks> /// <para> /// Returns <see langword="true" /> on Windows Vista or newer operating systems. /// </para> /// <para> /// If this property returns <see langword="false" />, the <see cref="VistaFileDialog"/> class (and /// its derived classes) will fall back to the regular file dialog. /// </para> /// </remarks> [Browsable(false)] public static bool IsVistaFileDialogSupported { get { return NativeMethods.IsWindowsVistaOrLater; } } /// <summary> /// Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name /// if the user omits the extension. /// </summary> /// <value> /// <see langword="true" /> if the dialog box adds an extension to a file name if the user omits the extension; otherwise, <see langword="false" />. /// The default value is <see langword="true" />. /// </value> [Description("A value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension."), Category("Behavior"), DefaultValue(true)] public bool AddExtension { get { if( DownlevelDialog != null ) return DownlevelDialog.AddExtension; return _addExtension; } set { if( DownlevelDialog != null ) DownlevelDialog.AddExtension = value; else _addExtension = value; } } /// <summary> /// Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist. /// </summary> /// <value> /// <see langword="true" /> if the dialog box displays a warning if the user specifies a file name that does not exist; /// otherwise, <see langword="false" />. The default value is <see langword="false" />. /// </value> [Description("A value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist."), Category("Behavior"), DefaultValue(false)] public virtual bool CheckFileExists { get { if( DownlevelDialog != null ) return DownlevelDialog.CheckFileExists; return GetOption(NativeMethods.FOS.FOS_FILEMUSTEXIST); } set { if( DownlevelDialog != null ) DownlevelDialog.CheckFileExists = value; else SetOption(NativeMethods.FOS.FOS_FILEMUSTEXIST, value); } } /// <summary> /// Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist. /// </summary> /// <value> /// <see langword="true" /> if the dialog box displays a warning when the user specifies a path that does not exist; otherwise, <see langword="false" />. /// The default value is <see langword="true" />. /// </value> [Description("A value indicating whether the dialog box displays a warning if the user specifies a path that does not exist."), DefaultValue(true), Category("Behavior")] public bool CheckPathExists { get { if( DownlevelDialog != null ) return DownlevelDialog.CheckPathExists; return GetOption(NativeMethods.FOS.FOS_PATHMUSTEXIST); } set { if( DownlevelDialog != null ) DownlevelDialog.CheckPathExists = value; else SetOption(NativeMethods.FOS.FOS_PATHMUSTEXIST, value); } } /// <summary> /// Gets or sets the default file name extension. /// </summary> /// <value> /// The default file name extension. The returned string does not include the period. The default value is an empty string (""). /// </value> [Category("Behavior"), DefaultValue(""), Description("The default file name extension.")] public string DefaultExt { get { if( DownlevelDialog != null ) return DownlevelDialog.DefaultExt; return _defaultExt ?? string.Empty; } set { if( DownlevelDialog != null ) DownlevelDialog.DefaultExt = value; else { if( value != null ) { if( value.StartsWith(".", StringComparison.CurrentCulture) ) value = value.Substring(1); else if( value.Length == 0 ) value = null; } _defaultExt = value; } } } /// <summary> /// Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut /// or whether it returns the location of the shortcut (.lnk). /// </summary> /// <value> /// <see langword="true" /> if the dialog box returns the location of the file referenced by the shortcut; otherwise, <see langword="false" />. /// The default value is <see langword="true" />. /// </value> [Category("Behavior"), Description("A value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk)."), DefaultValue(true)] public bool DereferenceLinks { get { if( DownlevelDialog != null ) return DownlevelDialog.DereferenceLinks; return !GetOption(NativeMethods.FOS.FOS_NODEREFERENCELINKS); } set { if( DownlevelDialog != null ) DownlevelDialog.DereferenceLinks = value; else SetOption(NativeMethods.FOS.FOS_NODEREFERENCELINKS, !value); } } /// <summary> /// Gets or sets a string containing the file name selected in the file dialog box. /// </summary> /// <value> /// The file name selected in the file dialog box. The default value is an empty string (""). /// </value> [DefaultValue(""), Category("Data"), Description("A string containing the file name selected in the file dialog box.")] public string FileName { get { if( DownlevelDialog != null ) return DownlevelDialog.FileName; if( _fileNames == null || _fileNames.Length == 0 || string.IsNullOrEmpty(_fileNames[0]) ) return string.Empty; else return _fileNames[0]; } set { if( DownlevelDialog != null ) DownlevelDialog.FileName = value; _fileNames = new string[1]; _fileNames[0] = value; } } /// <summary> /// Gets the file names of all selected files in the dialog box. /// </summary> /// <value> /// An array of type <see cref="String"/>, containing the file names of all selected files in the dialog box. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] // suppressed because it matches FileDialog [Description("The file names of all selected files in the dialog box."), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string[] FileNames { get { if( DownlevelDialog != null ) return DownlevelDialog.FileNames; return FileNamesInternal; } } /// <summary> /// Gets or sets the current file name filter string, which determines the choices that appear in the /// "Save as file type" or "Files of type" box in the dialog box. /// </summary> /// <value> /// The file filtering options available in the dialog box. /// </value> /// <exception cref="System.ArgumentException">Filter format is invalid.</exception> [Description("The current file name filter string, which determines the choices that appear in the \"Save as file type\" or \"Files of type\" box in the dialog box."), Category("Behavior"), Localizable(true), DefaultValue("")] public string Filter { get { if( DownlevelDialog != null ) return DownlevelDialog.Filter; return _filter; } set { if( DownlevelDialog != null ) DownlevelDialog.Filter = value; else { if( value != _filter ) { if( !string.IsNullOrEmpty(value) ) { string[] filterElements = value.Split(new char[] { '|' }); if( filterElements == null || filterElements.Length % 2 != 0 ) throw new ArgumentException(Properties.Resources.InvalidFilterString); } else value = null; _filter = value; } } } } /// <summary> /// Gets or sets the index of the filter currently selected in the file dialog box. /// </summary> /// <value> /// A value containing the index of the filter currently selected in the file dialog box. The default value is 1. /// </value> [Description("The index of the filter currently selected in the file dialog box."), Category("Behavior"), DefaultValue(1)] public int FilterIndex { get { if( DownlevelDialog != null ) return DownlevelDialog.FilterIndex; return _filterIndex; } set { if( DownlevelDialog != null ) DownlevelDialog.FilterIndex = value; else _filterIndex = value; } } /// <summary> /// Gets or sets the initial directory displayed by the file dialog box. /// </summary> /// <value> /// The initial directory displayed by the file dialog box. The default is an empty string (""). /// </value> [Description("The initial directory displayed by the file dialog box."), DefaultValue(""), Category("Data")] public string InitialDirectory { get { if( DownlevelDialog != null ) return DownlevelDialog.InitialDirectory; if( _initialDirectory != null ) return _initialDirectory; else return string.Empty; } set { if( DownlevelDialog != null ) DownlevelDialog.InitialDirectory = value; else _initialDirectory = value; } } /// <summary> /// Gets or sets a value indicating whether the dialog box restores the current directory before closing. /// </summary> /// <value> /// <see langword="true" /> if the dialog box restores the current directory to its original value if the user changed the /// directory while searching for files; otherwise, <see langword="false" />. The default value is <see langword="false" />. /// </value> [DefaultValue(false), Description("A value indicating whether the dialog box restores the current directory before closing."), Category("Behavior")] public bool RestoreDirectory { get { if( DownlevelDialog != null ) return DownlevelDialog.RestoreDirectory; return GetOption(NativeMethods.FOS.FOS_NOCHANGEDIR); } set { if( DownlevelDialog != null ) DownlevelDialog.RestoreDirectory = value; else SetOption(NativeMethods.FOS.FOS_NOCHANGEDIR, value); } } /// <summary> /// Gets or sets the file dialog box title. /// </summary> /// <value> /// The file dialog box title. The default value is an empty string (""). /// </value> [Description("The file dialog box title."), Category("Appearance"), DefaultValue(""), Localizable(true)] public string Title { get { if( DownlevelDialog != null ) return DownlevelDialog.Title; if( _title != null ) return _title; else return string.Empty; } set { if( DownlevelDialog != null ) DownlevelDialog.Title = value; else _title = value; } } /// <summary> /// Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names. /// </summary> /// <value> /// <see langword="true" /> if the dialog box accepts only valid Win32 file names; otherwise, <see langword="false" />. The default value is <see langword="false" />. /// </value> [DefaultValue(true), Category("Behavior"), Description("A value indicating whether the dialog box accepts only valid Win32 file names.")] public bool ValidateNames { get { if( DownlevelDialog != null ) return DownlevelDialog.ValidateNames; return !GetOption(NativeMethods.FOS.FOS_NOVALIDATE); } set { if( DownlevelDialog != null ) DownlevelDialog.ValidateNames = value; else SetOption(NativeMethods.FOS.FOS_NOVALIDATE, !value); } } #endregion #region Protected Properties /// <summary> /// Gets or sets the downlevel file dialog which is to be used if the Vista-style /// dialog is not supported. /// </summary> /// <value> /// The regular <see cref="FileDialog"/> that is used when the Vista-style file dialog /// is not supported. /// </value> /// <remarks> /// This property is set by classes that derive from <see cref="VistaFileDialog"/>. /// </remarks> [Browsable(false)] protected FileDialog DownlevelDialog { get { return _downlevelDialog; } set { _downlevelDialog = value; if( value != null ) { //value.HelpRequest += new EventHandler(DownlevelDialog_HelpRequest); value.FileOk += new System.ComponentModel.CancelEventHandler(DownlevelDialog_FileOk); } } } #endregion #region Internal Properties internal string[] FileNamesInternal { private get { if( _fileNames == null ) { return new string[0]; } return (string[])_fileNames.Clone(); } set { _fileNames = value; } } #endregion #region Public Methods /// <summary> /// Resets all properties to their default values. /// </summary> public virtual void Reset() { if( DownlevelDialog != null ) DownlevelDialog.Reset(); else { _fileNames = null; _filter = null; _filterIndex = 1; _addExtension = true; _defaultExt = null; _options = 0; _title = null; CheckPathExists = true; } } /// <summary> /// Displays the file dialog. /// </summary> /// <returns>If the user clicks the OK button of the dialog that is displayed (e.g. <see cref="VistaOpenFileDialog" />, <see cref="VistaSaveFileDialog" />), <see langword="true" /> is returned; otherwise, <see langword="false" />.</returns> public bool? ShowDialog() { return ShowDialog(null); } /// <summary> /// Displays the file dialog. /// </summary> /// <param name="owner">Handle to the window that owns the dialog.</param> /// <returns>If the user clicks the OK button of the dialog that is displayed (e.g. <see cref="VistaOpenFileDialog" />, <see cref="VistaSaveFileDialog" />), <see langword="true" /> is returned; otherwise, <see langword="false" />.</returns> public bool? ShowDialog(Window owner) { _owner = owner; if( DownlevelDialog != null ) return DownlevelDialog.ShowDialog(owner); else { IntPtr ownerHandle = owner == null ? NativeMethods.GetActiveWindow() : new WindowInteropHelper(owner).Handle; return new bool?(RunFileDialog(ownerHandle)); } } #endregion #region Protected Methods internal void SetOption(NativeMethods.FOS option, bool value) { if( value ) _options |= option; else _options &= ~option; } internal bool GetOption(NativeMethods.FOS option) { return (_options & option) != 0; } internal virtual void GetResult(Ookii.Dialogs.Wpf.Interop.IFileDialog dialog) { if( !GetOption(NativeMethods.FOS.FOS_ALLOWMULTISELECT) ) { _fileNames = new string[1]; Ookii.Dialogs.Wpf.Interop.IShellItem result; dialog.GetResult(out result); result.GetDisplayName(NativeMethods.SIGDN.SIGDN_FILESYSPATH, out _fileNames[0]); } } /// <summary> /// Raises the <see cref="FileOk" /> event. /// </summary> /// <param name="e">A <see cref="System.ComponentModel.CancelEventArgs" /> that contains the event data.</param> protected virtual void OnFileOk(System.ComponentModel.CancelEventArgs e) { System.ComponentModel.CancelEventHandler handler = FileOk; if( handler != null ) handler(this, e); } #endregion #region Internal Methods internal bool PromptUser(string text, MessageBoxButton buttons, MessageBoxImage icon, MessageBoxResult defaultResult) { string caption = string.IsNullOrEmpty(_title) ? (this is VistaOpenFileDialog ? ComDlgResources.LoadString(ComDlgResources.ComDlgResourceId.Open) : ComDlgResources.LoadString(ComDlgResources.ComDlgResourceId.ConfirmSaveAs)) : _title; MessageBoxOptions options = 0; if( System.Threading.Thread.CurrentThread.CurrentUICulture.TextInfo.IsRightToLeft ) options |= MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading; return MessageBox.Show(_owner, text, caption, buttons, icon, defaultResult, options) == MessageBoxResult.Yes; } internal virtual void SetDialogProperties(Ookii.Dialogs.Wpf.Interop.IFileDialog dialog) { uint cookie; dialog.Advise(new VistaFileDialogEvents(this), out cookie); // Set the default file name if( !(_fileNames == null || _fileNames.Length == 0 || string.IsNullOrEmpty(_fileNames[0])) ) { string parent = Path.GetDirectoryName(_fileNames[0]); if( parent == null || !Directory.Exists(parent) ) { dialog.SetFileName(_fileNames[0]); } else { string folder = Path.GetFileName(_fileNames[0]); dialog.SetFolder(NativeMethods.CreateItemFromParsingName(parent)); dialog.SetFileName(folder); } } // Set the filter if( !string.IsNullOrEmpty(_filter) ) { string[] filterElements = _filter.Split(new char[] { '|' }); NativeMethods.COMDLG_FILTERSPEC[] filter = new NativeMethods.COMDLG_FILTERSPEC[filterElements.Length / 2]; for( int x = 0; x < filterElements.Length; x += 2 ) { filter[x / 2].pszName = filterElements[x]; filter[x / 2].pszSpec = filterElements[x + 1]; } dialog.SetFileTypes((uint)filter.Length, filter); if( _filterIndex > 0 && _filterIndex <= filter.Length ) dialog.SetFileTypeIndex((uint)_filterIndex); } // Default extension if( _addExtension && !string.IsNullOrEmpty(_defaultExt) ) { dialog.SetDefaultExtension(_defaultExt); } // Initial directory if( !string.IsNullOrEmpty(_initialDirectory) ) { Ookii.Dialogs.Wpf.Interop.IShellItem item = NativeMethods.CreateItemFromParsingName(_initialDirectory); dialog.SetDefaultFolder(item); } if( !string.IsNullOrEmpty(_title) ) { dialog.SetTitle(_title); } dialog.SetOptions((_options | NativeMethods.FOS.FOS_FORCEFILESYSTEM)); } internal abstract Ookii.Dialogs.Wpf.Interop.IFileDialog CreateFileDialog(); internal bool DoFileOk(Ookii.Dialogs.Wpf.Interop.IFileDialog dialog) { GetResult(dialog); System.ComponentModel.CancelEventArgs e = new System.ComponentModel.CancelEventArgs(); OnFileOk(e); return !e.Cancel; } #endregion #region Private Methods private bool RunFileDialog(IntPtr hwndOwner) { Ookii.Dialogs.Wpf.Interop.IFileDialog dialog = null; try { dialog = CreateFileDialog(); SetDialogProperties(dialog); int result = dialog.Show(hwndOwner); if( result < 0 ) { if( (uint)result == (uint)HRESULT.ERROR_CANCELLED ) return false; else throw System.Runtime.InteropServices.Marshal.GetExceptionForHR(result); } return true; } finally { if( dialog != null ) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(dialog); } } private void DownlevelDialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { OnFileOk(e); } #endregion } }
// Copyright 2013, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: thagikura@gmail.com (Takeshi Hagikura) using Google.Api.Ads.Common.Lib; using System; using System.Collections.Generic; using System.Reflection; namespace Google.Api.Ads.AdWords.Lib { /// <summary> /// Lists all the services available through this library. /// </summary> public partial class AdWordsService : AdsService { /// <summary> /// All the services available in v201309. /// </summary> public class v201309 { /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/OfflineConversionFeedService.html"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature OfflineConversionFeedService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/AdGroupAdService.html"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature AdGroupAdService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/AdGroupCriterionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupCriterionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/AdGroupFeedService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupFeedService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/AdGroupService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/AdGroupBidModifierService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupBidModifierService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/AdParamService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdParamService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/AdwordsUserListService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdwordsUserListService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/AlertService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AlertService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/BiddingStrategyService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BiddingStrategyService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/BudgetService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BudgetService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/BudgetOrderService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BudgetOrderService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/CampaignAdExtensionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignAdExtensionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/CampaignCriterionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignCriterionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/CampaignFeedService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignFeedService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/CampaignService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/CampaignSharedSetService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignSharedSetService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/ConstantDataService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ConstantDataService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/ConversionTrackerService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ConversionTrackerService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/CustomerService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/CustomerSyncService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerSyncService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/DataService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature DataService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/ExperimentService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ExperimentService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/FeedService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/FeedItemService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedItemService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/FeedMappingService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedMappingService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/GeoLocationService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature GeoLocationService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/LocationCriterionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LocationCriterionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/ManagedCustomerService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ManagedCustomerService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/MediaService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature MediaService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/MutateJobService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature MutateJobService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/ReportDefinitionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ReportDefinitionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/SharedCriterionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SharedCriterionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/SharedSetService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SharedSetService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/TargetingIdeaService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TargetingIdeaService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201309/TrafficEstimatorService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TrafficEstimatorService; /// <summary> /// Factory type for v201309 services. /// </summary> public static readonly Type factoryType = typeof(AdWordsServiceFactory); /// <summary> /// Static constructor to initialize the service constants. /// </summary> static v201309() { OfflineConversionFeedService = AdWordsService.MakeServiceSignature("v201309", "cm", "OfflineConversionFeedService"); AdGroupAdService = AdWordsService.MakeServiceSignature("v201309", "cm", "AdGroupAdService"); AdGroupCriterionService = AdWordsService.MakeServiceSignature("v201309", "cm", "AdGroupCriterionService"); AdGroupService = AdWordsService.MakeServiceSignature("v201309", "cm", "AdGroupService"); AdGroupBidModifierService = AdWordsService.MakeServiceSignature("v201309", "cm", "AdGroupBidModifierService"); AdGroupFeedService = AdWordsService.MakeServiceSignature("v201309", "cm", "AdGroupFeedService"); AdParamService = AdWordsService.MakeServiceSignature("v201309", "cm", "AdParamService"); AdwordsUserListService = AdWordsService.MakeServiceSignature("v201309", "rm", "AdwordsUserListService"); AlertService = AdWordsService.MakeServiceSignature("v201309", "mcm", "AlertService"); BiddingStrategyService = AdWordsService.MakeServiceSignature("v201309", "cm", "BiddingStrategyService"); BudgetService = AdWordsService.MakeServiceSignature("v201309", "cm", "BudgetService"); BudgetOrderService = AdWordsService.MakeServiceSignature("v201309", "billing", "BudgetOrderService"); CampaignAdExtensionService = AdWordsService.MakeServiceSignature("v201309", "cm", "CampaignAdExtensionService"); CampaignCriterionService = AdWordsService.MakeServiceSignature("v201309", "cm", "CampaignCriterionService"); CampaignService = AdWordsService.MakeServiceSignature("v201309", "cm", "CampaignService"); CampaignFeedService = AdWordsService.MakeServiceSignature("v201309", "cm", "CampaignFeedService"); CampaignSharedSetService = AdWordsService.MakeServiceSignature("v201309", "cm", "CampaignSharedSetService"); ConstantDataService = AdWordsService.MakeServiceSignature("v201309", "cm", "ConstantDataService"); ConversionTrackerService = AdWordsService.MakeServiceSignature("v201309", "cm", "ConversionTrackerService"); CustomerService = AdWordsService.MakeServiceSignature("v201309", "mcm", "CustomerService"); CustomerSyncService = AdWordsService.MakeServiceSignature("v201309", "ch", "CustomerSyncService"); DataService = AdWordsService.MakeServiceSignature( "v201309", "cm", "DataService"); ExperimentService = AdWordsService.MakeServiceSignature("v201309", "cm", "ExperimentService"); FeedService = AdWordsService.MakeServiceSignature("v201309", "cm", "FeedService"); FeedItemService = AdWordsService.MakeServiceSignature("v201309", "cm", "FeedItemService"); FeedMappingService = AdWordsService.MakeServiceSignature("v201309", "cm", "FeedMappingService"); GeoLocationService = AdWordsService.MakeServiceSignature("v201309", "cm", "GeoLocationService"); LocationCriterionService = AdWordsService.MakeServiceSignature("v201309", "cm", "LocationCriterionService"); ManagedCustomerService = AdWordsService.MakeServiceSignature("v201309", "mcm", "ManagedCustomerService"); MediaService = AdWordsService.MakeServiceSignature("v201309", "cm", "MediaService"); MutateJobService = AdWordsService.MakeServiceSignature("v201309", "cm", "MutateJobService"); ReportDefinitionService = AdWordsService.MakeServiceSignature("v201309", "cm", "ReportDefinitionService"); SharedCriterionService = AdWordsService.MakeServiceSignature("v201309", "cm", "SharedCriterionService"); SharedSetService = AdWordsService.MakeServiceSignature("v201309", "cm", "SharedSetService"); TargetingIdeaService = AdWordsService.MakeServiceSignature("v201309", "o", "TargetingIdeaService"); TrafficEstimatorService = AdWordsService.MakeServiceSignature("v201309", "o", "TrafficEstimatorService"); } } } }
using System; using System.Collections; using System.Data; using PCSComProduction.DCP.DS; using PCSComProduction.WorkOrder.DS; using PCSComUtils.Common; using PCSComUtils.MasterSetup.DS; using PCSComUtils.DataContext; using System.Linq; using System.Transactions; using PCSComUtils.PCSExc; using PCSComUtils.DataAccess; using IsolationLevel = System.Transactions.IsolationLevel; namespace PCSComProduction.WorkOrder.BO { /// <summary> /// Multi WO Issue Material BO /// </summary> public class MultiWOIssueMaterialBO { private const string This = "PCSComProduction.WorkOrder.BO.MultiWOIssueMaterialBO"; #region IMultiWOIssueMaterialBO Members public DataSet GetWorkingTime() { var dsShiftPattern = new PRO_ShiftPatternDS(); return dsShiftPattern.GetWorkingTime(); } public decimal GetOHQuantity(int iCcnid, int iBinId, int iLocationId, int iProductId) { using (var db = new PCSDataContext(Utils.Instance.ConnectionString)) { var objBin = db.IV_BinCaches.SingleOrDefault(e => e.LocationID == iLocationId && e.BinID == iBinId && e.ProductID == iProductId); if (objBin != null) { if (objBin.OHQuantity != null) return Convert.ToDecimal(objBin.OHQuantity.ToString()); } } return 0; } public int AddAndReturnId(object pobjMaster, DataSet pdstDetailData) { const string methodName = "PCSComProduction.WorkOrder.BO.AddAndReturnID()"; try { using (var trans = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {IsolationLevel = IsolationLevel.ReadCommitted, Timeout = new TimeSpan(0, 1, 0)})) { using (var db = new PCSDataContext(Utils.Instance.ConnectionString)) { var serverDate = db.GetServerDate(); var tranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.PROIssueMaterial.ToString()).TranTypeID; #region add the master first //add the master first var objMaster = (PRO_IssueMaterialMasterVO)pobjMaster; var issueMaster = new PRO_IssueMaterialMaster { MasterLocationID = objMaster.MasterLocationID, PostDate = objMaster.PostDate, IssueNo = objMaster.IssueNo, CCNID = objMaster.CCNID, IssuePurposeID = objMaster.IssuePurposeID, ToLocationID = objMaster.ToLocationID, ToBinID = objMaster.ToBinID, ShiftID = objMaster.ShiftID }; if (objMaster.WorkOrderMasterID > 0) issueMaster.WorkOrderMasterID = objMaster.WorkOrderMasterID; if (objMaster.WorkOrderDetailID > 0) issueMaster.WorkOrderDetailID = objMaster.WorkOrderDetailID; #endregion #region insert issue detail //update the detail foreach (var issueDetail in from DataRow dr in pdstDetailData.Tables[0].Rows where dr.RowState != DataRowState.Deleted select CreateIssueDetail(dr)) { issueMaster.PRO_IssueMaterialDetails.Add(issueDetail); } db.PRO_IssueMaterialMasters.InsertOnSubmit(issueMaster); db.SubmitChanges(); #endregion #region cache data foreach (var issueDetail in issueMaster.PRO_IssueMaterialDetails) { var allowNegative = issueDetail.ITM_Product.AllowNegativeQty.GetValueOrDefault(false); #region subtract from source cache #region bin cache var sourceBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueDetail.LocationID && e.BinID == issueDetail.BinID && e.ProductID == issueDetail.ProductID); if (!allowNegative && (sourceBin == null || sourceBin.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity)) { var productError = new Hashtable { { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID }, { IV_BinCacheTable.OHQUANTITY_FLD, sourceBin == null ? 0 : sourceBin.OHQuantity.GetValueOrDefault(0) } }; throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError); } if (sourceBin != null) { sourceBin.OHQuantity = sourceBin.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity; } else { // create new record sourceBin = new IV_BinCache { BinID = issueDetail.BinID.GetValueOrDefault(0), CCNID = issueMaster.CCNID, LocationID = issueDetail.LocationID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = -issueDetail.CommitQuantity }; db.IV_BinCaches.InsertOnSubmit(sourceBin); } #endregion #region location cache var sourceLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.LocationID == issueDetail.LocationID && e.ProductID == issueDetail.ProductID); if (!allowNegative && (sourceLocation == null || sourceLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity)) { var productError = new Hashtable { { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID }, { IV_BinCacheTable.OHQUANTITY_FLD, sourceLocation == null ? 0 : sourceLocation.OHQuantity.GetValueOrDefault(0) } }; throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError); } if (sourceLocation != null) { sourceLocation.OHQuantity = sourceLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity; } else { // create new record sourceLocation = new IV_LocationCache { CCNID = issueMaster.CCNID, LocationID = issueDetail.LocationID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = -issueDetail.CommitQuantity }; db.IV_LocationCaches.InsertOnSubmit(sourceLocation); } #endregion #region master location cache var sourceMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.ProductID == issueDetail.ProductID); if (!allowNegative && (sourceMasLocation == null || sourceMasLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity)) { var productError = new Hashtable { { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID }, { IV_BinCacheTable.OHQUANTITY_FLD, sourceMasLocation == null ? 0 : sourceMasLocation.OHQuantity.GetValueOrDefault(0) } }; throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError); } if (sourceMasLocation != null) { sourceMasLocation.OHQuantity = sourceMasLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity; } else { // create new record sourceMasLocation = new IV_MasLocCache { CCNID = issueMaster.CCNID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = -issueDetail.CommitQuantity }; db.IV_MasLocCaches.InsertOnSubmit(sourceMasLocation); } #endregion #region Transaction history var sourceHistory = new MST_TransactionHistory { CCNID = issueMaster.CCNID, StockUMID = issueDetail.StockUMID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, LocationID = issueDetail.LocationID, BinID = issueDetail.BinID, RefMasterID = issueMaster.IssueMaterialMasterID, RefDetailID = issueDetail.IssueMaterialDetailID, PostDate = issueMaster.PostDate, TransDate = serverDate, Quantity = -issueDetail.CommitQuantity, UserName = SystemProperty.UserName, TranTypeID = tranTypeId, BinCommitQuantity = sourceBin.CommitQuantity, BinOHQuantity = sourceBin.OHQuantity, IssuePurposeID = issueMaster.IssuePurposeID, LocationCommitQuantity = sourceLocation.CommitQuantity, LocationOHQuantity = sourceLocation.OHQuantity, MasLocCommitQuantity = sourceMasLocation.CommitQuantity, MasLocOHQuantity = sourceMasLocation.OHQuantity }; db.MST_TransactionHistories.InsertOnSubmit(sourceHistory); #endregion #endregion #region add to destination cache #region bin cache var destBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueMaster.ToLocationID && e.BinID == issueMaster.ToBinID && e.ProductID == issueDetail.ProductID); if (destBin != null) { destBin.OHQuantity = destBin.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity; } else { // create new record destBin = new IV_BinCache { BinID = issueMaster.ToBinID.GetValueOrDefault(0), CCNID = issueMaster.CCNID, LocationID = issueMaster.ToLocationID.GetValueOrDefault(0), MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = issueDetail.CommitQuantity }; db.IV_BinCaches.InsertOnSubmit(destBin); } #endregion #region location cache var destLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.LocationID == issueMaster.ToLocationID && e.ProductID == issueDetail.ProductID); if (destLocation != null) { destLocation.OHQuantity = destLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity; } else { // create new record destLocation = new IV_LocationCache { CCNID = issueMaster.CCNID, LocationID = issueMaster.ToLocationID.GetValueOrDefault(0), MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = issueDetail.CommitQuantity }; db.IV_LocationCaches.InsertOnSubmit(destLocation); } #endregion #region master location cache var destMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.ProductID == issueDetail.ProductID); if (destMasLocation != null) { destMasLocation.OHQuantity = destMasLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity; } else { // create new record destMasLocation = new IV_MasLocCache { CCNID = issueMaster.CCNID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = issueDetail.CommitQuantity }; db.IV_MasLocCaches.InsertOnSubmit(destMasLocation); } #endregion #region Transaction history var destHistory = new MST_TransactionHistory { CCNID = issueMaster.CCNID, StockUMID = issueDetail.StockUMID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, LocationID = issueMaster.ToLocationID, BinID = issueMaster.ToBinID, RefMasterID = issueMaster.IssueMaterialMasterID, RefDetailID = issueDetail.IssueMaterialDetailID, PostDate = issueMaster.PostDate, TransDate = serverDate, Quantity = issueDetail.CommitQuantity, UserName = SystemProperty.UserName, TranTypeID = tranTypeId, BinCommitQuantity = destBin.CommitQuantity, BinOHQuantity = destBin.OHQuantity, IssuePurposeID = issueMaster.IssuePurposeID, LocationCommitQuantity = destLocation.CommitQuantity, LocationOHQuantity = destLocation.OHQuantity, MasLocCommitQuantity = destMasLocation.CommitQuantity, MasLocOHQuantity = destMasLocation.OHQuantity }; db.MST_TransactionHistories.InsertOnSubmit(destHistory); #endregion #endregion db.SubmitChanges(); } #endregion db.SubmitChanges(); trans.Complete(); return issueMaster.IssueMaterialMasterID; } } } catch (PCSBOException ex) { if (ex.mCode == ErrorCode.SQLDUPLICATE_KEYCODE) throw new PCSDBException(ErrorCode.DUPLICATE_KEY, methodName, ex); if (ex.mCode == ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE) throw; throw new PCSDBException(ErrorCode.ERROR_DB, methodName, ex); } } private static PRO_IssueMaterialDetail CreateIssueDetail(DataRow dr) { var objDetail = new PRO_IssueMaterialDetail(); if (dr[PRO_IssueMaterialDetailTable.LINE_FLD] != DBNull.Value) { objDetail.Line = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.LINE_FLD]); } if (dr[PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD] != DBNull.Value) { objDetail.CommitQuantity = Convert.ToDecimal(dr[PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD]); } if (dr[PRO_IssueMaterialDetailTable.PRODUCTID_FLD] != DBNull.Value) { objDetail.ProductID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.PRODUCTID_FLD]); } if (dr[PRO_IssueMaterialDetailTable.LOCATIONID_FLD] != DBNull.Value) { objDetail.LocationID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.LOCATIONID_FLD]); } if (dr[PRO_IssueMaterialDetailTable.BINID_FLD] != DBNull.Value) { objDetail.BinID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.BINID_FLD]); } objDetail.Lot = dr[PRO_IssueMaterialDetailTable.LOT_FLD].ToString(); objDetail.Serial = dr[PRO_IssueMaterialDetailTable.SERIAL_FLD].ToString(); if (dr[PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD] != DBNull.Value) { objDetail.MasterLocationID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD]); } if (dr[PRO_IssueMaterialDetailTable.STOCKUMID_FLD] != DBNull.Value) { objDetail.StockUMID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.STOCKUMID_FLD]); } if (dr[PRO_IssueMaterialDetailTable.QASTATUS_FLD] != DBNull.Value) { objDetail.QAStatus = Convert.ToByte(dr[PRO_IssueMaterialDetailTable.QASTATUS_FLD]); } if (dr[PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD] != DBNull.Value) { objDetail.WorkOrderMasterID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD]); } if (dr[PRO_IssueMaterialDetailTable.AVAILABLEQUANTITY_FLD] != DBNull.Value) { objDetail.AvailableQuantity = Convert.ToDecimal(dr[PRO_IssueMaterialDetailTable.AVAILABLEQUANTITY_FLD]); } if (dr[PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD] != DBNull.Value) { objDetail.WorkOrderDetailID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD]); } if (dr[PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD] != DBNull.Value) { objDetail.BomQuantity = Convert.ToDecimal(dr[PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD]); } return objDetail; } /// <summary> /// This method is used to get all the detail of the issue material /// Based on the Master ID of the table Issue Master Material /// </summary> /// <param name="pintMasterId"></param> /// <returns></returns> public DataSet GetDetailData(int pintMasterId) { var objProIssueMaterialDetailDS = new PRO_IssueMaterialDetailDS(); DataSet dstDetailData = objProIssueMaterialDetailDS.GetDetailData(pintMasterId); return dstDetailData; } /// <summary> /// /// </summary> /// <param name="pstrLocationCode"></param> /// <returns>MST_LocationVO</returns> public string GetLocationNameByLocationCode(string pstrLocationCode) { var objDS = new MST_LocationDS(); return objDS.GetNameFromCode(pstrLocationCode); } #endregion /// <summary> /// Delete transaction /// </summary> /// <param name="issueMasterId"></param> public void DeleteTransaction(int issueMasterId) { const string methodName = This + ".DeleteTransaction()"; try { using (var trans = new TransactionScope()) { using (var db = new PCSDataContext(Utils.Instance.ConnectionString)) { var tranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.PROIssueMaterial.ToString()).TranTypeID; var deleteTranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.DeleteTransaction.ToString()).TranTypeID; var serverDate = db.GetServerDate(); #region PRO_IssueMaterialMasters var issueMaster = db.PRO_IssueMaterialMasters.FirstOrDefault(e => e.IssueMaterialMasterID == issueMasterId); if (issueMaster == null) return; #endregion #region old transaction history to be updated var oldSourceHistory = db.MST_TransactionHistories.Where(e => e.RefMasterID == issueMasterId && e.TranTypeID == tranTypeId); foreach (var history in oldSourceHistory) { // mark as delete transaction history.TranTypeID = deleteTranTypeId; history.UserName = SystemProperty.UserName; } #endregion #region cache data foreach (var issueDetail in issueMaster.PRO_IssueMaterialDetails) { var allowNegative = issueDetail.ITM_Product.AllowNegativeQty.GetValueOrDefault(false); #region subtract from destionation cache #region bin cache var destBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueMaster.ToLocationID && e.BinID == issueMaster.ToBinID && e.ProductID == issueDetail.ProductID); if (!allowNegative && (destBin == null || destBin.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity)) { var productError = new Hashtable { { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID }, { IV_BinCacheTable.OHQUANTITY_FLD, destBin == null ? 0 : destBin.OHQuantity.GetValueOrDefault(0) } }; throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError); } if (destBin != null) { destBin.OHQuantity = destBin.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity; } else { // create new record destBin = new IV_BinCache { BinID = issueMaster.ToBinID.GetValueOrDefault(0), CCNID = issueMaster.CCNID, LocationID = issueMaster.ToLocationID.GetValueOrDefault(0), MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = -issueDetail.CommitQuantity }; db.IV_BinCaches.InsertOnSubmit(destBin); } #endregion #region location cache var destLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.LocationID == issueMaster.ToLocationID && e.ProductID == issueDetail.ProductID); if (!allowNegative && (destLocation == null || destLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity)) { var productError = new Hashtable { { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID }, { IV_BinCacheTable.OHQUANTITY_FLD, destLocation == null ? 0 : destLocation.OHQuantity.GetValueOrDefault(0) } }; throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError); } if (destLocation != null) { destLocation.OHQuantity = destLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity; } else { // create new record destLocation = new IV_LocationCache { CCNID = issueMaster.CCNID, LocationID = issueMaster.ToLocationID.GetValueOrDefault(0), MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = -issueDetail.CommitQuantity }; db.IV_LocationCaches.InsertOnSubmit(destLocation); } #endregion #region master location cache var destMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.ProductID == issueDetail.ProductID); if (!allowNegative && (destMasLocation == null || destMasLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity)) { var productError = new Hashtable { { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID }, { IV_BinCacheTable.OHQUANTITY_FLD, destMasLocation == null ? 0 : destMasLocation.OHQuantity.GetValueOrDefault(0) } }; throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError); } if (destMasLocation != null) { destMasLocation.OHQuantity = destMasLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity; } else { // create new record destMasLocation = new IV_MasLocCache { CCNID = issueMaster.CCNID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = -issueDetail.CommitQuantity }; db.IV_MasLocCaches.InsertOnSubmit(destMasLocation); } #endregion #region Transaction history var destHistory = new MST_TransactionHistory { CCNID = issueMaster.CCNID, StockUMID = issueDetail.StockUMID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, LocationID = issueMaster.ToLocationID, BinID = issueMaster.ToBinID, RefMasterID = issueMaster.IssueMaterialMasterID, RefDetailID = issueDetail.IssueMaterialDetailID, PostDate = issueMaster.PostDate, TransDate = serverDate, Quantity = -issueDetail.CommitQuantity, UserName = SystemProperty.UserName, TranTypeID = tranTypeId, BinCommitQuantity = destBin.CommitQuantity, BinOHQuantity = destBin.OHQuantity, IssuePurposeID = issueMaster.IssuePurposeID, LocationCommitQuantity = destLocation.CommitQuantity, LocationOHQuantity = destLocation.OHQuantity, MasLocCommitQuantity = destMasLocation.CommitQuantity, MasLocOHQuantity = destMasLocation.OHQuantity }; db.MST_TransactionHistories.InsertOnSubmit(destHistory); #endregion #endregion #region add to source cache #region bin cache var sourceBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueDetail.LocationID && e.BinID == issueDetail.BinID && e.ProductID == issueDetail.ProductID); if (sourceBin != null) { sourceBin.OHQuantity = sourceBin.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity; } else { // create new record sourceBin = new IV_BinCache { BinID = issueDetail.BinID.GetValueOrDefault(0), CCNID = issueMaster.CCNID, LocationID = issueDetail.LocationID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = issueDetail.CommitQuantity }; db.IV_BinCaches.InsertOnSubmit(sourceBin); } #endregion #region location cache var sourceLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.LocationID == issueDetail.LocationID && e.ProductID == issueDetail.ProductID); if (sourceLocation != null) { sourceLocation.OHQuantity = sourceLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity; } else { // create new record sourceLocation = new IV_LocationCache { CCNID = issueMaster.CCNID, LocationID = issueDetail.LocationID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = issueDetail.CommitQuantity }; db.IV_LocationCaches.InsertOnSubmit(sourceLocation); } #endregion #region master location cache var sourceMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.ProductID == issueDetail.ProductID); if (sourceMasLocation != null) { sourceMasLocation.OHQuantity = sourceMasLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity; } else { // create new record sourceMasLocation = new IV_MasLocCache { CCNID = issueMaster.CCNID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, OHQuantity = issueDetail.CommitQuantity }; db.IV_MasLocCaches.InsertOnSubmit(sourceMasLocation); } #endregion #region Transaction history var sourceHistory = new MST_TransactionHistory { CCNID = issueMaster.CCNID, StockUMID = issueDetail.StockUMID, MasterLocationID = issueMaster.MasterLocationID, ProductID = issueDetail.ProductID, LocationID = issueDetail.LocationID, BinID = issueDetail.BinID, RefMasterID = issueMaster.IssueMaterialMasterID, RefDetailID = issueDetail.IssueMaterialDetailID, PostDate = issueMaster.PostDate, TransDate = serverDate, Quantity = issueDetail.CommitQuantity, UserName = SystemProperty.UserName, TranTypeID = tranTypeId, BinCommitQuantity = sourceBin.CommitQuantity, BinOHQuantity = sourceBin.OHQuantity, IssuePurposeID = issueMaster.IssuePurposeID, LocationCommitQuantity = sourceLocation.CommitQuantity, LocationOHQuantity = sourceLocation.OHQuantity, MasLocCommitQuantity = sourceMasLocation.CommitQuantity, MasLocOHQuantity = sourceMasLocation.OHQuantity }; db.MST_TransactionHistories.InsertOnSubmit(sourceHistory); #endregion #endregion db.PRO_IssueMaterialDetails.DeleteOnSubmit(issueDetail); } #endregion db.PRO_IssueMaterialMasters.DeleteOnSubmit(issueMaster); db.SubmitChanges(); trans.Complete(); } } } catch (PCSBOException ex) { if (ex.mCode == ErrorCode.SQLDUPLICATE_KEYCODE) throw new PCSDBException(ErrorCode.DUPLICATE_KEY, methodName, ex); if (ex.mCode == ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE) throw; throw new PCSDBException(ErrorCode.ERROR_DB, methodName, ex); } } /// <summary> /// /// </summary> /// <param name="pintIssueMasterId"></param> /// <returns></returns> public DataTable GetMasterIssue(int pintIssueMasterId) { return (new PRO_IssueMaterialMasterDS()).GetMasterIssue(pintIssueMasterId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; using System.Net; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.IO; namespace umbraco.cms.businesslogic.packager.repositories { public class Repository : DisposableObject { public string Guid { get; private set; } public string Name { get; private set; } public string RepositoryUrl { get; private set; } public string WebserviceUrl { get; private set; } public RepositoryWebservice Webservice { get { var repo = new RepositoryWebservice(WebserviceUrl); return repo; } } public SubmitStatus SubmitPackage(string authorGuid, PackageInstance package, byte[] doc) { string packageName = package.Name; string packageGuid = package.PackageGuid; string description = package.Readme; string packageFile = package.PackagePath; System.IO.FileStream fs1 = null; try { byte[] pack = new byte[0]; fs1 = System.IO.File.Open(IOHelper.MapPath(packageFile), FileMode.Open, FileAccess.Read); pack = new byte[fs1.Length]; fs1.Read(pack, 0, (int) fs1.Length); fs1.Close(); fs1 = null; byte[] thumb = new byte[0]; //todo upload thumbnail... return Webservice.SubmitPackage(Guid, authorGuid, packageGuid, pack, doc, thumb, packageName, "", "", description); } catch (Exception ex) { LogHelper.Error<Repository>("An error occurred in SubmitPackage", ex); return SubmitStatus.Error; } } public static List<Repository> getAll() { var repositories = new List<Repository>(); foreach (var r in UmbracoConfig.For.UmbracoSettings().PackageRepositories.Repositories) { var repository = new Repository { Guid = r.Id.ToString(), Name = r.Name }; repository.RepositoryUrl = r.RepositoryUrl; repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + r.WebServiceUrl.Trim('/'); if (r.HasCustomWebServiceUrl) { string wsUrl = r.WebServiceUrl; if (wsUrl.Contains("://")) { repository.WebserviceUrl = r.WebServiceUrl; } else { repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + wsUrl.Trim('/'); } } repositories.Add(repository); } return repositories; } public static Repository getByGuid(string repositoryGuid) { Guid id; if (System.Guid.TryParse(repositoryGuid, out id) == false) { throw new FormatException("The repositoryGuid is not a valid GUID"); } var found = UmbracoConfig.For.UmbracoSettings().PackageRepositories.Repositories.FirstOrDefault(x => x.Id == id); if (found == null) { return null; } var repository = new Repository { Guid = found.Id.ToString(), Name = found.Name }; repository.RepositoryUrl = found.RepositoryUrl; repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + found.WebServiceUrl.Trim('/'); if (found.HasCustomWebServiceUrl) { string wsUrl = found.WebServiceUrl; if (wsUrl.Contains("://")) { repository.WebserviceUrl = found.WebServiceUrl; } else { repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + wsUrl.Trim('/'); } } return repository; } //shortcut method to download pack from repo and place it on the server... public string fetch(string packageGuid) { return fetch(packageGuid, string.Empty); } public bool HasConnection() { string strServer = this.RepositoryUrl; try { HttpWebRequest reqFP = (HttpWebRequest) HttpWebRequest.Create(strServer); HttpWebResponse rspFP = (HttpWebResponse) reqFP.GetResponse(); if (HttpStatusCode.OK == rspFP.StatusCode) { // HTTP = 200 - Internet connection available, server online rspFP.Close(); return true; } else { // Other status - Server or connection not available rspFP.Close(); return false; } } catch (WebException) { // Exception - connection not available return false; } } public string fetch(string packageGuid, string key) { byte[] fileByteArray = new byte[0]; if (key == string.Empty) { if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema) fileByteArray = this.Webservice.fetchPackage(packageGuid); else fileByteArray = this.Webservice.fetchPackageByVersion(packageGuid, Version.Version41); } else { fileByteArray = this.Webservice.fetchProtectedPackage(packageGuid, key); } //successfull if (fileByteArray.Length > 0) { // Check for package directory if (Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot)) == false) Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); using (var fs1 = new FileStream(IOHelper.MapPath(Settings.PackagerRoot + Path.DirectorySeparatorChar + packageGuid + ".umb"), FileMode.Create)) { fs1.Write(fileByteArray, 0, fileByteArray.Length); fs1.Close(); return "packages\\" + packageGuid + ".umb"; } } return ""; } /// <summary> /// Handles the disposal of resources. Derived from abstract class <see cref="DisposableObject"/> which handles common required locking logic. /// </summary> protected override void DisposeResources() { Webservice.Dispose(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.VisualBasic; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.RemoveEmptyFinalizersAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.RemoveEmptyFinalizersAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests { public class RemoveEmptyFinalizersTests { [Fact] public async Task CA1821CSharpTestNoWarning() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Diagnostics; public class Class1 { // No violation because the finalizer contains a method call ~Class1() { System.Console.Write("" ""); } } public class Class2 { // No violation because the finalizer contains a local declaration statement ~Class2() { var x = 1; } } public class Class3 { bool x = true; // No violation because the finalizer contains an expression statement ~Class3() { x = false; } } public class Class4 { // No violation because the finalizer's body is not empty ~Class4() { var x = false; Debug.Fail(""Finalizer called!""); } } public class Class5 { // No violation because the finalizer's body is not empty ~Class5() { while (true) ; } } public class Class6 { // No violation because the finalizer's body is not empty ~Class6() { System.Console.WriteLine(); Debug.Fail(""Finalizer called!""); } } public class Class7 { // Violation will not occur because the finalizer's body is not empty. ~Class7() { if (true) { Debug.Fail(""Finalizer called!""); } } } "); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizers() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { // Violation occurs because the finalizer is empty. ~Class1() { } } public class Class2 { // Violation occurs because the finalizer is empty. ~Class2() { //// Comments here } } ", GetCA1821CSharpResultAt(5, 3), GetCA1821CSharpResultAt(13, 3)); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithScope() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { // Violation occurs because the finalizer is empty. ~[|Class1|]() { } } public class Class2 { // Violation occurs because the finalizer is empty. ~[|Class2|]() { //// Comments here } } "); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithDebugFail() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Diagnostics; public class Class1 { // Violation occurs because Debug.Fail is a conditional method. // The finalizer will contain code only if the DEBUG directive // symbol is present at compile time. When the DEBUG // directive is not present, the finalizer will still exist, but // it will be empty. ~Class1() { Debug.Fail(""Finalizer called!""); } } ", GetCA1821CSharpResultAt(11, 3)); } [Fact, WorkItem(1788, "https://github.com/dotnet/roslyn-analyzers/issues/1788")] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithDebugFail_ExpressionBody() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Diagnostics; public class Class1 { // Violation occurs because Debug.Fail is a conditional method. // The finalizer will contain code only if the DEBUG directive // symbol is present at compile time. When the DEBUG // directive is not present, the finalizer will still exist, but // it will be empty. ~Class1() => Debug.Fail(""Finalizer called!""); } ", GetCA1821CSharpResultAt(11, 3)); } [Fact, WorkItem(1241, "https://github.com/dotnet/roslyn-analyzers/issues/1241")] public async Task CA1821_DebugFailAndDebugDirective_NoDiagnostic() { await new VerifyCS.Test { TestCode = @" public class Class1 { #if DEBUG // Violation will not occur because the finalizer will exist and // contain code when the DEBUG directive is present. When the // DEBUG directive is not present, the finalizer will not exist, // and therefore not be empty. ~Class1() { System.Diagnostics.Debug.Fail(""Finalizer called!""); } #endif } ", SolutionTransforms = { (solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = ((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols("DEBUG"); return project.WithParseOptions(parseOptions) .Solution; }, } }.RunAsync(); await new VerifyVB.Test { TestCode = @" Public Class Class1 #If DEBUG Then Protected Overrides Sub Finalize() System.Diagnostics.Debug.Fail(""Finalizer called!"") End Sub #End If End Class ", SolutionTransforms = { (solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = ((VisualBasicParseOptions)project.ParseOptions).WithPreprocessorSymbols(new KeyValuePair<string, object>("DEBUG", true)); return project.WithParseOptions(parseOptions) .Solution; }, } }.RunAsync(); } [Fact, WorkItem(1241, "https://github.com/dotnet/roslyn-analyzers/issues/1241")] public async Task CA1821_DebugFailAndReleaseDirective_NoDiagnostic_FalsePositive() { await new VerifyCS.Test { TestCode = @" public class Class1 { #if RELEASE // There should be a diagnostic because in release the finalizer will be empty. ~Class1() { System.Diagnostics.Debug.Fail(""Finalizer called!""); } #endif } ", SolutionTransforms = { (solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = ((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols("RELEASE"); return project.WithParseOptions(parseOptions) .Solution; }, } }.RunAsync(); await new VerifyVB.Test { TestCode = @" Public Class Class1 #If RELEASE Then ' There should be a diagnostic because in release the finalizer will be empty. Protected Overrides Sub Finalize() System.Diagnostics.Debug.Fail(""Finalizer called!"") End Sub #End If End Class ", SolutionTransforms = { (solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = ((VisualBasicParseOptions)project.ParseOptions).WithPreprocessorSymbols(new KeyValuePair<string, object>("RELEASE", true)); return project.WithParseOptions(parseOptions) .Solution; }, } }.RunAsync(); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithDebugFailAndDirectiveAroundStatements() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Diagnostics; public class Class1 { // Violation occurs because Debug.Fail is a conditional method. ~Class1() { Debug.Fail(""Class1 finalizer called!""); } } public class Class2 { // Violation will not occur because the finalizer's body is not empty. ~Class2() { Debug.Fail(""Class2 finalizer called!""); SomeMethod(); } void SomeMethod() { } } ", GetCA1821CSharpResultAt(7, 3)); } [WorkItem(820941, "DevDiv")] [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithNonInvocationBody() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { ~Class1() { Class2.SomeFlag = true; } } public class Class2 { public static bool SomeFlag; } "); } [Fact] public async Task CA1821BasicTestNoWarning() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Diagnostics Public Class Class1 ' No violation because the finalizer contains a method call Protected Overrides Sub Finalize() System.Console.Write("" "") End Sub End Class Public Class Class2 ' No violation because the finalizer's body is not empty. Protected Overrides Sub Finalize() Dim a = true End Sub End Class Public Class Class3 Dim a As Boolean = True ' No violation because the finalizer's body is not empty. Protected Overrides Sub Finalize() a = False End Sub End Class Public Class Class4 ' No violation because the finalizer's body is not empty. Protected Overrides Sub Finalize() Dim a = False Debug.Fail(""Finalizer called!"") End Sub End Class Public Class Class5 ' No violation because the finalizer's body is not empty. Protected Overrides Sub Finalize() If True Then Debug.Fail(""Finalizer called!"") End If End Sub End Class "); } [Fact] public async Task CA1821BasicTestRemoveEmptyFinalizers() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Diagnostics Public Class Class1 ' Violation occurs because the finalizer is empty. Protected Overrides Sub Finalize() End Sub End Class Public Class Class2 ' Violation occurs because the finalizer is empty. Protected Overrides Sub Finalize() ' Comments End Sub End Class Public Class Class3 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub Finalize() Debug.Fail(""Finalizer called!"") End Sub End Class ", GetCA1821BasicResultAt(6, 29), GetCA1821BasicResultAt(13, 29), GetCA1821BasicResultAt(20, 29)); } [Fact] public async Task CA1821BasicTestRemoveEmptyFinalizersWithScope() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Diagnostics Public Class Class1 ' Violation occurs because the finalizer is empty. Protected Overrides Sub [|Finalize|]() End Sub End Class Public Class Class2 ' Violation occurs because the finalizer is empty. Protected Overrides Sub [|Finalize|]() ' Comments End Sub End Class Public Class Class3 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub [|Finalize|]() Debug.Fail(""Finalizer called!"") End Sub End Class "); } [Fact] public async Task CA1821BasicTestRemoveEmptyFinalizersWithDebugFail() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Diagnostics Public Class Class1 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub Finalize() Debug.Fail(""Finalizer called!"") End Sub End Class Public Class Class2 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub Finalize() Dim a = False Debug.Fail(""Finalizer called!"") End Sub End Class ", GetCA1821BasicResultAt(6, 29)); } [Fact] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithThrowStatement() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { ~Class1() { throw new System.Exception(); } }", GetCA1821CSharpResultAt(4, 6)); } [Fact, WorkItem(1788, "https://github.com/dotnet/roslyn-analyzers/issues/1788")] public async Task CA1821CSharpTestRemoveEmptyFinalizersWithThrowExpression() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class1 { ~Class1() => throw new System.Exception(); }", GetCA1821CSharpResultAt(4, 6)); } [Fact] public async Task CA1821BasicTestRemoveEmptyFinalizersWithThrowStatement() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Class1 ' Violation occurs because Debug.Fail is a conditional method. Protected Overrides Sub Finalize() Throw New System.Exception() End Sub End Class ", GetCA1821BasicResultAt(4, 29)); } [Fact, WorkItem(1211, "https://github.com/dotnet/roslyn-analyzers/issues/1211")] public async Task CA1821CSharpRemoveEmptyFinalizersInvalidInvocationExpression() { await VerifyCS.VerifyAnalyzerAsync(@" public class C1 { ~C1() { {|CS0103:a|}{|CS1002:|} } } "); } [Fact, WorkItem(1788, "https://github.com/dotnet/roslyn-analyzers/issues/1788")] public async Task CA1821CSharpRemoveEmptyFinalizers_ErrorCodeWithBothBlockAndExpressionBody() { await VerifyCS.VerifyAnalyzerAsync(@" public class C1 { {|CS8057:~C1() { } => {|CS1525:;|}|} } "); } [Fact, WorkItem(1211, "https://github.com/dotnet/roslyn-analyzers/issues/1211")] public async Task CA1821BasicRemoveEmptyFinalizersInvalidInvocationExpression() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Class1 Protected Overrides Sub Finalize() {|BC30451:a|} End Sub End Class "); } [Fact, WorkItem(1788, "https://github.com/dotnet/roslyn-analyzers/issues/1788")] public async Task CA1821CSharpRemoveEmptyFinalizers_ExpressionBodiedImpl() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.IO; public class SomeTestClass : IDisposable { private readonly Stream resource = new MemoryStream(1024); public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool dispose) { if (dispose) { this.resource.Dispose(); } } ~SomeTestClass() => this.Dispose(false); }"); } private static DiagnosticResult GetCA1821CSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA1821BasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Core.Cache; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using umbraco.interfaces; namespace Umbraco.Core.Sync { /// <summary> /// An <see cref="IServerMessenger"/> that works by storing messages in the database. /// </summary> // // this messenger writes ALL instructions to the database, // but only processes instructions coming from remote servers, // thus ensuring that instructions run only once // public class DatabaseServerMessenger : ServerMessengerBase { private readonly ApplicationContext _appContext; private readonly DatabaseServerMessengerOptions _options; private readonly ManualResetEvent _syncIdle; private readonly object _locko = new object(); private readonly ILogger _logger; private int _lastId = -1; private DateTime _lastSync; private bool _initialized; private bool _syncing; private bool _released; private readonly ProfilingLogger _profilingLogger; protected ApplicationContext ApplicationContext { get { return _appContext; } } public DatabaseServerMessenger(ApplicationContext appContext, bool distributedEnabled, DatabaseServerMessengerOptions options) : base(distributedEnabled) { if (appContext == null) throw new ArgumentNullException("appContext"); if (options == null) throw new ArgumentNullException("options"); _appContext = appContext; _options = options; _lastSync = DateTime.UtcNow; _syncIdle = new ManualResetEvent(true); _profilingLogger = appContext.ProfilingLogger; _logger = appContext.ProfilingLogger.Logger; } #region Messenger protected override bool RequiresDistributed(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, MessageType dispatchType) { // we don't care if there's servers listed or not, // if distributed call is enabled we will make the call return _initialized && DistributedEnabled; } protected override void DeliverRemote( IEnumerable<IServerAddress> servers, ICacheRefresher refresher, MessageType messageType, IEnumerable<object> ids = null, string json = null) { var idsA = ids == null ? null : ids.ToArray(); Type idType; if (GetArrayType(idsA, out idType) == false) throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids"); var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json); var dto = new CacheInstructionDto { UtcStamp = DateTime.UtcNow, Instructions = JsonConvert.SerializeObject(instructions, Formatting.None), OriginIdentity = LocalIdentity }; ApplicationContext.DatabaseContext.Database.Insert(dto); } #endregion #region Sync /// <summary> /// Boots the messenger. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// Callers MUST ensure thread-safety. /// </remarks> protected void Boot() { // weight:10, must release *before* the facade service, because once released // the service will *not* be able to properly handle our notifications anymore const int weight = 10; var registered = ApplicationContext.MainDom.Register( () => { lock (_locko) { _released = true; // no more syncs } _syncIdle.WaitOne(); // wait for pending sync }, weight); if (registered == false) return; ReadLastSynced(); // get _lastId EnsureInstructions(); // reset _lastId if instrs are missing Initialize(); // boot } /// <summary> /// Initializes a server that has never synchronized before. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// Callers MUST ensure thread-safety. /// </remarks> private void Initialize() { lock (_locko) { if (_released) return; if (_lastId < 0) // never synced before { // we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new // server and it will need to rebuild it's own caches, eg Lucene or the xml cache file. _logger.Warn<DatabaseServerMessenger>("No last synced Id found, this generally means this is a new server/install. The server will rebuild its caches and indexes and then adjust it's last synced id to the latest found in the database and will start maintaining cache updates based on that id"); // go get the last id in the db and store it // note: do it BEFORE initializing otherwise some instructions might get lost // when doing it before, some instructions might run twice - not an issue var lastId = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction"); if (lastId > 0) SaveLastSynced(lastId); // execute initializing callbacks if (_options.InitializingCallbacks != null) foreach (var callback in _options.InitializingCallbacks) callback(); } _initialized = true; } } /// <summary> /// Synchronize the server (throttled). /// </summary> protected void Sync() { lock (_locko) { if (_syncing) return; if (_released) return; if ((DateTime.UtcNow - _lastSync).Seconds <= _options.ThrottleSeconds) return; _syncing = true; _syncIdle.Reset(); _lastSync = DateTime.UtcNow; } try { using (_profilingLogger.DebugDuration<DatabaseServerMessenger>("Syncing from database...")) { ProcessDatabaseInstructions(); switch (_appContext.GetCurrentServerRole()) { case ServerRole.Single: case ServerRole.Master: PruneOldInstructions(); break; } } } finally { _syncing = false; _syncIdle.Set(); } } /// <summary> /// Process instructions from the database. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> private void ProcessDatabaseInstructions() { // NOTE // we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that // would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests // (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are // pending requests after being processed, they'll just be processed on the next poll. // // FIXME not true if we're running on a background thread, assuming we can? var sql = new Sql().Select("*") .From<CacheInstructionDto>(_appContext.DatabaseContext.SqlSyntax) .Where<CacheInstructionDto>(dto => dto.Id > _lastId) .OrderBy<CacheInstructionDto>(dto => dto.Id, _appContext.DatabaseContext.SqlSyntax); var dtos = _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(sql); if (dtos.Count <= 0) return; // only process instructions coming from a remote server, and ignore instructions coming from // the local server as they've already been processed. We should NOT assume that the sequence of // instructions in the database makes any sense whatsoever, because it's all async. var localIdentity = LocalIdentity; var lastId = 0; foreach (var dto in dtos) { if (dto.OriginIdentity == localIdentity) { // just skip that local one but update lastId nevertheless lastId = dto.Id; continue; } // deserialize remote instructions & skip if it fails JArray jsonA; try { jsonA = JsonConvert.DeserializeObject<JArray>(dto.Instructions); } catch (JsonException ex) { _logger.Error<DatabaseServerMessenger>(string.Format("Failed to deserialize instructions ({0}: \"{1}\").", dto.Id, dto.Instructions), ex); lastId = dto.Id; // skip continue; } // execute remote instructions & update lastId try { NotifyRefreshers(jsonA); lastId = dto.Id; } catch (Exception ex) { _logger.Error<DatabaseServerMessenger>( string.Format("DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({0}: \"{1}\"). Instruction is being skipped/ignored", dto.Id, dto.Instructions), ex); //we cannot throw here because this invalid instruction will just keep getting processed over and over and errors // will be thrown over and over. The only thing we can do is ignore and move on. lastId = dto.Id; } } if (lastId > 0) SaveLastSynced(lastId); } /// <summary> /// Remove old instructions from the database. /// </summary> private void PruneOldInstructions() { _appContext.DatabaseContext.Database.Delete<CacheInstructionDto>("WHERE utcStamp < @pruneDate", new { pruneDate = DateTime.UtcNow.AddDays(-_options.DaysToRetainInstructions) }); } /// <summary> /// Ensure that the last instruction that was processed is still in the database. /// </summary> /// <remarks>If the last instruction is not in the database anymore, then the messenger /// should not try to process any instructions, because some instructions might be lost, /// and it should instead cold-boot.</remarks> private void EnsureInstructions() { var sql = new Sql().Select("*") .From<CacheInstructionDto>(_appContext.DatabaseContext.SqlSyntax) .Where<CacheInstructionDto>(dto => dto.Id == _lastId); var dtos = _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(sql); if (dtos.Count == 0) _lastId = -1; } /// <summary> /// Reads the last-synced id from file into memory. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> private void ReadLastSynced() { var path = SyncFilePath; if (File.Exists(path) == false) return; var content = File.ReadAllText(path); int last; if (int.TryParse(content, out last)) _lastId = last; } /// <summary> /// Updates the in-memory last-synced id and persists it to file. /// </summary> /// <param name="id">The id.</param> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> private void SaveLastSynced(int id) { File.WriteAllText(SyncFilePath, id.ToString(CultureInfo.InvariantCulture)); _lastId = id; } /// <summary> /// Gets the unique local identity of the executing AppDomain. /// </summary> /// <remarks> /// <para>It is not only about the "server" (machine name and appDomainappId), but also about /// an AppDomain, within a Process, on that server - because two AppDomains running at the same /// time on the same server (eg during a restart) are, practically, a LB setup.</para> /// <para>Practically, all we really need is the guid, the other infos are here for information /// and debugging purposes.</para> /// </remarks> protected readonly static string LocalIdentity = NetworkHelper.MachineName // eg DOMAIN\SERVER + "/" + HttpRuntime.AppDomainAppId // eg /LM/S3SVC/11/ROOT + " [P" + Process.GetCurrentProcess().Id // eg 1234 + "/D" + AppDomain.CurrentDomain.Id // eg 22 + "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique /// <summary> /// Gets the sync file path for the local server. /// </summary> /// <returns>The sync file path for the local server.</returns> private static string SyncFilePath { get { var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/DistCache/" + NetworkHelper.FileSafeMachineName); if (Directory.Exists(tempFolder) == false) Directory.CreateDirectory(tempFolder); return Path.Combine(tempFolder, HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt"); } } #endregion #region Notify refreshers private static ICacheRefresher GetRefresher(Guid id) { var refresher = CacheRefreshersResolver.Current.GetById(id); if (refresher == null) throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist."); return refresher; } private static IJsonCacheRefresher GetJsonRefresher(Guid id) { return GetJsonRefresher(GetRefresher(id)); } private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher) { var jsonRefresher = refresher as IJsonCacheRefresher; if (jsonRefresher == null) throw new InvalidOperationException("Cache refresher with ID \"" + refresher.UniqueIdentifier + "\" does not implement " + typeof(IJsonCacheRefresher) + "."); return jsonRefresher; } private static void NotifyRefreshers(IEnumerable<JToken> jsonArray) { foreach (var jsonItem in jsonArray) { // could be a JObject in which case we can convert to a RefreshInstruction, // otherwise it could be another JArray - in which case we'll iterate that. var jsonObj = jsonItem as JObject; if (jsonObj != null) { var instruction = jsonObj.ToObject<RefreshInstruction>(); switch (instruction.RefreshType) { case RefreshMethodType.RefreshAll: RefreshAll(instruction.RefresherId); break; case RefreshMethodType.RefreshByGuid: RefreshByGuid(instruction.RefresherId, instruction.GuidId); break; case RefreshMethodType.RefreshById: RefreshById(instruction.RefresherId, instruction.IntId); break; case RefreshMethodType.RefreshByIds: RefreshByIds(instruction.RefresherId, instruction.JsonIds); break; case RefreshMethodType.RefreshByJson: RefreshByJson(instruction.RefresherId, instruction.JsonPayload); break; case RefreshMethodType.RemoveById: RemoveById(instruction.RefresherId, instruction.IntId); break; } } else { var jsonInnerArray = (JArray) jsonItem; NotifyRefreshers(jsonInnerArray); // recurse } } } private static void RefreshAll(Guid uniqueIdentifier) { var refresher = GetRefresher(uniqueIdentifier); refresher.RefreshAll(); } private static void RefreshByGuid(Guid uniqueIdentifier, Guid id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Refresh(id); } private static void RefreshById(Guid uniqueIdentifier, int id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Refresh(id); } private static void RefreshByIds(Guid uniqueIdentifier, string jsonIds) { var refresher = GetRefresher(uniqueIdentifier); foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds)) refresher.Refresh(id); } private static void RefreshByJson(Guid uniqueIdentifier, string jsonPayload) { var refresher = GetJsonRefresher(uniqueIdentifier); refresher.Refresh(jsonPayload); } private static void RemoveById(Guid uniqueIdentifier, int id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Remove(id); } #endregion } }
using System; using System.Text; namespace ClosedXML.Excel { internal class XLStyle : IXLStyle { #region Static members public static XLStyle Default { get { return new XLStyle(XLStyleValue.Default); } } internal static XLStyleKey GenerateKey(IXLStyle initialStyle) { if (initialStyle == null) return Default.Key; if (initialStyle is XLStyle) return (initialStyle as XLStyle).Key; return new XLStyleKey { Font = XLFont.GenerateKey(initialStyle.Font), Alignment = XLAlignment.GenerateKey(initialStyle.Alignment), Border = XLBorder.GenerateKey(initialStyle.Border), Fill = XLFill.GenerateKey(initialStyle.Fill), NumberFormat = XLNumberFormat.GenerateKey(initialStyle.NumberFormat), Protection = XLProtection.GenerateKey(initialStyle.Protection) }; } internal static XLStyle CreateEmptyStyle() { return new XLStyle(new XLStylizedEmpty(null)); } #endregion Static members #region properties private readonly IXLStylized _container; internal XLStyleValue Value { get; private set; } internal XLStyleKey Key { get { return Value.Key; } private set { Value = XLStyleValue.FromKey(ref value); } } #endregion properties #region constructors public XLStyle(IXLStylized container, IXLStyle initialStyle = null, Boolean useDefaultModify = true) : this(container, GenerateKey(initialStyle)) { } public XLStyle(IXLStylized container, XLStyleKey key) : this(container, XLStyleValue.FromKey(ref key)) { } internal XLStyle(IXLStylized container, XLStyleValue value) { _container = container ?? new XLStylizedEmpty(XLStyle.Default); Value = value; } /// <summary> /// To initialize XLStyle.Default only /// </summary> private XLStyle(XLStyleValue value) { _container = null; Value = value; } #endregion constructors internal void Modify(Func<XLStyleKey, XLStyleKey> modification) { Key = modification(Key); if (_container != null) { _container.ModifyStyle(modification); } } #region IXLStyle members public IXLFont Font { get { return new XLFont(this, Value.Font); } set { Modify(k => { k.Font = XLFont.GenerateKey(value); return k; }); } } public IXLAlignment Alignment { get { return new XLAlignment(this, Value.Alignment); } set { Modify(k => { k.Alignment = XLAlignment.GenerateKey(value); return k; }); } } public IXLBorder Border { get { return new XLBorder(_container, this, Value.Border); } set { Modify(k => { k.Border = XLBorder.GenerateKey(value); return k; }); } } public IXLFill Fill { get { return new XLFill(this, Value.Fill); } set { Modify(k => { k.Fill = XLFill.GenerateKey(value); return k; }); } } public Boolean IncludeQuotePrefix { get { return Value.IncludeQuotePrefix; } set { Modify(k => { k.IncludeQuotePrefix = value; return k; }); } } public IXLStyle SetIncludeQuotePrefix(Boolean includeQuotePrefix = true) { IncludeQuotePrefix = includeQuotePrefix; return this; } public IXLNumberFormat NumberFormat { get { return new XLNumberFormat(this, Value.NumberFormat); } set { Modify(k => { k.NumberFormat = XLNumberFormat.GenerateKey(value); return k; }); } } public IXLProtection Protection { get { return new XLProtection(this, Value.Protection); } set { Modify(k => { k.Protection = XLProtection.GenerateKey(value); return k; }); } } public IXLNumberFormat DateFormat { get { return NumberFormat; } } #endregion IXLStyle members #region Overridden public override string ToString() { var sb = new StringBuilder(); sb.Append("Font:"); sb.Append(Font); sb.Append(" Fill:"); sb.Append(Fill); sb.Append(" Border:"); sb.Append(Border); sb.Append(" NumberFormat: "); sb.Append(NumberFormat); sb.Append(" Alignment: "); sb.Append(Alignment); sb.Append(" Protection: "); sb.Append(Protection); return sb.ToString(); } public bool Equals(IXLStyle other) { var otherS = other as XLStyle; if (otherS == null) return false; return Key == otherS.Key && _container == otherS._container; } public override bool Equals(object obj) { return Equals(obj as XLStyle); } public override int GetHashCode() { var hashCode = 416600561; hashCode = hashCode * -1521134295 + Key.GetHashCode(); return hashCode; } #endregion Overridden } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.CookiePolicy.Test { public class CookieConsentTests { [Fact] public async Task ConsentChecksOffByDefault() { var httpContext = await RunTestAsync(options => { }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.False(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.True(feature.CanTrack); context.Response.Cookies.Append("Test", "Value"); return Task.CompletedTask; }); Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie); } [Fact] public async Task ConsentEnabledForTemplateScenario() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Append("Test", "Value"); return Task.CompletedTask; }); Assert.Empty(httpContext.Response.Headers.SetCookie); } [Fact] public async Task NonEssentialCookiesWithOptionsExcluded() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Append("Test", "Value", new CookieOptions() { IsEssential = false }); return Task.CompletedTask; }); Assert.Empty(httpContext.Response.Headers.SetCookie); } [Fact] public async Task NonEssentialCookiesCanBeAllowedViaOnAppendCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; options.OnAppendCookie = context => { Assert.True(context.IsConsentNeeded); Assert.False(context.HasConsent); Assert.False(context.IssueCookie); context.IssueCookie = true; }; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Append("Test", "Value", new CookieOptions() { IsEssential = false }); return Task.CompletedTask; }); Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie); } [Fact] public async Task NeedsConsentDoesNotPreventEssentialCookies() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Append("Test", "Value", new CookieOptions() { IsEssential = true }); return Task.CompletedTask; }); Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie); } [Fact] public async Task EssentialCookiesCanBeExcludedByOnAppendCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; options.OnAppendCookie = context => { Assert.True(context.IsConsentNeeded); Assert.True(context.HasConsent); Assert.True(context.IssueCookie); context.IssueCookie = false; }; }, requestContext => { requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes"; }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); context.Response.Cookies.Append("Test", "Value", new CookieOptions() { IsEssential = true }); return Task.CompletedTask; }); Assert.Empty(httpContext.Response.Headers.SetCookie); } [Fact] public async Task HasConsentReadsRequestCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes"; }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); context.Response.Cookies.Append("Test", "Value"); return Task.CompletedTask; }); Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie); } [Fact] public async Task HasConsentIgnoresInvalidRequestCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { requestContext.Request.Headers.Cookie = ".AspNet.Consent=IAmATeapot"; }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Append("Test", "Value"); return Task.CompletedTask; }); Assert.Empty(httpContext.Response.Headers.SetCookie); } [Fact] public async Task GrantConsentSetsCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); feature.GrantConsent(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); context.Response.Cookies.Append("Test", "Value"); return Task.CompletedTask; }); var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie); Assert.Equal(2, cookies.Count); var consentCookie = cookies[0]; Assert.Equal(".AspNet.Consent", consentCookie.Name); Assert.Equal("yes", consentCookie.Value); Assert.True(consentCookie.Expires.HasValue); Assert.True(consentCookie.Expires.Value > DateTimeOffset.Now + TimeSpan.FromDays(364)); Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, consentCookie.SameSite); Assert.NotNull(consentCookie.Expires); var testCookie = cookies[1]; Assert.Equal("Test", testCookie.Name); Assert.Equal("Value", testCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, testCookie.SameSite); Assert.Null(testCookie.Expires); } [Fact] public async Task GrantConsentAppliesPolicyToConsentCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = Http.SameSiteMode.Strict; options.OnAppendCookie = context => { Assert.Equal(".AspNet.Consent", context.CookieName); Assert.Equal("yes", context.CookieValue); Assert.Equal(Http.SameSiteMode.Strict, context.CookieOptions.SameSite); context.CookieName += "1"; context.CookieValue += "1"; }; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); feature.GrantConsent(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); return Task.CompletedTask; }); var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie); Assert.Equal(1, cookies.Count); var consentCookie = cookies[0]; Assert.Equal(".AspNet.Consent1", consentCookie.Name); Assert.Equal("yes1", consentCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.Strict, consentCookie.SameSite); Assert.NotNull(consentCookie.Expires); } [Fact] public async Task GrantConsentWhenAlreadyHasItDoesNotSetCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes"; }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); feature.GrantConsent(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); context.Response.Cookies.Append("Test", "Value"); return Task.CompletedTask; }); Assert.Equal("Test=Value; path=/", httpContext.Response.Headers.SetCookie); } [Fact] public async Task GrantConsentAfterResponseStartsSetsHasConsentButDoesNotSetCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { }, async context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); await context.Response.WriteAsync("Started."); feature.GrantConsent(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); Assert.Throws<InvalidOperationException>(() => context.Response.Cookies.Append("Test", "Value")); await context.Response.WriteAsync("Granted."); }); var reader = new StreamReader(httpContext.Response.Body); Assert.Equal("Started.Granted.", await reader.ReadToEndAsync()); Assert.Empty(httpContext.Response.Headers.SetCookie); } [Fact] public async Task WithdrawConsentWhenNotHasConsentNoOps() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); feature.WithdrawConsent(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Append("Test", "Value"); return Task.CompletedTask; }); Assert.Empty(httpContext.Response.Headers.SetCookie); } [Fact] public async Task WithdrawConsentDeletesCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes"; }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); context.Response.Cookies.Append("Test", "Value1"); feature.WithdrawConsent(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Append("Test", "Value2"); return Task.CompletedTask; }); var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie); Assert.Equal(2, cookies.Count); var testCookie = cookies[0]; Assert.Equal("Test", testCookie.Name); Assert.Equal("Value1", testCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, testCookie.SameSite); Assert.Null(testCookie.Expires); var consentCookie = cookies[1]; Assert.Equal(".AspNet.Consent", consentCookie.Name); Assert.Equal("", consentCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, consentCookie.SameSite); Assert.NotNull(consentCookie.Expires); } [Fact] public async Task WithdrawConsentAppliesPolicyToDeleteCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = Http.SameSiteMode.Strict; options.OnDeleteCookie = context => { Assert.Equal(".AspNet.Consent", context.CookieName); context.CookieName += "1"; }; }, requestContext => { requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes"; }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); feature.WithdrawConsent(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); return Task.CompletedTask; }); var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie); Assert.Equal(1, cookies.Count); var consentCookie = cookies[0]; Assert.Equal(".AspNet.Consent1", consentCookie.Name); Assert.Equal("", consentCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.Strict, consentCookie.SameSite); Assert.NotNull(consentCookie.Expires); } [Fact] public async Task WithdrawConsentAfterResponseHasStartedDoesNotDeleteCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { requestContext.Request.Headers.Cookie = ".AspNet.Consent=yes"; }, async context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); context.Response.Cookies.Append("Test", "Value1"); await context.Response.WriteAsync("Started."); feature.WithdrawConsent(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); // Doesn't throw the normal InvalidOperationException because the cookie is never written context.Response.Cookies.Append("Test", "Value2"); await context.Response.WriteAsync("Withdrawn."); }); var reader = new StreamReader(httpContext.Response.Body); Assert.Equal("Started.Withdrawn.", await reader.ReadToEndAsync()); Assert.Equal("Test=Value1; path=/", httpContext.Response.Headers.SetCookie); } [Fact] public async Task DeleteCookieDoesNotRequireConsent() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Delete("Test"); return Task.CompletedTask; }); var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie); Assert.Equal(1, cookies.Count); var testCookie = cookies[0]; Assert.Equal("Test", testCookie.Name); Assert.Equal("", testCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, testCookie.SameSite); Assert.NotNull(testCookie.Expires); } [Fact] public async Task OnDeleteCookieCanSuppressCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; options.OnDeleteCookie = context => { Assert.True(context.IsConsentNeeded); Assert.False(context.HasConsent); Assert.True(context.IssueCookie); context.IssueCookie = false; }; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); context.Response.Cookies.Delete("Test"); return Task.CompletedTask; }); Assert.Empty(httpContext.Response.Headers.SetCookie); } [Fact] public async Task CreateConsentCookieMatchesGrantConsentCookie() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); feature.GrantConsent(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); var cookie = feature.CreateConsentCookie(); context.Response.Headers["ManualCookie"] = cookie; return Task.CompletedTask; }); var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie); Assert.Equal(1, cookies.Count); var consentCookie = cookies[0]; Assert.Equal(".AspNet.Consent", consentCookie.Name); Assert.Equal("yes", consentCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, consentCookie.SameSite); Assert.NotNull(consentCookie.Expires); cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers["ManualCookie"]); Assert.Equal(1, cookies.Count); var manualCookie = cookies[0]; Assert.Equal(consentCookie.Name, manualCookie.Name); Assert.Equal(consentCookie.Value, manualCookie.Value); Assert.Equal(consentCookie.SameSite, manualCookie.SameSite); Assert.NotNull(manualCookie.Expires); // Expires may not exactly match to the second. } [Fact] public async Task CreateConsentCookieAppliesPolicy() { var httpContext = await RunTestAsync(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = Http.SameSiteMode.Strict; options.OnAppendCookie = context => { Assert.Equal(".AspNet.Consent", context.CookieName); Assert.Equal("yes", context.CookieValue); Assert.Equal(Http.SameSiteMode.Strict, context.CookieOptions.SameSite); context.CookieName += "1"; context.CookieValue += "1"; }; }, requestContext => { }, context => { var feature = context.Features.Get<ITrackingConsentFeature>(); Assert.True(feature.IsConsentNeeded); Assert.False(feature.HasConsent); Assert.False(feature.CanTrack); feature.GrantConsent(); Assert.True(feature.IsConsentNeeded); Assert.True(feature.HasConsent); Assert.True(feature.CanTrack); var cookie = feature.CreateConsentCookie(); context.Response.Headers["ManualCookie"] = cookie; return Task.CompletedTask; }); var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie); Assert.Equal(1, cookies.Count); var consentCookie = cookies[0]; Assert.Equal(".AspNet.Consent1", consentCookie.Name); Assert.Equal("yes1", consentCookie.Value); Assert.Equal(Net.Http.Headers.SameSiteMode.Strict, consentCookie.SameSite); Assert.NotNull(consentCookie.Expires); cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers["ManualCookie"]); Assert.Equal(1, cookies.Count); var manualCookie = cookies[0]; Assert.Equal(consentCookie.Name, manualCookie.Name); Assert.Equal(consentCookie.Value, manualCookie.Value); Assert.Equal(consentCookie.SameSite, manualCookie.SameSite); Assert.NotNull(manualCookie.Expires); // Expires may not exactly match to the second. } private async Task<HttpContext> RunTestAsync(Action<CookiePolicyOptions> configureOptions, Action<HttpContext> configureRequest, RequestDelegate handleRequest) { var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .Configure(app => { app.UseCookiePolicy(); app.Run(handleRequest); }) .UseTestServer(); }) .ConfigureServices(services => { services.Configure(configureOptions); }) .Build(); var server = host.GetTestServer(); await host.StartAsync(); return await server.SendAsync(configureRequest); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class FullNameTests : CSharpResultProviderTestBase { [Fact] public void Null() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("null", fullNameProvider.GetClrExpressionForNull(inspectionContext)); } [Fact] public void This() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("this", fullNameProvider.GetClrExpressionForThis(inspectionContext)); } [Fact] public void ArrayIndex() { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); Assert.Equal("[]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new string[0])); Assert.Equal("[]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "" })); Assert.Equal("[ ]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { " " })); Assert.Equal("[1]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "1" })); Assert.Equal("[[], 2, 3]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "[]", "2", "3" })); Assert.Equal("[, , ]", fullNameProvider.GetClrArrayIndexExpression(inspectionContext, new[] { "", "", "" })); } [Fact] public void Cast() { var source = @"class C { }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); var type = runtime.GetType("C"); Assert.Equal("(C)o", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.None)); Assert.Equal("o as C", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("(C)(o)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeArgument)); Assert.Equal("(o) as C", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeArgument | DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("((C)o)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression)); Assert.Equal("(o as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("((C)(o))", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ParenthesizeArgument)); Assert.Equal("((o) as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ParenthesizeArgument | DkmClrCastExpressionOptions.ConditionalCast)); // Some of the same tests with "..." as the expression ("..." is used // by the debugger when the expression cannot be determined). Assert.Equal("(C)...", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.None)); Assert.Equal("... as C", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.ConditionalCast)); Assert.Equal("(... as C)", fullNameProvider.GetClrCastExpression(inspectionContext, "...", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ConditionalCast)); } } [Fact] public void RootComment() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a // Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult(" a // Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a// Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a /*b*/ +c /*d*/// Comment", value); Assert.Equal("(a +c).F", GetChildren(root).Single().FullName); root = FormatResult("a /*//*/+ c// Comment", value); Assert.Equal("(a + c).F", GetChildren(root).Single().FullName); root = FormatResult("a /*/**/+ c// Comment", value); Assert.Equal("(a + c).F", GetChildren(root).Single().FullName); root = FormatResult("/**/a// Comment", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); } [Fact] public void RootFormatSpecifiers() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a, raw", value); // simple Assert.Equal("a, raw", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a, raw, ac, h", value); // multiple specifiers Assert.Equal("a, raw, ac, h", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("M(a, b), raw", value); // non-specifier comma Assert.Equal("M(a, b), raw", root.FullName); Assert.Equal("M(a, b).F", GetChildren(root).Single().FullName); root = FormatResult("a, raw1", value); // alpha-numeric Assert.Equal("a, raw1", root.FullName); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a, $raw", value); // other punctuation Assert.Equal("a, $raw", root.FullName); Assert.Equal("(a, $raw).F", GetChildren(root).Single().FullName); // not ideal } [Fact] public void RootParentheses() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a + b", value); Assert.Equal("(a + b).F", GetChildren(root).Single().FullName); // required root = FormatResult("new C()", value); Assert.Equal("(new C()).F", GetChildren(root).Single().FullName); // documentation root = FormatResult("A.B", value); Assert.Equal("A.B.F", GetChildren(root).Single().FullName); // desirable root = FormatResult("A::B", value); Assert.Equal("(A::B).F", GetChildren(root).Single().FullName); // documentation } [Fact] public void RootTrailingSemicolons() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); var root = FormatResult("a;", value); Assert.Equal("a.F", GetChildren(root).Single().FullName); root = FormatResult("a + b;;", value); Assert.Equal("(a + b).F", GetChildren(root).Single().FullName); root = FormatResult(" M( ) ; ;", value); Assert.Equal("M( ).F", GetChildren(root).Single().FullName); } [Fact] public void RootMixedExtras() { var source = @" class C { public int F; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate()); // Semicolon, then comment. var root = FormatResult("a; //", value); Assert.Equal("a", root.FullName); // Comment, then semicolon. root = FormatResult("a // ;", value); Assert.Equal("a", root.FullName); // Semicolon, then format specifier. root = FormatResult("a;, ac", value); Assert.Equal("a, ac", root.FullName); // Format specifier, then semicolon. root = FormatResult("a, ac;", value); Assert.Equal("a, ac", root.FullName); // Comment, then format specifier. root = FormatResult("a//, ac", value); Assert.Equal("a", root.FullName); // Format specifier, then comment. root = FormatResult("a, ac //", value); Assert.Equal("a, ac", root.FullName); // Everything. root = FormatResult("/*A*/ a /*B*/ + /*C*/ b /*D*/ ; ; , ac /*E*/, raw // ;, hidden", value); Assert.Equal("a + b, ac, raw", root.FullName); } [Fact, WorkItem(1022165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022165")] public void Keywords_Root() { var source = @" class C { void M() { int @namespace = 3; } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(3); var root = FormatResult("@namespace", value); Verify(root, EvalResult("@namespace", "3", "int", "@namespace")); value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); root = FormatResult("this", value); Verify(root, EvalResult("this", "{C}", "C", "this")); // Verify that keywords aren't escaped by the ResultProvider at the // root level (we would never expect to see "namespace" passed as a // resultName, but this check verifies that we leave them "as is"). root = FormatResult("namespace", CreateDkmClrValue(new object())); Verify(root, EvalResult("namespace", "{object}", "object", "namespace")); } [Fact] public void Keywords_RuntimeType() { var source = @" public class @struct { } public class @namespace : @struct { @struct m = new @if(); } public class @if : @struct { } "; var assembly = GetAssembly(source); var type = assembly.GetType("namespace"); var declaredType = assembly.GetType("struct"); var value = CreateDkmClrValue(type.Instantiate(), type); var root = FormatResult("o", value, new DkmClrType((TypeImpl)declaredType)); Verify(GetChildren(root), EvalResult("m", "{if}", "struct {if}", "((@namespace)o).m", DkmEvaluationResultFlags.None)); } [Fact] public void Keywords_ProxyType() { var source = @" using System.Diagnostics; [DebuggerTypeProxy(typeof(@class))] public class @struct { public bool @true = false; } public class @class { public bool @false = true; public @class(@struct s) { } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("@false", "true", "bool", "new @class(o).@false", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var grandChildren = GetChildren(children.Last()); Verify(grandChildren, EvalResult("@true", "false", "bool", "o.@true", DkmEvaluationResultFlags.Boolean)); } [Fact] public void Keywords_MemberAccess() { var source = @" public class @struct { public int @true; } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); Verify(GetChildren(root), EvalResult("@true", "0", "int", "o.@true")); } [Fact] public void Keywords_StaticMembers() { var source = @" public class @struct { public static int @true; } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "@struct", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("@true", "0", "int", "@struct.@true", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public)); } [Fact] public void Keywords_ExplicitInterfaceImplementation() { var source = @" namespace @namespace { public interface @interface<T> { int @return { get; set; } } public class @class : @interface<@class> { int @interface<@class>.@return { get; set; } } } "; var assembly = GetAssembly(source); var value = CreateDkmClrValue(assembly.GetType("namespace.class").Instantiate()); var root = FormatResult("instance", value); Verify(GetChildren(root), EvalResult("@namespace.@interface<@namespace.@class>.@return", "0", "int", "((@namespace.@interface<@namespace.@class>)instance).@return")); } [Fact] public void MangledNames_CastRequired() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled' { .field public int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void '<>Mangled'::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); var root = FormatResult("o", value); Verify(GetChildren(root), EvalResult("x (<>Mangled)", "0", "int", null), EvalResult("x", "0", "int", "o.x")); } [Fact] public void MangledNames_StaticMembers() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public static int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled' { .field public static int32 y .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void '<>Mangled'::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled").Instantiate()); var root = FormatResult("o", baseValue); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); var derivedValue = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); root = FormatResult("o", derivedValue); children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "NotMangled", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null, DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public), EvalResult("y", "0", "int", "NotMangled.y", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public)); } [Fact] public void MangledNames_ExplicitInterfaceImplementation() { var il = @" .class interface public abstract auto ansi 'abstract.I<>Mangled' { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .property instance int32 P() { .get instance int32 'abstract.I<>Mangled'::get_P() } } // end of class 'abstract.I<>Mangled' .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements 'abstract.I<>Mangled' { .method private hidebysig newslot specialname virtual final instance int32 'abstract.I<>Mangled.get_P'() cil managed { .override 'abstract.I<>Mangled'::get_P ldc.i4.1 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 'abstract.I<>Mangled.P'() { .get instance int32 C::'abstract.I<>Mangled.get_P'() } .property instance int32 P() { .get instance int32 C::'abstract.I<>Mangled.get_P'() } } // end of class C "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); var root = FormatResult("instance", value); Verify(GetChildren(root), EvalResult("P", "1", "int", "instance.P", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private), EvalResult("abstract.I<>Mangled.P", "1", "int", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private)); } [Fact] public void MangledNames_ArrayElement() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit NotMangled extends [mscorlib]System.Object { .field public class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> 'array' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 ldc.i4.1 newarr '<>Mangled' stfld class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> NotMangled::'array' ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("array", "{<>Mangled[1]}", "System.Collections.Generic.IEnumerable<<>Mangled> {<>Mangled[]}", "o.array", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children.Single()), EvalResult("[0]", "null", "<>Mangled", null)); } [Fact] public void MangledNames_Namespace() { var il = @" .class public auto ansi beforefieldinit '<>Mangled.C' extends [mscorlib]System.Object { .field public static int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled.C").Instantiate()); var root = FormatResult("o", baseValue); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); } [Fact] public void MangledNames_PointerDereference() { var il = @" .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field private static int32* p .method assembly hidebysig specialname rtspecialname instance void .ctor(int64 arg) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0008: ldarg.1 IL_0009: conv.u IL_000a: stsfld int32* '<>Mangled'::p IL_0010: ret } } // end of class '<>Mangled' "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); unsafe { int i = 4; long p = (long)&i; var type = assembly.GetType("<>Mangled"); var rootExpr = "m"; var value = CreateDkmClrValue(type.Instantiate(p)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{<>Mangled}", "<>Mangled", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children.Single()); Verify(children, EvalResult("p", PointerToString(new IntPtr(p)), "int*", null, DkmEvaluationResultFlags.Expandable)); children = GetChildren(children.Single()); Verify(children, EvalResult("*p", "4", "int", null)); } } [Fact] public void MangledNames_DebuggerTypeProxy() { var il = @" .class public auto ansi beforefieldinit Type extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = {type('<>Mangled')} .field public bool x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 ldc.i4.0 stfld bool Type::x ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } // end of method Type::.ctor } // end of class Type .class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object { .field public bool y .method public hidebysig specialname rtspecialname instance void .ctor(class Type s) cil managed { ldarg.0 ldc.i4.1 stfld bool '<>Mangled'::y ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } // end of method '<>Mangled'::.ctor } // end of class '<>Mangled' "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("Type").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("y", "true", "bool", null, DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var grandChildren = GetChildren(children.Last()); Verify(grandChildren, EvalResult("x", "false", "bool", "o.x", DkmEvaluationResultFlags.Boolean)); } [Fact] public void GenericTypeWithoutBacktick() { var il = @" .class public auto ansi beforefieldinit C<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", "C<int>.x")); } [Fact] public void BackTick_NonGenericType() { var il = @" .class public auto ansi beforefieldinit 'C`1' extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C`1").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", null)); } [Fact] public void BackTick_GenericType() { var il = @" .class public auto ansi beforefieldinit 'C`1'<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C`1").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", "C<int>.x")); } [Fact] public void BackTick_Member() { // IL doesn't support using generic methods as property accessors so // there's no way to test a "legitimate" backtick in a member name. var il = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .field public static int32 'x`1' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("C").Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x`1", "0", "int", fullName: null)); } [Fact] public void BackTick_FirstCharacter() { var il = @" .class public auto ansi beforefieldinit '`1'<T> extends [mscorlib]System.Object { .field public static int32 'x' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var value = CreateDkmClrValue(assembly.GetType("`1").MakeGenericType(typeof(int)).Instantiate()); var root = FormatResult("o", value); var children = GetChildren(root); Verify(children, EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); Verify(GetChildren(children.Single()), EvalResult("x", "0", "int", fullName: null)); } } }
// MIT License - Copyright (C) The Mono.Xna Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.Diagnostics; using System.Text; using System.Runtime.Serialization; namespace TriangleDemo { /// <summary> /// Describes a 3D-vector. /// </summary> [DataContract] [DebuggerDisplay("{DebugDisplayString,nq}")] public struct Vector3 : IEquatable<Vector3> { #region Private Fields private static readonly Vector3 mZero = new Vector3(0f, 0f, 0f); private static readonly Vector3 mOne = new Vector3(1f, 1f, 1f); private static readonly Vector3 mUnitX = new Vector3(1f, 0f, 0f); private static readonly Vector3 mUnitY = new Vector3(0f, 1f, 0f); private static readonly Vector3 mUnitZ = new Vector3(0f, 0f, 1f); private static readonly Vector3 mUp = new Vector3(0f, 1f, 0f); private static readonly Vector3 mDown = new Vector3(0f, -1f, 0f); private static readonly Vector3 mRight = new Vector3(1f, 0f, 0f); private static readonly Vector3 mLeft = new Vector3(-1f, 0f, 0f); private static readonly Vector3 mForward = new Vector3(0f, 0f, -1f); private static readonly Vector3 mBackward = new Vector3(0f, 0f, 1f); #endregion #region Public Fields /// <summary> /// The x coordinate of this <see cref="Vector3"/>. /// </summary> [DataMember] public float X; /// <summary> /// The y coordinate of this <see cref="Vector3"/>. /// </summary> [DataMember] public float Y; /// <summary> /// The z coordinate of this <see cref="Vector3"/>. /// </summary> [DataMember] public float Z; #endregion #region Public Properties /// <summary> /// Returns a <see cref="Vector3"/> with components 0, 0, 0. /// </summary> public static Vector3 Zero { get { return mZero; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 1, 1, 1. /// </summary> public static Vector3 One { get { return mOne; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 1, 0, 0. /// </summary> public static Vector3 UnitX { get { return mUnitX; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 0, 1, 0. /// </summary> public static Vector3 UnitY { get { return mUnitY; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 0, 0, 1. /// </summary> public static Vector3 UnitZ { get { return mUnitZ; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 0, 1, 0. /// </summary> public static Vector3 Up { get { return mUp; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 0, -1, 0. /// </summary> public static Vector3 Down { get { return mDown; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 1, 0, 0. /// </summary> public static Vector3 Right { get { return mRight; } } /// <summary> /// Returns a <see cref="Vector3"/> with components -1, 0, 0. /// </summary> public static Vector3 Left { get { return mLeft; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 0, 0, -1. /// </summary> public static Vector3 Forward { get { return mForward; } } /// <summary> /// Returns a <see cref="Vector3"/> with components 0, 0, 1. /// </summary> public static Vector3 Backward { get { return mBackward; } } #endregion #region Internal Properties internal string DebugDisplayString { get { return string.Concat( this.X.ToString(), " ", this.Y.ToString(), " ", this.Z.ToString() ); } } #endregion #region Constructors /// <summary> /// Constructs a 3d vector with X, Y and Z from three values. /// </summary> /// <param name="x">The x coordinate in 3d-space.</param> /// <param name="y">The y coordinate in 3d-space.</param> /// <param name="z">The z coordinate in 3d-space.</param> public Vector3(float x, float y, float z) { this.X = x; this.Y = y; this.Z = z; } /// <summary> /// Constructs a 3d vector with X, Y and Z set to the same value. /// </summary> /// <param name="value">The x, y and z coordinates in 3d-space.</param> public Vector3(float value) { this.X = value; this.Y = value; this.Z = value; } #endregion #region Public Methods /// <summary> /// Performs vector addition on <paramref name="value1"/> and <paramref name="value2"/>. /// </summary> /// <param name="value1">The first vector to add.</param> /// <param name="value2">The second vector to add.</param> /// <returns>The result of the vector addition.</returns> public static Vector3 Add(Vector3 value1, Vector3 value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } /// <summary> /// Performs vector addition on <paramref name="value1"/> and /// <paramref name="value2"/>, storing the result of the /// addition in <paramref name="result"/>. /// </summary> /// <param name="value1">The first vector to add.</param> /// <param name="value2">The second vector to add.</param> /// <param name="result">The result of the vector addition.</param> public static void Add(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; result.Z = value1.Z + value2.Z; } /// <summary> /// Computes the cross product of two vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The cross product of two vectors.</returns> public static Vector3 Cross(Vector3 vector1, Vector3 vector2) { Cross(ref vector1, ref vector2, out vector1); return vector1; } /// <summary> /// Computes the cross product of two vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <param name="result">The cross product of two vectors as an output parameter.</param> public static void Cross(ref Vector3 vector1, ref Vector3 vector2, out Vector3 result) { var x = vector1.Y * vector2.Z - vector2.Y * vector1.Z; var y = -(vector1.X * vector2.Z - vector2.X * vector1.Z); var z = vector1.X * vector2.Y - vector2.X * vector1.Y; result.X = x; result.Y = y; result.Z = z; } /// <summary> /// Returns the distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The distance between two vectors.</returns> public static float Distance(Vector3 value1, Vector3 value2) { float result; DistanceSquared(ref value1, ref value2, out result); return (float)Math.Sqrt(result); } /// <summary> /// Returns the distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="result">The distance between two vectors as an output parameter.</param> public static void Distance(ref Vector3 value1, ref Vector3 value2, out float result) { DistanceSquared(ref value1, ref value2, out result); result = (float)Math.Sqrt(result); } /// <summary> /// Returns the squared distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The squared distance between two vectors.</returns> public static float DistanceSquared(Vector3 value1, Vector3 value2) { return (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } /// <summary> /// Returns the squared distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="result">The squared distance between two vectors as an output parameter.</param> public static void DistanceSquared(ref Vector3 value1, ref Vector3 value2, out float result) { result = (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } /// <summary> /// Divides the components of a <see cref="Vector3"/> by the components of another <see cref="Vector3"/>. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="value2">Divisor <see cref="Vector3"/>.</param> /// <returns>The result of dividing the vectors.</returns> public static Vector3 Divide(Vector3 value1, Vector3 value2) { value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } /// <summary> /// Divides the components of a <see cref="Vector3"/> by a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="divider">Divisor scalar.</param> /// <returns>The result of dividing a vector by a scalar.</returns> public static Vector3 Divide(Vector3 value1, float divider) { float factor = 1 / divider; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } /// <summary> /// Divides the components of a <see cref="Vector3"/> by a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="divider">Divisor scalar.</param> /// <param name="result">The result of dividing a vector by a scalar as an output parameter.</param> public static void Divide(ref Vector3 value1, float divider, out Vector3 result) { float factor = 1 / divider; result.X = value1.X * factor; result.Y = value1.Y * factor; result.Z = value1.Z * factor; } /// <summary> /// Divides the components of a <see cref="Vector3"/> by the components of another <see cref="Vector3"/>. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="value2">Divisor <see cref="Vector3"/>.</param> /// <param name="result">The result of dividing the vectors as an output parameter.</param> public static void Divide(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result.X = value1.X / value2.X; result.Y = value1.Y / value2.Y; result.Z = value1.Z / value2.Z; } /// <summary> /// Returns a dot product of two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The dot product of two vectors.</returns> public static float Dot(Vector3 value1, Vector3 value2) { return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z; } /// <summary> /// Returns a dot product of two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="result">The dot product of two vectors as an output parameter.</param> public static void Dot(ref Vector3 value1, ref Vector3 value2, out float result) { result = value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z; } /// <summary> /// Compares whether current instance is equal to specified <see cref="Object"/>. /// </summary> /// <param name="obj">The <see cref="Object"/> to compare.</param> /// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector3)) return false; var other = (Vector3)obj; return X == other.X && Y == other.Y && Z == other.Z; } /// <summary> /// Compares whether current instance is equal to specified <see cref="Vector3"/>. /// </summary> /// <param name="other">The <see cref="Vector3"/> to compare.</param> /// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns> public bool Equals(Vector3 other) { return X == other.X && Y == other.Y && Z == other.Z; } /// <summary> /// Gets the hash code of this <see cref="Vector3"/>. /// </summary> /// <returns>Hash code of this <see cref="Vector3"/>.</returns> public override int GetHashCode() { return (int)(this.X + this.Y + this.Z); } /// <summary> /// Returns the length of this <see cref="Vector3"/>. /// </summary> /// <returns>The length of this <see cref="Vector3"/>.</returns> public float Length() { float result = DistanceSquared(this, mZero); return (float)Math.Sqrt(result); } /// <summary> /// Returns the squared length of this <see cref="Vector3"/>. /// </summary> /// <returns>The squared length of this <see cref="Vector3"/>.</returns> public float LengthSquared() { return DistanceSquared(this, mZero); } /// <summary> /// Creates a new <see cref="Vector3"/> that contains a multiplication of two vectors. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="value2">Source <see cref="Vector3"/>.</param> /// <returns>The result of the vector multiplication.</returns> public static Vector3 Multiply(Vector3 value1, Vector3 value2) { value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains a multiplication of <see cref="Vector3"/> and a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="scaleFactor">Scalar value.</param> /// <returns>The result of the vector multiplication with a scalar.</returns> public static Vector3 Multiply(Vector3 value1, float scaleFactor) { value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains a multiplication of <see cref="Vector3"/> and a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="scaleFactor">Scalar value.</param> /// <param name="result">The result of the multiplication with a scalar as an output parameter.</param> public static void Multiply(ref Vector3 value1, float scaleFactor, out Vector3 result) { result.X = value1.X * scaleFactor; result.Y = value1.Y * scaleFactor; result.Z = value1.Z * scaleFactor; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains a multiplication of two vectors. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="value2">Source <see cref="Vector3"/>.</param> /// <param name="result">The result of the vector multiplication as an output parameter.</param> public static void Multiply(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result.X = value1.X * value2.X; result.Y = value1.Y * value2.Y; result.Z = value1.Z * value2.Z; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains the specified vector inversion. /// </summary> /// <param name="value">Source <see cref="Vector3"/>.</param> /// <returns>The result of the vector inversion.</returns> public static Vector3 Negate(Vector3 value) { value = new Vector3(-value.X, -value.Y, -value.Z); return value; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains the specified vector inversion. /// </summary> /// <param name="value">Source <see cref="Vector3"/>.</param> /// <param name="result">The result of the vector inversion as an output parameter.</param> public static void Negate(ref Vector3 value, out Vector3 result) { result.X = -value.X; result.Y = -value.Y; result.Z = -value.Z; } /// <summary> /// Turns this <see cref="Vector3"/> to a unit vector with the same direction. /// </summary> public void Normalize() { Normalize(ref this, out this); } /// <summary> /// Creates a new <see cref="Vector3"/> that contains a normalized values from another vector. /// </summary> /// <param name="value">Source <see cref="Vector3"/>.</param> /// <returns>Unit vector.</returns> public static Vector3 Normalize(Vector3 value) { float factor = Distance(value, mZero); factor = 1f / factor; return new Vector3(value.X * factor, value.Y * factor, value.Z * factor); } /// <summary> /// Creates a new <see cref="Vector3"/> that contains a normalized values from another vector. /// </summary> /// <param name="value">Source <see cref="Vector3"/>.</param> /// <param name="result">Unit vector as an output parameter.</param> public static void Normalize(ref Vector3 value, out Vector3 result) { float factor = Distance(value, mZero); factor = 1f / factor; result.X = value.X * factor; result.Y = value.Y * factor; result.Z = value.Z * factor; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains reflect vector of the given vector and normal. /// </summary> /// <param name="vector">Source <see cref="Vector3"/>.</param> /// <param name="normal">Reflection normal.</param> /// <returns>Reflected vector.</returns> public static Vector3 Reflect(Vector3 vector, Vector3 normal) { // I is the original array // N is the normal of the incident plane // R = I - (2 * N * ( DotProduct[ I,N] )) Vector3 reflectedVector; // inline the dotProduct here instead of calling method float dotProduct = ((vector.X * normal.X) + (vector.Y * normal.Y)) + (vector.Z * normal.Z); reflectedVector.X = vector.X - (2.0f * normal.X) * dotProduct; reflectedVector.Y = vector.Y - (2.0f * normal.Y) * dotProduct; reflectedVector.Z = vector.Z - (2.0f * normal.Z) * dotProduct; return reflectedVector; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains reflect vector of the given vector and normal. /// </summary> /// <param name="vector">Source <see cref="Vector3"/>.</param> /// <param name="normal">Reflection normal.</param> /// <param name="result">Reflected vector as an output parameter.</param> public static void Reflect(ref Vector3 vector, ref Vector3 normal, out Vector3 result) { // I is the original array // N is the normal of the incident plane // R = I - (2 * N * ( DotProduct[ I,N] )) // inline the dotProduct here instead of calling method float dotProduct = ((vector.X * normal.X) + (vector.Y * normal.Y)) + (vector.Z * normal.Z); result.X = vector.X - (2.0f * normal.X) * dotProduct; result.Y = vector.Y - (2.0f * normal.Y) * dotProduct; result.Z = vector.Z - (2.0f * normal.Z) * dotProduct; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains subtraction of on <see cref="Vector3"/> from a another. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="value2">Source <see cref="Vector3"/>.</param> /// <returns>The result of the vector subtraction.</returns> public static Vector3 Subtract(Vector3 value1, Vector3 value2) { value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains subtraction of on <see cref="Vector3"/> from a another. /// </summary> /// <param name="value1">Source <see cref="Vector3"/>.</param> /// <param name="value2">Source <see cref="Vector3"/>.</param> /// <param name="result">The result of the vector subtraction as an output parameter.</param> public static void Subtract(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; result.Z = value1.Z - value2.Z; } /// <summary> /// Returns a <see cref="String"/> representation of this <see cref="Vector3"/> in the format: /// {X:[<see cref="X"/>] Y:[<see cref="Y"/>] Z:[<see cref="Z"/>]} /// </summary> /// <returns>A <see cref="String"/> representation of this <see cref="Vector3"/>.</returns> public override string ToString() { StringBuilder sb = new StringBuilder(32); sb.Append("{X:"); sb.Append(this.X); sb.Append(" Y:"); sb.Append(this.Y); sb.Append(" Z:"); sb.Append(this.Z); sb.Append("}"); return sb.ToString(); } #region Transform /// <summary> /// Creates a new <see cref="Vector3"/> that contains a transformation of 3d-vector by the specified <see cref="Matrix4"/>. /// </summary> /// <param name="position">Source <see cref="Vector3"/>.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <returns>Transformed <see cref="Vector3"/>.</returns> public static Vector3 Transform(Vector3 position, Matrix4 matrix) { Transform(ref position, ref matrix, out position); return position; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains a transformation of 3d-vector by the specified <see cref="Matrix4"/>. /// </summary> /// <param name="position">Source <see cref="Vector3"/>.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="result">Transformed <see cref="Vector3"/> as an output parameter.</param> public static void Transform(ref Vector3 position, ref Matrix4 matrix, out Vector3 result) { var x = (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41; var y = (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42; var z = (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43; result.X = x; result.Y = y; result.Z = z; } /// <summary> /// Apply transformation on vectors within array of <see cref="Vector3"/> by the specified <see cref="Matrix4"/> and places the results in an another array. /// </summary> /// <param name="sourceArray">Source array.</param> /// <param name="sourceIndex">The starting index of transformation in the source array.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="destinationArray">Destination array.</param> /// <param name="destinationIndex">The starting index in the destination array, where the first <see cref="Vector3"/> should be written.</param> /// <param name="length">The number of vectors to be transformed.</param> public static void Transform(Vector3[] sourceArray, int sourceIndex, ref Matrix4 matrix, Vector3[] destinationArray, int destinationIndex, int length) { if (sourceArray == null) throw new ArgumentNullException("sourceArray"); if (destinationArray == null) throw new ArgumentNullException("destinationArray"); if (sourceArray.Length < sourceIndex + length) throw new ArgumentException("Source array length is lesser than sourceIndex + length"); if (destinationArray.Length < destinationIndex + length) throw new ArgumentException("Destination array length is lesser than destinationIndex + length"); // TODO: Are there options on some platforms to implement a vectorized version of this? for (var i = 0; i < length; i++) { var position = sourceArray[sourceIndex + i]; destinationArray[destinationIndex + i] = new Vector3( (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43); } } /// <summary> /// Apply transformation on all vectors within array of <see cref="Vector3"/> by the specified <see cref="Matrix4"/> and places the results in an another array. /// </summary> /// <param name="sourceArray">Source array.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="destinationArray">Destination array.</param> public static void Transform(Vector3[] sourceArray, ref Matrix4 matrix, Vector3[] destinationArray) { if (sourceArray == null) throw new ArgumentNullException("sourceArray"); if (destinationArray == null) throw new ArgumentNullException("destinationArray"); if (destinationArray.Length < sourceArray.Length) throw new ArgumentException("Destination array length is lesser than source array length"); // TODO: Are there options on some platforms to implement a vectorized version of this? for (var i = 0; i < sourceArray.Length; i++) { var position = sourceArray[i]; destinationArray[i] = new Vector3( (position.X*matrix.M11) + (position.Y*matrix.M21) + (position.Z*matrix.M31) + matrix.M41, (position.X*matrix.M12) + (position.Y*matrix.M22) + (position.Z*matrix.M32) + matrix.M42, (position.X*matrix.M13) + (position.Y*matrix.M23) + (position.Z*matrix.M33) + matrix.M43); } } #endregion #region TransformNormal /// <summary> /// Creates a new <see cref="Vector3"/> that contains a transformation of the specified normal by the specified <see cref="Matrix4"/>. /// </summary> /// <param name="normal">Source <see cref="Vector3"/> which represents a normal vector.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <returns>Transformed normal.</returns> public static Vector3 TransformNormal(Vector3 normal, Matrix4 matrix) { TransformNormal(ref normal, ref matrix, out normal); return normal; } /// <summary> /// Creates a new <see cref="Vector3"/> that contains a transformation of the specified normal by the specified <see cref="Matrix4"/>. /// </summary> /// <param name="normal">Source <see cref="Vector3"/> which represents a normal vector.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="result">Transformed normal as an output parameter.</param> public static void TransformNormal(ref Vector3 normal, ref Matrix4 matrix, out Vector3 result) { var x = (normal.X * matrix.M11) + (normal.Y * matrix.M21) + (normal.Z * matrix.M31); var y = (normal.X * matrix.M12) + (normal.Y * matrix.M22) + (normal.Z * matrix.M32); var z = (normal.X * matrix.M13) + (normal.Y * matrix.M23) + (normal.Z * matrix.M33); result.X = x; result.Y = y; result.Z = z; } /// <summary> /// Apply transformation on normals within array of <see cref="Vector3"/> by the specified <see cref="Matrix4"/> and places the results in an another array. /// </summary> /// <param name="sourceArray">Source array.</param> /// <param name="sourceIndex">The starting index of transformation in the source array.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="destinationArray">Destination array.</param> /// <param name="destinationIndex">The starting index in the destination array, where the first <see cref="Vector3"/> should be written.</param> /// <param name="length">The number of normals to be transformed.</param> public static void TransformNormal(Vector3[] sourceArray, int sourceIndex, ref Matrix4 matrix, Vector3[] destinationArray, int destinationIndex, int length) { if (sourceArray == null) throw new ArgumentNullException("sourceArray"); if (destinationArray == null) throw new ArgumentNullException("destinationArray"); if(sourceArray.Length < sourceIndex + length) throw new ArgumentException("Source array length is lesser than sourceIndex + length"); if (destinationArray.Length < destinationIndex + length) throw new ArgumentException("Destination array length is lesser than destinationIndex + length"); for (int x = 0; x < length; x++) { var normal = sourceArray[sourceIndex + x]; destinationArray[destinationIndex + x] = new Vector3( (normal.X * matrix.M11) + (normal.Y * matrix.M21) + (normal.Z * matrix.M31), (normal.X * matrix.M12) + (normal.Y * matrix.M22) + (normal.Z * matrix.M32), (normal.X * matrix.M13) + (normal.Y * matrix.M23) + (normal.Z * matrix.M33)); } } /// <summary> /// Apply transformation on all normals within array of <see cref="Vector3"/> by the specified <see cref="Matrix4"/> and places the results in an another array. /// </summary> /// <param name="sourceArray">Source array.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="destinationArray">Destination array.</param> public static void TransformNormal(Vector3[] sourceArray, ref Matrix4 matrix, Vector3[] destinationArray) { if(sourceArray == null) throw new ArgumentNullException("sourceArray"); if (destinationArray == null) throw new ArgumentNullException("destinationArray"); if (destinationArray.Length < sourceArray.Length) throw new ArgumentException("Destination array length is lesser than source array length"); for (var i = 0; i < sourceArray.Length; i++) { var normal = sourceArray[i]; destinationArray[i] = new Vector3( (normal.X*matrix.M11) + (normal.Y*matrix.M21) + (normal.Z*matrix.M31), (normal.X*matrix.M12) + (normal.Y*matrix.M22) + (normal.Z*matrix.M32), (normal.X*matrix.M13) + (normal.Y*matrix.M23) + (normal.Z*matrix.M33)); } } #endregion #endregion #region Operators /// <summary> /// Compares whether two <see cref="Vector3"/> instances are equal. /// </summary> /// <param name="value1"><see cref="Vector3"/> instance on the left of the equal sign.</param> /// <param name="value2"><see cref="Vector3"/> instance on the right of the equal sign.</param> /// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns> public static bool operator ==(Vector3 value1, Vector3 value2) { return value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z; } /// <summary> /// Compares whether two <see cref="Vector3"/> instances are not equal. /// </summary> /// <param name="value1"><see cref="Vector3"/> instance on the left of the not equal sign.</param> /// <param name="value2"><see cref="Vector3"/> instance on the right of the not equal sign.</param> /// <returns><c>true</c> if the instances are not equal; <c>false</c> otherwise.</returns> public static bool operator !=(Vector3 value1, Vector3 value2) { return !(value1 == value2); } /// <summary> /// Adds two vectors. /// </summary> /// <param name="value1">Source <see cref="Vector3"/> on the left of the add sign.</param> /// <param name="value2">Source <see cref="Vector3"/> on the right of the add sign.</param> /// <returns>Sum of the vectors.</returns> public static Vector3 operator +(Vector3 value1, Vector3 value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } /// <summary> /// Inverts values in the specified <see cref="Vector3"/>. /// </summary> /// <param name="value">Source <see cref="Vector3"/> on the right of the sub sign.</param> /// <returns>Result of the inversion.</returns> public static Vector3 operator -(Vector3 value) { value = new Vector3(-value.X, -value.Y, -value.Z); return value; } /// <summary> /// Subtracts a <see cref="Vector3"/> from a <see cref="Vector3"/>. /// </summary> /// <param name="value1">Source <see cref="Vector3"/> on the left of the sub sign.</param> /// <param name="value2">Source <see cref="Vector3"/> on the right of the sub sign.</param> /// <returns>Result of the vector subtraction.</returns> public static Vector3 operator -(Vector3 value1, Vector3 value2) { value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } /// <summary> /// Multiplies the components of two vectors by each other. /// </summary> /// <param name="value1">Source <see cref="Vector3"/> on the left of the mul sign.</param> /// <param name="value2">Source <see cref="Vector3"/> on the right of the mul sign.</param> /// <returns>Result of the vector multiplication.</returns> public static Vector3 operator *(Vector3 value1, Vector3 value2) { value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } /// <summary> /// Multiplies the components of vector by a scalar. /// </summary> /// <param name="value">Source <see cref="Vector3"/> on the left of the mul sign.</param> /// <param name="scaleFactor">Scalar value on the right of the mul sign.</param> /// <returns>Result of the vector multiplication with a scalar.</returns> public static Vector3 operator *(Vector3 value, float scaleFactor) { value.X *= scaleFactor; value.Y *= scaleFactor; value.Z *= scaleFactor; return value; } /// <summary> /// Multiplies the components of vector by a scalar. /// </summary> /// <param name="scaleFactor">Scalar value on the left of the mul sign.</param> /// <param name="value">Source <see cref="Vector3"/> on the right of the mul sign.</param> /// <returns>Result of the vector multiplication with a scalar.</returns> public static Vector3 operator *(float scaleFactor, Vector3 value) { value.X *= scaleFactor; value.Y *= scaleFactor; value.Z *= scaleFactor; return value; } /// <summary> /// Divides the components of a <see cref="Vector3"/> by the components of another <see cref="Vector3"/>. /// </summary> /// <param name="value1">Source <see cref="Vector3"/> on the left of the div sign.</param> /// <param name="value2">Divisor <see cref="Vector3"/> on the right of the div sign.</param> /// <returns>The result of dividing the vectors.</returns> public static Vector3 operator /(Vector3 value1, Vector3 value2) { value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } /// <summary> /// Divides the components of a <see cref="Vector3"/> by a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector3"/> on the left of the div sign.</param> /// <param name="divider">Divisor scalar on the right of the div sign.</param> /// <returns>The result of dividing a vector by a scalar.</returns> public static Vector3 operator /(Vector3 value1, float divider) { float factor = 1 / divider; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } #endregion } }
// <copyright file="NormalGammaTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 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> namespace MathNet.Numerics.UnitTests.DistributionTests.Multivariate { using System; using System.Linq; using Distributions; using NUnit.Framework; /// <summary> /// <c>NormalGamma</c> distribution tests. /// </summary> [TestFixture, Category("Distributions")] public class NormalGammaTests { /// <summary> /// Can create <c>NormalGamma</c>. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> [TestCase(0.0, 1.0, 1.0, 1.0)] [TestCase(10.0, 2.0, 2.0, 2.0)] public void CanCreateNormalGamma(double meanLocation, double meanScale, double precShape, double precInvScale) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); Assert.AreEqual(meanLocation, ng.MeanLocation); Assert.AreEqual(meanScale, ng.MeanScale); Assert.AreEqual(precShape, ng.PrecisionShape); Assert.AreEqual(precInvScale, ng.PrecisionInverseScale); } /// <summary> /// Can get density and density log. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> [TestCase(0.0, 1.0, 1.0, 1.0)] [TestCase(10.0, 1.0, 2.0, 2.0)] public void CanGetDensityAndDensityLn(double meanLocation, double meanScale, double precShape, double precInvScale) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); Assert.AreEqual(ng.DensityLn(meanLocation, precShape), Math.Log(ng.Density(meanLocation, precShape)), 1e-14); } /// <summary> /// <c>NormalGamma</c> constructor fails with invalid params. /// </summary> [Test] public void NormalGammaConstructorFailsWithInvalidParams() { Assert.That(() => new NormalGamma(1.0, -1.3, 2.0, 2.0), Throws.ArgumentException); Assert.That(() => new NormalGamma(1.0, 1.0, -1.0, 1.0), Throws.ArgumentException); Assert.That(() => new NormalGamma(1.0, 1.0, 1.0, -1.0), Throws.ArgumentException); } /// <summary> /// Can get mean location. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> [TestCase(0.0, 1.0, 1.0, 1.0)] [TestCase(10.0, 2.0, 2.0, 2.0)] public void CanGetMeanLocation(double meanLocation, double meanScale, double precShape, double precInvScale) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); Assert.AreEqual(meanLocation, ng.MeanLocation); } /// <summary> /// Can get mean scale. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> [TestCase(0.0, 1.0, 1.0, 1.0)] [TestCase(10.0, 2.0, 2.0, 2.0)] public void CanGetMeanScale(double meanLocation, double meanScale, double precShape, double precInvScale) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); Assert.AreEqual(meanScale, ng.MeanScale); } /// <summary> /// Can get precision shape. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> [TestCase(0.0, 1.0, 1.0, 1.0)] [TestCase(10.0, 2.0, 2.0, 2.0)] public void CanGetPrecisionShape(double meanLocation, double meanScale, double precShape, double precInvScale) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); Assert.AreEqual(precShape, ng.PrecisionShape); } /// <summary> /// Can get precision inverse scale. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> [TestCase(0.0, 1.0, 1.0, 1.0)] [TestCase(10.0, 2.0, 2.0, 2.0)] public void CanGetPrecisionInverseScale(double meanLocation, double meanScale, double precShape, double precInvScale) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); Assert.AreEqual(precInvScale, ng.PrecisionInverseScale); } /// <summary> /// Can get mean marginals. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> /// <param name="meanMarginalMean">Mean marginal mean.</param> /// <param name="meanMarginalScale">Mean marginal scale.</param> /// <param name="meanMarginalDoF">Mean marginal degrees of freedom.</param> [TestCase(0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 2.0)] [TestCase(10.0, 1.0, 2.0, 2.0, 10.0, 1.0, 4.0)] [TestCase(10.0, 1.0, 2.0, Double.PositiveInfinity, 10.0, 0.5, Double.PositiveInfinity)] public void CanGetMeanMarginal(double meanLocation, double meanScale, double precShape, double precInvScale, double meanMarginalMean, double meanMarginalScale, double meanMarginalDoF) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); var mm = ng.MeanMarginal(); Assert.AreEqual(meanMarginalMean, mm.Location); Assert.AreEqual(meanMarginalScale, mm.Scale); Assert.AreEqual(meanMarginalDoF, mm.DegreesOfFreedom); } /// <summary> /// Can get precision marginal. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> [TestCase(0.0, 1.0, 1.0, 1.0)] [TestCase(10.0, 2.0, 2.0, 2.0)] [TestCase(10.0, 2.0, 2.0, Double.PositiveInfinity)] public void CanGetPrecisionMarginal(double meanLocation, double meanScale, double precShape, double precInvScale) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); var pm = ng.PrecisionMarginal(); Assert.AreEqual(precShape, pm.Shape); Assert.AreEqual(precInvScale, pm.Rate); } /// <summary> /// Can get mean. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> /// <param name="meanMean">Mean value.</param> /// <param name="meanPrecision">Mean precision.</param> [TestCase(0.0, 1.0, 1.0, 1.0, 0.0, 1.0)] [TestCase(10.0, 1.0, 2.0, 2.0, 10.0, 1.0)] [TestCase(10.0, 1.0, 2.0, Double.PositiveInfinity, 10.0, 2.0)] public void CanGetMean(double meanLocation, double meanScale, double precShape, double precInvScale, double meanMean, double meanPrecision) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); Assert.AreEqual(meanMean, ng.Mean.Mean); Assert.AreEqual(meanPrecision, ng.Mean.Precision); } /// <summary> /// Has random source. /// </summary> [Test] public void HasRandomSource() { var ng = new NormalGamma(0.0, 1.0, 1.0, 1.0); Assert.IsNotNull(ng.RandomSource); } /// <summary> /// Can set random source. /// </summary> [Test] public void CanSetRandomSource() { GC.KeepAlive(new NormalGamma(0.0, 1.0, 1.0, 1.0) { RandomSource = new Random(0) }); } /// <summary> /// Validate variance. /// </summary> /// <param name="meanLocation">Mean location.</param> /// <param name="meanScale">Mean scale.</param> /// <param name="precShape">Precision shape.</param> /// <param name="precInvScale">Precision inverse scale.</param> [TestCase(0.0, 1.0, 1.0, 1.0)] [TestCase(10.0, 2.0, 2.0, 2.0)] [TestCase(10.9, 2.0, 2.0, Double.PositiveInfinity)] public void ValidateVariance(double meanLocation, double meanScale, double precShape, double precInvScale) { var ng = new NormalGamma(meanLocation, meanScale, precShape, precInvScale); var x = precInvScale / (meanScale * (precShape - 1)); var t = precShape / Math.Sqrt(precInvScale); Assert.AreEqual(x, ng.Variance.Mean); Assert.AreEqual(t, ng.Variance.Precision); } /// <summary> /// Test the method which samples one variable at a time. /// </summary> [Test] public void SampleFollowsCorrectDistribution() { var cd = new NormalGamma(1.0, 4.0, 7.0, 3.5); // Sample from the distribution. var samples = new MeanPrecisionPair[CommonDistributionTests.NumberOfTestSamples]; for (var i = 0; i < CommonDistributionTests.NumberOfTestSamples; i++) { samples[i] = cd.Sample(); } // Extract the mean and precisions. var means = samples.Select(mp => mp.Mean).ToArray(); var precs = samples.Select(mp => mp.Precision).ToArray(); var meanMarginal = cd.MeanMarginal(); var precMarginal = cd.PrecisionMarginal(); // Check the precision distribution. CommonDistributionTests.ContinuousVapnikChervonenkisTest( CommonDistributionTests.ErrorTolerance, CommonDistributionTests.ErrorProbability, precs, precMarginal); // Check the mean distribution. CommonDistributionTests.ContinuousVapnikChervonenkisTest( CommonDistributionTests.ErrorTolerance, CommonDistributionTests.ErrorProbability, means, meanMarginal); } /// <summary> /// Test the method which samples a sequence of variables. /// </summary> [Test] public void SamplesFollowsCorrectDistribution() { var cd = new NormalGamma(1.0, 4.0, 3.0, 3.5); // Sample from the distribution. var samples = cd.Samples().Take(CommonDistributionTests.NumberOfTestSamples).ToArray(); // Extract the mean and precisions. var means = samples.Select(mp => mp.Mean).ToArray(); var precs = samples.Select(mp => mp.Precision).ToArray(); var meanMarginal = cd.MeanMarginal(); var precMarginal = cd.PrecisionMarginal(); // Check the precision distribution. CommonDistributionTests.ContinuousVapnikChervonenkisTest( CommonDistributionTests.ErrorTolerance, CommonDistributionTests.ErrorProbability, precs, precMarginal); // Check the mean distribution. CommonDistributionTests.ContinuousVapnikChervonenkisTest( CommonDistributionTests.ErrorTolerance, CommonDistributionTests.ErrorProbability, means, meanMarginal); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sqs-2012-11-05.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SQS.Model { /// <summary> /// Container for the parameters to the ReceiveMessage operation. /// Retrieves one or more messages, with a maximum limit of 10 messages, from the specified /// queue. Long poll support is enabled by using the <code>WaitTimeSeconds</code> parameter. /// For more information, see <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html">Amazon /// SQS Long Poll</a> in the <i>Amazon SQS Developer Guide</i>. /// /// /// <para> /// Short poll is the default behavior where a weighted random set of machines is sampled /// on a <code>ReceiveMessage</code> call. This means only the messages on the sampled /// machines are returned. If the number of messages in the queue is small (less than /// 1000), it is likely you will get fewer messages than you requested per <code>ReceiveMessage</code> /// call. If the number of messages in the queue is extremely small, you might not receive /// any messages in a particular <code>ReceiveMessage</code> response; in which case you /// should repeat the request. /// </para> /// /// <para> /// For each message returned, the response includes the following: /// </para> /// <ul> <li> /// <para> /// Message body /// </para> /// </li> <li> /// <para> /// MD5 digest of the message body. For information about MD5, go to <a href="http://www.faqs.org/rfcs/rfc1321.html">http://www.faqs.org/rfcs/rfc1321.html</a>. /// /// </para> /// </li> <li> /// <para> /// Message ID you received when you sent the message to the queue. /// </para> /// </li> <li> /// <para> /// Receipt handle. /// </para> /// </li> <li> /// <para> /// Message attributes. /// </para> /// </li> <li> /// <para> /// MD5 digest of the message attributes. /// </para> /// </li> </ul> /// <para> /// The receipt handle is the identifier you must provide when deleting the message. /// For more information, see <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ImportantIdentifiers.html">Queue /// and Message Identifiers</a> in the <i>Amazon SQS Developer Guide</i>. /// </para> /// /// <para> /// You can provide the <code>VisibilityTimeout</code> parameter in your request, which /// will be applied to the messages that Amazon SQS returns in the response. If you do /// not include the parameter, the overall visibility timeout for the queue is used for /// the returned messages. For more information, see <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html">Visibility /// Timeout</a> in the <i>Amazon SQS Developer Guide</i>. /// </para> /// <note> /// <para> /// Going forward, new attributes might be added. If you are writing code that calls /// this action, we recommend that you structure your code so that it can handle new attributes /// gracefully. /// </para> /// </note> /// </summary> public partial class ReceiveMessageRequest : AmazonSQSRequest { private List<string> _attributeNames = new List<string>(); private int? _maxNumberOfMessages; private List<string> _messageAttributeNames = new List<string>(); private string _queueUrl; private int? _visibilityTimeout; private int? _waitTimeSeconds; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public ReceiveMessageRequest() { } /// <summary> /// Instantiates ReceiveMessageRequest with the parameterized properties /// </summary> /// <param name="queueUrl">The URL of the Amazon SQS queue to take action on.</param> public ReceiveMessageRequest(string queueUrl) { _queueUrl = queueUrl; } /// <summary> /// Gets and sets the property AttributeNames. /// <para> /// A list of attributes that need to be returned along with each message. /// </para> /// /// <para> /// The following lists the names and descriptions of the attributes that can be returned: /// /// </para> /// <ul> <li> <code>All</code> - returns all values.</li> <li> <code>ApproximateFirstReceiveTimestamp</code> /// - returns the time when the message was first received from the queue (epoch time /// in milliseconds).</li> <li> <code>ApproximateReceiveCount</code> - returns the number /// of times a message has been received from the queue but not deleted.</li> <li> <code>SenderId</code> /// - returns the AWS account number (or the IP address, if anonymous access is allowed) /// of the sender.</li> <li> <code>SentTimestamp</code> - returns the time when the message /// was sent to the queue (epoch time in milliseconds).</li> </ul> /// </summary> public List<string> AttributeNames { get { return this._attributeNames; } set { this._attributeNames = value; } } // Check to see if AttributeNames property is set internal bool IsSetAttributeNames() { return this._attributeNames != null && this._attributeNames.Count > 0; } /// <summary> /// Gets and sets the property MaxNumberOfMessages. /// <para> /// The maximum number of messages to return. Amazon SQS never returns more messages than /// this value but may return fewer. Values can be from 1 to 10. Default is 1. /// </para> /// /// <para> /// All of the messages are not necessarily returned. /// </para> /// </summary> public int MaxNumberOfMessages { get { return this._maxNumberOfMessages.GetValueOrDefault(); } set { this._maxNumberOfMessages = value; } } // Check to see if MaxNumberOfMessages property is set internal bool IsSetMaxNumberOfMessages() { return this._maxNumberOfMessages.HasValue; } /// <summary> /// Gets and sets the property MessageAttributeNames. /// <para> /// The name of the message attribute, where <i>N</i> is the index. The message attribute /// name can contain the following characters: A-Z, a-z, 0-9, underscore (_), hyphen (-), /// and period (.). The name must not start or end with a period, and it should not have /// successive periods. The name is case sensitive and must be unique among all attribute /// names for the message. The name can be up to 256 characters long. The name cannot /// start with "AWS." or "Amazon." (or any variations in casing), because these prefixes /// are reserved for use by Amazon Web Services. /// </para> /// /// <para> /// When using <code>ReceiveMessage</code>, you can send a list of attribute names to /// receive, or you can return all of the attributes by specifying "All" or ".*" in your /// request. You can also use "foo.*" to return all message attributes starting with the /// "foo" prefix. /// </para> /// </summary> public List<string> MessageAttributeNames { get { return this._messageAttributeNames; } set { this._messageAttributeNames = value; } } // Check to see if MessageAttributeNames property is set internal bool IsSetMessageAttributeNames() { return this._messageAttributeNames != null && this._messageAttributeNames.Count > 0; } /// <summary> /// Gets and sets the property QueueUrl. /// <para> /// The URL of the Amazon SQS queue to take action on. /// </para> /// </summary> public string QueueUrl { get { return this._queueUrl; } set { this._queueUrl = value; } } // Check to see if QueueUrl property is set internal bool IsSetQueueUrl() { return this._queueUrl != null; } /// <summary> /// Gets and sets the property VisibilityTimeout. /// <para> /// The duration (in seconds) that the received messages are hidden from subsequent retrieve /// requests after being retrieved by a <code>ReceiveMessage</code> request. /// </para> /// </summary> public int VisibilityTimeout { get { return this._visibilityTimeout.GetValueOrDefault(); } set { this._visibilityTimeout = value; } } // Check to see if VisibilityTimeout property is set internal bool IsSetVisibilityTimeout() { return this._visibilityTimeout.HasValue; } /// <summary> /// Gets and sets the property WaitTimeSeconds. /// <para> /// The duration (in seconds) for which the call will wait for a message to arrive in /// the queue before returning. If a message is available, the call will return sooner /// than WaitTimeSeconds. /// </para> /// </summary> public int WaitTimeSeconds { get { return this._waitTimeSeconds.GetValueOrDefault(); } set { this._waitTimeSeconds = value; } } // Check to see if WaitTimeSeconds property is set internal bool IsSetWaitTimeSeconds() { return this._waitTimeSeconds.HasValue; } } }
using System; using System.IO; using System.Drawing; using System.Resources; using System.Windows.Forms; using System.Drawing.Printing; using System.ComponentModel.Design; namespace System.Workflow.ComponentModel.Design { /// <summary> /// Summary description for Form1. /// </summary> [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class WorkflowPageSetupDialog : System.Windows.Forms.Form { #region [....] Desiger Generated Members private System.ComponentModel.Container components = null; private System.Windows.Forms.TabControl tabs; private System.Windows.Forms.PictureBox landscapePicture; private System.Windows.Forms.PictureBox portraitPicture; private System.Windows.Forms.TabPage pageSettingsTab; private System.Windows.Forms.GroupBox marginsGroup; private NumericUpDown marginsBottomInput; private NumericUpDown marginsRightInput; private NumericUpDown marginsTopInput; private System.Windows.Forms.Label marginsTopLabel; private System.Windows.Forms.Label marginsLeftLabel; private System.Windows.Forms.Label marginsBottomLabel; private System.Windows.Forms.Label marginsRightLabel; private NumericUpDown marginsLeftInput; private System.Windows.Forms.GroupBox scalingGroup; private NumericUpDown adjustToScaleInput; private System.Windows.Forms.RadioButton adjustToRadioButton; private System.Windows.Forms.RadioButton fitToRadioButton; private NumericUpDown fitToPagesWideInput; private NumericUpDown fitToPagesTallInput; private System.Windows.Forms.Label fitToTallLabel; private System.Windows.Forms.Label fitToWideLabel; private System.Windows.Forms.GroupBox orientationGroup; private System.Windows.Forms.RadioButton portraitRadioButton; private System.Windows.Forms.RadioButton landscapeRadioButton; private System.Windows.Forms.GroupBox paperSettingsGroup; private System.Windows.Forms.ComboBox paperSizeComboBox; private System.Windows.Forms.Label paperSizeLabel; private System.Windows.Forms.Label paperSourceLabel; private System.Windows.Forms.ComboBox paperSourceComboBox; private System.Windows.Forms.TabPage headerFooterTab; private System.Windows.Forms.GroupBox footerGroup; private System.Windows.Forms.GroupBox headerGroup; private System.Windows.Forms.ComboBox headerAlignmentComboBox; private System.Windows.Forms.Label headerAlignmentLabel; private System.Windows.Forms.ComboBox headerTextComboBox; private System.Windows.Forms.Label headerTextLabel; private System.Windows.Forms.Label headerMarginLabel; private System.Windows.Forms.Button OKButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button printerButton; private NumericUpDown headerMarginInput; private NumericUpDown footerMarginInput; private System.Windows.Forms.ComboBox footerAlignmentComboBox; private System.Windows.Forms.Label footerAlignmentLabel; private System.Windows.Forms.ComboBox footerTextComboBox; private System.Windows.Forms.Label footerTextLabel; private System.Windows.Forms.Label footerMarginLabel; private System.Windows.Forms.Label scalingOfSizeLabel; private System.Windows.Forms.Label footerMarginUnitsLabel; private System.Windows.Forms.Label headerMarginUnitsLabel; private System.Windows.Forms.TextBox customHeaderText; private System.Windows.Forms.Label customHeaderLabel; private System.Windows.Forms.Label customFooterLabel; private System.Windows.Forms.TextBox customFooterText; private System.Windows.Forms.GroupBox centerGroup; private System.Windows.Forms.CheckBox CenterHorizontallyCheckBox; private System.Windows.Forms.CheckBox CenterVerticallyCheckBox; #endregion #region Members and Constructor/Destructor private IServiceProvider serviceProvider; private WorkflowPrintDocument printDocument = null; private string headerFooterNone = null; private string headerFooterCustom = null; private string[] headerFooterTemplates = null; private bool headerCustom = false; private TableLayoutPanel okCancelTableLayoutPanel; private TableLayoutPanel paperTableLayoutPanel; private TableLayoutPanel centerTableLayoutPanel; private TableLayoutPanel marginsTableLayoutPanel; private TableLayoutPanel orientationTableLayoutPanel; private TableLayoutPanel scalingTableLayoutPanel; private TableLayoutPanel headerTableLayoutPanel; private TableLayoutPanel footerTableLayoutPanel; private bool footerCustom = false; public WorkflowPageSetupDialog(IServiceProvider serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); this.serviceProvider = serviceProvider; WorkflowView workflowView = this.serviceProvider.GetService(typeof(WorkflowView)) as WorkflowView; if (workflowView == null) throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(WorkflowView).FullName)); if (!(workflowView.PrintDocument is WorkflowPrintDocument)) throw new InvalidOperationException(DR.GetString(DR.WorkflowPrintDocumentNotFound, typeof(WorkflowPrintDocument).Name)); try { Cursor.Current = Cursors.WaitCursor; InitializeComponent(); this.printDocument = workflowView.PrintDocument as WorkflowPrintDocument; //deserialize state of the dialog from the page setup data scaling: //set the values scaling controls this.adjustToScaleInput.Value = this.printDocument.PageSetupData.ScaleFactor; this.fitToPagesWideInput.Value = this.printDocument.PageSetupData.PagesWide; this.fitToPagesTallInput.Value = this.printDocument.PageSetupData.PagesTall; //select the right mode if (this.printDocument.PageSetupData.AdjustToScaleFactor) this.adjustToRadioButton.Checked = true; else this.fitToRadioButton.Checked = true; //set the orientation if (this.printDocument.PageSetupData.Landscape) this.landscapeRadioButton.Checked = true; else this.portraitRadioButton.Checked = true; //margins SetMarginsToUI(this.printDocument.PageSetupData.Margins); //centering this.CenterHorizontallyCheckBox.Checked = this.printDocument.PageSetupData.CenterHorizontally; this.CenterVerticallyCheckBox.Checked = this.printDocument.PageSetupData.CenterVertically; //Initialize the paper InitializePaperInformation(); //read standard header/footer formats this.headerFooterNone = DR.GetString(DR.HeaderFooterStringNone); //"(none)" this.headerFooterCustom = DR.GetString(DR.HeaderFooterStringCustom); //"(none)" this.headerFooterTemplates = new string[] { DR.GetString(DR.HeaderFooterFormat1), //"Page %Page%",// DR.GetString(DR.HeaderFooterFormat2), //"Page %Page% of %Pages%",// DR.GetString(DR.HeaderFooterFormat3), //"%Path%%File, Page %Page% of %Pages%", // DR.GetString(DR.HeaderFooterFormat4), //"%Path%%File, Page %Page%",// DR.GetString(DR.HeaderFooterFormat5), //"%File, %Date% %Time%, Page %Page%",// DR.GetString(DR.HeaderFooterFormat6), //"%File, Page %Page% of %Pages%",// DR.GetString(DR.HeaderFooterFormat7), //"%File, Page %Page%",// DR.GetString(DR.HeaderFooterFormat8), //"Prepated by %User% %Date%",// DR.GetString(DR.HeaderFooterFormat9), //"%User%, Page %Page%, %Date%"// }; //header inputs this.headerTextComboBox.Items.Add(this.headerFooterNone); this.headerTextComboBox.Items.AddRange(this.headerFooterTemplates); this.headerTextComboBox.Items.Add(this.headerFooterCustom); this.headerTextComboBox.SelectedIndex = 0; string userHeader = this.printDocument.PageSetupData.HeaderTemplate; this.headerCustom = this.printDocument.PageSetupData.HeaderCustom; if (userHeader.Length == 0) { this.headerTextComboBox.SelectedIndex = 0; //none } else { int userHeaderIndex = this.headerTextComboBox.Items.IndexOf(userHeader); if (-1 == userHeaderIndex || this.headerCustom) { //this is an unknown template, put it into custom field this.headerTextComboBox.SelectedIndex = this.headerTextComboBox.Items.IndexOf(this.headerFooterCustom); this.customHeaderText.Text = userHeader; } else { this.headerTextComboBox.SelectedIndex = userHeaderIndex; } } this.headerAlignmentComboBox.Items.AddRange(new object[] { HorizontalAlignment.Left, HorizontalAlignment.Center, HorizontalAlignment.Right }); if (this.headerAlignmentComboBox.Items.IndexOf(this.printDocument.PageSetupData.HeaderAlignment) != -1) this.headerAlignmentComboBox.SelectedItem = this.printDocument.PageSetupData.HeaderAlignment; else this.headerAlignmentComboBox.SelectedItem = HorizontalAlignment.Center; this.headerMarginInput.Value = PrinterUnitToUIUnit(this.printDocument.PageSetupData.HeaderMargin); //footer inputs this.footerTextComboBox.Items.Add(this.headerFooterNone); this.footerTextComboBox.SelectedIndex = 0; this.footerTextComboBox.Items.AddRange(this.headerFooterTemplates); this.footerTextComboBox.Items.Add(this.headerFooterCustom); string userFooter = this.printDocument.PageSetupData.FooterTemplate; this.footerCustom = this.printDocument.PageSetupData.FooterCustom; if (userFooter.Length == 0) { this.footerTextComboBox.SelectedIndex = 0; //none } else { int userFooterIndex = this.footerTextComboBox.Items.IndexOf(userFooter); if (-1 == userFooterIndex || this.footerCustom) { //this is an unknown template, put it into custom field this.footerTextComboBox.SelectedIndex = this.footerTextComboBox.Items.IndexOf(this.headerFooterCustom); this.customFooterText.Text = userFooter; } else { this.footerTextComboBox.SelectedIndex = userFooterIndex; } } this.footerAlignmentComboBox.Items.AddRange(new object[] { HorizontalAlignment.Left, HorizontalAlignment.Center, HorizontalAlignment.Right }); if (this.footerAlignmentComboBox.Items.IndexOf(this.printDocument.PageSetupData.FooterAlignment) != -1) this.footerAlignmentComboBox.SelectedItem = this.printDocument.PageSetupData.FooterAlignment; else this.footerAlignmentComboBox.SelectedItem = HorizontalAlignment.Center; this.footerMarginInput.Value = PrinterUnitToUIUnit(this.printDocument.PageSetupData.FooterMargin); } finally { Cursor.Current = Cursors.Default; } } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WorkflowPageSetupDialog)); this.tabs = new System.Windows.Forms.TabControl(); this.pageSettingsTab = new System.Windows.Forms.TabPage(); this.centerGroup = new System.Windows.Forms.GroupBox(); this.centerTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.CenterVerticallyCheckBox = new System.Windows.Forms.CheckBox(); this.CenterHorizontallyCheckBox = new System.Windows.Forms.CheckBox(); this.marginsGroup = new System.Windows.Forms.GroupBox(); this.marginsTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.marginsRightInput = new System.Windows.Forms.NumericUpDown(); this.marginsBottomInput = new System.Windows.Forms.NumericUpDown(); this.marginsTopLabel = new System.Windows.Forms.Label(); this.marginsLeftLabel = new System.Windows.Forms.Label(); this.marginsRightLabel = new System.Windows.Forms.Label(); this.marginsBottomLabel = new System.Windows.Forms.Label(); this.marginsTopInput = new System.Windows.Forms.NumericUpDown(); this.marginsLeftInput = new System.Windows.Forms.NumericUpDown(); this.scalingGroup = new System.Windows.Forms.GroupBox(); this.scalingTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.fitToTallLabel = new System.Windows.Forms.Label(); this.scalingOfSizeLabel = new System.Windows.Forms.Label(); this.fitToWideLabel = new System.Windows.Forms.Label(); this.adjustToRadioButton = new System.Windows.Forms.RadioButton(); this.fitToPagesTallInput = new System.Windows.Forms.NumericUpDown(); this.fitToPagesWideInput = new System.Windows.Forms.NumericUpDown(); this.adjustToScaleInput = new System.Windows.Forms.NumericUpDown(); this.fitToRadioButton = new System.Windows.Forms.RadioButton(); this.orientationGroup = new System.Windows.Forms.GroupBox(); this.orientationTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.landscapeRadioButton = new System.Windows.Forms.RadioButton(); this.landscapePicture = new System.Windows.Forms.PictureBox(); this.portraitRadioButton = new System.Windows.Forms.RadioButton(); this.portraitPicture = new System.Windows.Forms.PictureBox(); this.paperSettingsGroup = new System.Windows.Forms.GroupBox(); this.paperTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.paperSourceComboBox = new System.Windows.Forms.ComboBox(); this.paperSizeComboBox = new System.Windows.Forms.ComboBox(); this.paperSizeLabel = new System.Windows.Forms.Label(); this.paperSourceLabel = new System.Windows.Forms.Label(); this.headerFooterTab = new System.Windows.Forms.TabPage(); this.footerGroup = new System.Windows.Forms.GroupBox(); this.footerTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.footerTextLabel = new System.Windows.Forms.Label(); this.footerAlignmentLabel = new System.Windows.Forms.Label(); this.footerMarginUnitsLabel = new System.Windows.Forms.Label(); this.footerMarginLabel = new System.Windows.Forms.Label(); this.footerMarginInput = new System.Windows.Forms.NumericUpDown(); this.footerTextComboBox = new System.Windows.Forms.ComboBox(); this.footerAlignmentComboBox = new System.Windows.Forms.ComboBox(); this.customFooterText = new System.Windows.Forms.TextBox(); this.customFooterLabel = new System.Windows.Forms.Label(); this.headerGroup = new System.Windows.Forms.GroupBox(); this.headerTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.headerTextLabel = new System.Windows.Forms.Label(); this.headerAlignmentLabel = new System.Windows.Forms.Label(); this.headerMarginUnitsLabel = new System.Windows.Forms.Label(); this.headerMarginLabel = new System.Windows.Forms.Label(); this.headerMarginInput = new System.Windows.Forms.NumericUpDown(); this.headerTextComboBox = new System.Windows.Forms.ComboBox(); this.headerAlignmentComboBox = new System.Windows.Forms.ComboBox(); this.customHeaderText = new System.Windows.Forms.TextBox(); this.customHeaderLabel = new System.Windows.Forms.Label(); this.OKButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.printerButton = new System.Windows.Forms.Button(); this.okCancelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.tabs.SuspendLayout(); this.pageSettingsTab.SuspendLayout(); this.centerGroup.SuspendLayout(); this.centerTableLayoutPanel.SuspendLayout(); this.marginsGroup.SuspendLayout(); this.marginsTableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.marginsRightInput)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.marginsBottomInput)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.marginsTopInput)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.marginsLeftInput)).BeginInit(); this.scalingGroup.SuspendLayout(); this.scalingTableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.fitToPagesTallInput)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.fitToPagesWideInput)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.adjustToScaleInput)).BeginInit(); this.orientationGroup.SuspendLayout(); this.orientationTableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.landscapePicture)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.portraitPicture)).BeginInit(); this.paperSettingsGroup.SuspendLayout(); this.paperTableLayoutPanel.SuspendLayout(); this.headerFooterTab.SuspendLayout(); this.footerGroup.SuspendLayout(); this.footerTableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.footerMarginInput)).BeginInit(); this.headerGroup.SuspendLayout(); this.headerTableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.headerMarginInput)).BeginInit(); this.okCancelTableLayoutPanel.SuspendLayout(); this.SuspendLayout(); // // tabs // resources.ApplyResources(this.tabs, "tabs"); this.tabs.Controls.Add(this.pageSettingsTab); this.tabs.Controls.Add(this.headerFooterTab); this.tabs.Name = "tabs"; this.tabs.SelectedIndex = 0; // // pageSettingsTab // this.pageSettingsTab.Controls.Add(this.centerGroup); this.pageSettingsTab.Controls.Add(this.marginsGroup); this.pageSettingsTab.Controls.Add(this.scalingGroup); this.pageSettingsTab.Controls.Add(this.orientationGroup); this.pageSettingsTab.Controls.Add(this.paperSettingsGroup); resources.ApplyResources(this.pageSettingsTab, "pageSettingsTab"); this.pageSettingsTab.Name = "pageSettingsTab"; // // centerGroup // resources.ApplyResources(this.centerGroup, "centerGroup"); this.centerGroup.Controls.Add(this.centerTableLayoutPanel); this.centerGroup.Name = "centerGroup"; this.centerGroup.TabStop = false; // // centerTableLayoutPanel // resources.ApplyResources(this.centerTableLayoutPanel, "centerTableLayoutPanel"); this.centerTableLayoutPanel.Controls.Add(this.CenterVerticallyCheckBox, 1, 0); this.centerTableLayoutPanel.Controls.Add(this.CenterHorizontallyCheckBox, 0, 0); this.centerTableLayoutPanel.Name = "centerTableLayoutPanel"; // // CenterVerticallyCheckBox // resources.ApplyResources(this.CenterVerticallyCheckBox, "CenterVerticallyCheckBox"); this.CenterVerticallyCheckBox.Name = "CenterVerticallyCheckBox"; // // CenterHorizontallyCheckBox // resources.ApplyResources(this.CenterHorizontallyCheckBox, "CenterHorizontallyCheckBox"); this.CenterHorizontallyCheckBox.Name = "CenterHorizontallyCheckBox"; // // marginsGroup // resources.ApplyResources(this.marginsGroup, "marginsGroup"); this.marginsGroup.Controls.Add(this.marginsTableLayoutPanel); this.marginsGroup.Name = "marginsGroup"; this.marginsGroup.TabStop = false; // // marginsTableLayoutPanel // resources.ApplyResources(this.marginsTableLayoutPanel, "marginsTableLayoutPanel"); this.marginsTableLayoutPanel.Controls.Add(this.marginsRightInput, 3, 1); this.marginsTableLayoutPanel.Controls.Add(this.marginsBottomInput, 3, 0); this.marginsTableLayoutPanel.Controls.Add(this.marginsTopLabel, 0, 0); this.marginsTableLayoutPanel.Controls.Add(this.marginsLeftLabel, 0, 1); this.marginsTableLayoutPanel.Controls.Add(this.marginsRightLabel, 2, 1); this.marginsTableLayoutPanel.Controls.Add(this.marginsBottomLabel, 2, 0); this.marginsTableLayoutPanel.Controls.Add(this.marginsTopInput, 1, 0); this.marginsTableLayoutPanel.Controls.Add(this.marginsLeftInput, 1, 1); this.marginsTableLayoutPanel.Name = "marginsTableLayoutPanel"; // // marginsRightInput // resources.ApplyResources(this.marginsRightInput, "marginsRightInput"); this.marginsRightInput.DecimalPlaces = 2; this.marginsRightInput.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.marginsRightInput.Name = "marginsRightInput"; this.marginsRightInput.Value = new decimal(new int[] { 100, 0, 0, 131072}); this.marginsRightInput.Validating += new System.ComponentModel.CancelEventHandler(this.Margins_Validating); // // marginsBottomInput // resources.ApplyResources(this.marginsBottomInput, "marginsBottomInput"); this.marginsBottomInput.DecimalPlaces = 2; this.marginsBottomInput.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.marginsBottomInput.Name = "marginsBottomInput"; this.marginsBottomInput.Value = new decimal(new int[] { 100, 0, 0, 131072}); this.marginsBottomInput.Validating += new System.ComponentModel.CancelEventHandler(this.Margins_Validating); // // marginsTopLabel // resources.ApplyResources(this.marginsTopLabel, "marginsTopLabel"); this.marginsTopLabel.Name = "marginsTopLabel"; // // marginsLeftLabel // resources.ApplyResources(this.marginsLeftLabel, "marginsLeftLabel"); this.marginsLeftLabel.Name = "marginsLeftLabel"; // // marginsRightLabel // resources.ApplyResources(this.marginsRightLabel, "marginsRightLabel"); this.marginsRightLabel.Name = "marginsRightLabel"; // // marginsBottomLabel // resources.ApplyResources(this.marginsBottomLabel, "marginsBottomLabel"); this.marginsBottomLabel.Name = "marginsBottomLabel"; // // marginsTopInput // resources.ApplyResources(this.marginsTopInput, "marginsTopInput"); this.marginsTopInput.DecimalPlaces = 2; this.marginsTopInput.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.marginsTopInput.Name = "marginsTopInput"; this.marginsTopInput.Value = new decimal(new int[] { 100, 0, 0, 131072}); this.marginsTopInput.Validating += new System.ComponentModel.CancelEventHandler(this.Margins_Validating); // // marginsLeftInput // resources.ApplyResources(this.marginsLeftInput, "marginsLeftInput"); this.marginsLeftInput.DecimalPlaces = 2; this.marginsLeftInput.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.marginsLeftInput.Name = "marginsLeftInput"; this.marginsLeftInput.Value = new decimal(new int[] { 100, 0, 0, 131072}); this.marginsLeftInput.Validating += new System.ComponentModel.CancelEventHandler(this.Margins_Validating); // // scalingGroup // resources.ApplyResources(this.scalingGroup, "scalingGroup"); this.scalingGroup.Controls.Add(this.scalingTableLayoutPanel); this.scalingGroup.Name = "scalingGroup"; this.scalingGroup.TabStop = false; // // scalingTableLayoutPanel // resources.ApplyResources(this.scalingTableLayoutPanel, "scalingTableLayoutPanel"); this.scalingTableLayoutPanel.Controls.Add(this.fitToTallLabel, 2, 2); this.scalingTableLayoutPanel.Controls.Add(this.scalingOfSizeLabel, 2, 0); this.scalingTableLayoutPanel.Controls.Add(this.fitToWideLabel, 2, 1); this.scalingTableLayoutPanel.Controls.Add(this.adjustToRadioButton, 0, 0); this.scalingTableLayoutPanel.Controls.Add(this.fitToPagesTallInput, 1, 2); this.scalingTableLayoutPanel.Controls.Add(this.fitToPagesWideInput, 1, 1); this.scalingTableLayoutPanel.Controls.Add(this.adjustToScaleInput, 1, 0); this.scalingTableLayoutPanel.Controls.Add(this.fitToRadioButton, 0, 1); this.scalingTableLayoutPanel.Name = "scalingTableLayoutPanel"; // // fitToTallLabel // resources.ApplyResources(this.fitToTallLabel, "fitToTallLabel"); this.fitToTallLabel.Name = "fitToTallLabel"; // // scalingOfSizeLabel // resources.ApplyResources(this.scalingOfSizeLabel, "scalingOfSizeLabel"); this.scalingOfSizeLabel.Name = "scalingOfSizeLabel"; // // fitToWideLabel // resources.ApplyResources(this.fitToWideLabel, "fitToWideLabel"); this.fitToWideLabel.Name = "fitToWideLabel"; // // adjustToRadioButton // resources.ApplyResources(this.adjustToRadioButton, "adjustToRadioButton"); this.adjustToRadioButton.Name = "adjustToRadioButton"; // // fitToPagesTallInput // resources.ApplyResources(this.fitToPagesTallInput, "fitToPagesTallInput"); this.fitToPagesTallInput.Maximum = new decimal(new int[] { 20, 0, 0, 0}); this.fitToPagesTallInput.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.fitToPagesTallInput.Name = "fitToPagesTallInput"; this.fitToPagesTallInput.Value = new decimal(new int[] { 1, 0, 0, 0}); this.fitToPagesTallInput.ValueChanged += new System.EventHandler(this.fitToInputs_ValueChanged); // // fitToPagesWideInput // resources.ApplyResources(this.fitToPagesWideInput, "fitToPagesWideInput"); this.fitToPagesWideInput.Maximum = new decimal(new int[] { 20, 0, 0, 0}); this.fitToPagesWideInput.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.fitToPagesWideInput.Name = "fitToPagesWideInput"; this.fitToPagesWideInput.Value = new decimal(new int[] { 1, 0, 0, 0}); this.fitToPagesWideInput.ValueChanged += new System.EventHandler(this.fitToInputs_ValueChanged); // // adjustToScaleInput // resources.ApplyResources(this.adjustToScaleInput, "adjustToScaleInput"); this.adjustToScaleInput.Maximum = new decimal(new int[] { 400, 0, 0, 0}); this.adjustToScaleInput.Minimum = new decimal(new int[] { 10, 0, 0, 0}); this.adjustToScaleInput.Name = "adjustToScaleInput"; this.adjustToScaleInput.Value = new decimal(new int[] { 100, 0, 0, 0}); this.adjustToScaleInput.ValueChanged += new System.EventHandler(this.adjustToInput_ValueChanged); // // fitToRadioButton // resources.ApplyResources(this.fitToRadioButton, "fitToRadioButton"); this.fitToRadioButton.Name = "fitToRadioButton"; // // orientationGroup // resources.ApplyResources(this.orientationGroup, "orientationGroup"); this.orientationGroup.Controls.Add(this.orientationTableLayoutPanel); this.orientationGroup.Name = "orientationGroup"; this.orientationGroup.TabStop = false; // // orientationTableLayoutPanel // resources.ApplyResources(this.orientationTableLayoutPanel, "orientationTableLayoutPanel"); this.orientationTableLayoutPanel.Controls.Add(this.landscapeRadioButton, 3, 0); this.orientationTableLayoutPanel.Controls.Add(this.landscapePicture, 2, 0); this.orientationTableLayoutPanel.Controls.Add(this.portraitRadioButton, 1, 0); this.orientationTableLayoutPanel.Controls.Add(this.portraitPicture, 0, 0); this.orientationTableLayoutPanel.Name = "orientationTableLayoutPanel"; // // landscapeRadioButton // resources.ApplyResources(this.landscapeRadioButton, "landscapeRadioButton"); this.landscapeRadioButton.Name = "landscapeRadioButton"; this.landscapeRadioButton.CheckedChanged += new System.EventHandler(this.landscapeRadioButton_CheckedChanged); // // landscapePicture // resources.ApplyResources(this.landscapePicture, "landscapePicture"); this.landscapePicture.Name = "landscapePicture"; this.landscapePicture.TabStop = false; // // portraitRadioButton // resources.ApplyResources(this.portraitRadioButton, "portraitRadioButton"); this.portraitRadioButton.Name = "portraitRadioButton"; this.portraitRadioButton.CheckedChanged += new System.EventHandler(this.portraitRadioButton_CheckedChanged); // // portraitPicture // resources.ApplyResources(this.portraitPicture, "portraitPicture"); this.portraitPicture.Name = "portraitPicture"; this.portraitPicture.TabStop = false; // // paperSettingsGroup // resources.ApplyResources(this.paperSettingsGroup, "paperSettingsGroup"); this.paperSettingsGroup.Controls.Add(this.paperTableLayoutPanel); this.paperSettingsGroup.Name = "paperSettingsGroup"; this.paperSettingsGroup.TabStop = false; // // paperTableLayoutPanel // resources.ApplyResources(this.paperTableLayoutPanel, "paperTableLayoutPanel"); this.paperTableLayoutPanel.Controls.Add(this.paperSourceComboBox, 1, 1); this.paperTableLayoutPanel.Controls.Add(this.paperSizeComboBox, 1, 0); this.paperTableLayoutPanel.Controls.Add(this.paperSizeLabel, 0, 0); this.paperTableLayoutPanel.Controls.Add(this.paperSourceLabel, 0, 1); this.paperTableLayoutPanel.Name = "paperTableLayoutPanel"; // // paperSourceComboBox // resources.ApplyResources(this.paperSourceComboBox, "paperSourceComboBox"); this.paperSourceComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.paperSourceComboBox.FormattingEnabled = true; this.paperSourceComboBox.Name = "paperSourceComboBox"; // // paperSizeComboBox // resources.ApplyResources(this.paperSizeComboBox, "paperSizeComboBox"); this.paperSizeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.paperSizeComboBox.FormattingEnabled = true; this.paperSizeComboBox.Name = "paperSizeComboBox"; this.paperSizeComboBox.SelectedIndexChanged += new System.EventHandler(this.paperSizeComboBox_SelectedIndexChanged); // // paperSizeLabel // resources.ApplyResources(this.paperSizeLabel, "paperSizeLabel"); this.paperSizeLabel.Name = "paperSizeLabel"; // // paperSourceLabel // resources.ApplyResources(this.paperSourceLabel, "paperSourceLabel"); this.paperSourceLabel.Name = "paperSourceLabel"; // // headerFooterTab // this.headerFooterTab.Controls.Add(this.footerGroup); this.headerFooterTab.Controls.Add(this.headerGroup); resources.ApplyResources(this.headerFooterTab, "headerFooterTab"); this.headerFooterTab.Name = "headerFooterTab"; // // footerGroup // resources.ApplyResources(this.footerGroup, "footerGroup"); this.footerGroup.Controls.Add(this.footerTableLayoutPanel); this.footerGroup.Controls.Add(this.customFooterText); this.footerGroup.Controls.Add(this.customFooterLabel); this.footerGroup.Name = "footerGroup"; this.footerGroup.TabStop = false; // // footerTableLayoutPanel // resources.ApplyResources(this.footerTableLayoutPanel, "footerTableLayoutPanel"); this.footerTableLayoutPanel.Controls.Add(this.footerTextLabel, 0, 0); this.footerTableLayoutPanel.Controls.Add(this.footerAlignmentLabel, 0, 1); this.footerTableLayoutPanel.Controls.Add(this.footerMarginUnitsLabel, 2, 2); this.footerTableLayoutPanel.Controls.Add(this.footerMarginLabel, 0, 2); this.footerTableLayoutPanel.Controls.Add(this.footerMarginInput, 1, 2); this.footerTableLayoutPanel.Controls.Add(this.footerTextComboBox, 1, 0); this.footerTableLayoutPanel.Controls.Add(this.footerAlignmentComboBox, 1, 1); this.footerTableLayoutPanel.Name = "footerTableLayoutPanel"; // // footerTextLabel // resources.ApplyResources(this.footerTextLabel, "footerTextLabel"); this.footerTextLabel.Name = "footerTextLabel"; // // footerAlignmentLabel // resources.ApplyResources(this.footerAlignmentLabel, "footerAlignmentLabel"); this.footerAlignmentLabel.Name = "footerAlignmentLabel"; // // footerMarginUnitsLabel // resources.ApplyResources(this.footerMarginUnitsLabel, "footerMarginUnitsLabel"); this.footerMarginUnitsLabel.Name = "footerMarginUnitsLabel"; // // footerMarginLabel // resources.ApplyResources(this.footerMarginLabel, "footerMarginLabel"); this.footerMarginLabel.Name = "footerMarginLabel"; // // footerMarginInput // resources.ApplyResources(this.footerMarginInput, "footerMarginInput"); this.footerMarginInput.DecimalPlaces = 2; this.footerMarginInput.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.footerMarginInput.Name = "footerMarginInput"; this.footerMarginInput.Value = new decimal(new int[] { 1, 0, 0, 0}); this.footerMarginInput.Validating += new System.ComponentModel.CancelEventHandler(this.footerMarginInput_Validating); // // footerTextComboBox // resources.ApplyResources(this.footerTextComboBox, "footerTextComboBox"); this.footerTableLayoutPanel.SetColumnSpan(this.footerTextComboBox, 2); this.footerTextComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.footerTextComboBox.FormattingEnabled = true; this.footerTextComboBox.Name = "footerTextComboBox"; this.footerTextComboBox.SelectedIndexChanged += new System.EventHandler(this.footerTextComboBox_SelectedIndexChanged); // // footerAlignmentComboBox // resources.ApplyResources(this.footerAlignmentComboBox, "footerAlignmentComboBox"); this.footerTableLayoutPanel.SetColumnSpan(this.footerAlignmentComboBox, 2); this.footerAlignmentComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.footerAlignmentComboBox.FormattingEnabled = true; this.footerAlignmentComboBox.Name = "footerAlignmentComboBox"; // // customFooterText // resources.ApplyResources(this.customFooterText, "customFooterText"); this.customFooterText.Name = "customFooterText"; // // customFooterLabel // resources.ApplyResources(this.customFooterLabel, "customFooterLabel"); this.customFooterLabel.Name = "customFooterLabel"; // // headerGroup // resources.ApplyResources(this.headerGroup, "headerGroup"); this.headerGroup.Controls.Add(this.headerTableLayoutPanel); this.headerGroup.Controls.Add(this.customHeaderText); this.headerGroup.Controls.Add(this.customHeaderLabel); this.headerGroup.Name = "headerGroup"; this.headerGroup.TabStop = false; // // headerTableLayoutPanel // resources.ApplyResources(this.headerTableLayoutPanel, "headerTableLayoutPanel"); this.headerTableLayoutPanel.Controls.Add(this.headerTextLabel, 0, 0); this.headerTableLayoutPanel.Controls.Add(this.headerAlignmentLabel, 0, 1); this.headerTableLayoutPanel.Controls.Add(this.headerMarginUnitsLabel, 2, 2); this.headerTableLayoutPanel.Controls.Add(this.headerMarginLabel, 0, 2); this.headerTableLayoutPanel.Controls.Add(this.headerMarginInput, 1, 2); this.headerTableLayoutPanel.Controls.Add(this.headerTextComboBox, 1, 0); this.headerTableLayoutPanel.Controls.Add(this.headerAlignmentComboBox, 1, 1); this.headerTableLayoutPanel.Name = "headerTableLayoutPanel"; // // headerTextLabel // resources.ApplyResources(this.headerTextLabel, "headerTextLabel"); this.headerTextLabel.Name = "headerTextLabel"; // // headerAlignmentLabel // resources.ApplyResources(this.headerAlignmentLabel, "headerAlignmentLabel"); this.headerAlignmentLabel.Cursor = System.Windows.Forms.Cursors.Arrow; this.headerAlignmentLabel.Name = "headerAlignmentLabel"; // // headerMarginUnitsLabel // resources.ApplyResources(this.headerMarginUnitsLabel, "headerMarginUnitsLabel"); this.headerMarginUnitsLabel.Name = "headerMarginUnitsLabel"; // // headerMarginLabel // resources.ApplyResources(this.headerMarginLabel, "headerMarginLabel"); this.headerMarginLabel.Name = "headerMarginLabel"; // // headerMarginInput // resources.ApplyResources(this.headerMarginInput, "headerMarginInput"); this.headerMarginInput.DecimalPlaces = 2; this.headerMarginInput.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.headerMarginInput.Name = "headerMarginInput"; this.headerMarginInput.Value = new decimal(new int[] { 1, 0, 0, 0}); this.headerMarginInput.Validating += new System.ComponentModel.CancelEventHandler(this.headerMarginInput_Validating); // // headerTextComboBox // resources.ApplyResources(this.headerTextComboBox, "headerTextComboBox"); this.headerTableLayoutPanel.SetColumnSpan(this.headerTextComboBox, 2); this.headerTextComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.headerTextComboBox.FormattingEnabled = true; this.headerTextComboBox.Name = "headerTextComboBox"; this.headerTextComboBox.SelectedIndexChanged += new System.EventHandler(this.headerTextComboBox_SelectedIndexChanged); // // headerAlignmentComboBox // resources.ApplyResources(this.headerAlignmentComboBox, "headerAlignmentComboBox"); this.headerTableLayoutPanel.SetColumnSpan(this.headerAlignmentComboBox, 2); this.headerAlignmentComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.headerAlignmentComboBox.FormattingEnabled = true; this.headerAlignmentComboBox.Name = "headerAlignmentComboBox"; // // customHeaderText // resources.ApplyResources(this.customHeaderText, "customHeaderText"); this.customHeaderText.Name = "customHeaderText"; // // customHeaderLabel // resources.ApplyResources(this.customHeaderLabel, "customHeaderLabel"); this.customHeaderLabel.Name = "customHeaderLabel"; // // OKButton // resources.ApplyResources(this.OKButton, "OKButton"); this.OKButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.OKButton.Name = "OKButton"; this.OKButton.Click += new System.EventHandler(this.OKButton_Click); // // cancelButton // resources.ApplyResources(this.cancelButton, "cancelButton"); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Name = "cancelButton"; // // printerButton // resources.ApplyResources(this.printerButton, "printerButton"); this.printerButton.Name = "printerButton"; this.printerButton.Click += new System.EventHandler(this.printerButton_Click); // // okCancelTableLayoutPanel // resources.ApplyResources(this.okCancelTableLayoutPanel, "okCancelTableLayoutPanel"); this.okCancelTableLayoutPanel.Controls.Add(this.OKButton, 0, 0); this.okCancelTableLayoutPanel.Controls.Add(this.cancelButton, 1, 0); this.okCancelTableLayoutPanel.Controls.Add(this.printerButton, 2, 0); this.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel"; // // WorkflowPageSetupDialog // this.AcceptButton = this.OKButton; resources.ApplyResources(this, "$this"); this.CancelButton = this.cancelButton; this.Controls.Add(this.okCancelTableLayoutPanel); this.Controls.Add(this.tabs); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "WorkflowPageSetupDialog"; this.ShowInTaskbar = false; this.HelpButtonClicked += new System.ComponentModel.CancelEventHandler(this.WorkflowPageSetupDialog_HelpButtonClicked); this.tabs.ResumeLayout(false); this.pageSettingsTab.ResumeLayout(false); this.centerGroup.ResumeLayout(false); this.centerTableLayoutPanel.ResumeLayout(false); this.centerTableLayoutPanel.PerformLayout(); this.marginsGroup.ResumeLayout(false); this.marginsTableLayoutPanel.ResumeLayout(false); this.marginsTableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.marginsRightInput)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.marginsBottomInput)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.marginsTopInput)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.marginsLeftInput)).EndInit(); this.scalingGroup.ResumeLayout(false); this.scalingTableLayoutPanel.ResumeLayout(false); this.scalingTableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.fitToPagesTallInput)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.fitToPagesWideInput)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.adjustToScaleInput)).EndInit(); this.orientationGroup.ResumeLayout(false); this.orientationTableLayoutPanel.ResumeLayout(false); this.orientationTableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.landscapePicture)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.portraitPicture)).EndInit(); this.paperSettingsGroup.ResumeLayout(false); this.paperTableLayoutPanel.ResumeLayout(false); this.paperTableLayoutPanel.PerformLayout(); this.headerFooterTab.ResumeLayout(false); this.footerGroup.ResumeLayout(false); this.footerGroup.PerformLayout(); this.footerTableLayoutPanel.ResumeLayout(false); this.footerTableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.footerMarginInput)).EndInit(); this.headerGroup.ResumeLayout(false); this.headerGroup.PerformLayout(); this.headerTableLayoutPanel.ResumeLayout(false); this.headerTableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.headerMarginInput)).EndInit(); this.okCancelTableLayoutPanel.ResumeLayout(false); this.okCancelTableLayoutPanel.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion #region Events private void OKButton_Click(object sender, System.EventArgs e) { //serialize state of the dialog into the pageSetupData object Margins margins = GetMarginsFromUI(); //scaling this.printDocument.PageSetupData.AdjustToScaleFactor = this.adjustToRadioButton.Checked; this.printDocument.PageSetupData.ScaleFactor = (int)this.adjustToScaleInput.Value; this.printDocument.PageSetupData.PagesWide = (int)this.fitToPagesWideInput.Value; this.printDocument.PageSetupData.PagesTall = (int)this.fitToPagesTallInput.Value; //Set the orientation this.printDocument.PageSetupData.Landscape = this.landscapeRadioButton.Checked; this.printDocument.PageSetupData.Margins = margins; //centering this.printDocument.PageSetupData.CenterHorizontally = this.CenterHorizontallyCheckBox.Checked; this.printDocument.PageSetupData.CenterVertically = this.CenterVerticallyCheckBox.Checked; //header inputs if (this.headerTextComboBox.SelectedIndex == 0) this.printDocument.PageSetupData.HeaderTemplate = string.Empty; else if (!this.headerTextComboBox.Text.Equals(this.headerFooterCustom)) this.printDocument.PageSetupData.HeaderTemplate = this.headerTextComboBox.Text; else this.printDocument.PageSetupData.HeaderTemplate = this.customHeaderText.Text; this.printDocument.PageSetupData.HeaderCustom = this.headerCustom; this.printDocument.PageSetupData.HeaderAlignment = (HorizontalAlignment)this.headerAlignmentComboBox.SelectedItem; this.printDocument.PageSetupData.HeaderMargin = UIUnitToPrinterUnit(this.headerMarginInput.Value); //footer inputs if (this.footerTextComboBox.SelectedIndex == 0) this.printDocument.PageSetupData.FooterTemplate = string.Empty; else if (!this.footerTextComboBox.Text.Equals(this.headerFooterCustom)) this.printDocument.PageSetupData.FooterTemplate = this.footerTextComboBox.Text; else this.printDocument.PageSetupData.FooterTemplate = this.customFooterText.Text; this.printDocument.PageSetupData.FooterCustom = this.footerCustom; this.printDocument.PageSetupData.FooterAlignment = (HorizontalAlignment)this.footerAlignmentComboBox.SelectedItem; this.printDocument.PageSetupData.FooterMargin = UIUnitToPrinterUnit(this.footerMarginInput.Value); // Set the paper size based upon the selection in the combo box. if (PrinterSettings.InstalledPrinters.Count > 0) { if (this.paperSizeComboBox.SelectedItem != null) this.printDocument.DefaultPageSettings.PaperSize = (PaperSize)this.paperSizeComboBox.SelectedItem; // Set the paper source based upon the selection in the combo box. if (this.paperSourceComboBox.SelectedItem != null) this.printDocument.DefaultPageSettings.PaperSource = (PaperSource)this.paperSourceComboBox.SelectedItem; this.printDocument.DefaultPageSettings.Landscape = this.printDocument.PageSetupData.Landscape; this.printDocument.DefaultPageSettings.Margins = margins; //Make sure that printer setting are changed this.printDocument.PrinterSettings.DefaultPageSettings.PaperSize = this.printDocument.DefaultPageSettings.PaperSize; this.printDocument.PrinterSettings.DefaultPageSettings.PaperSource = this.printDocument.DefaultPageSettings.PaperSource; this.printDocument.PrinterSettings.DefaultPageSettings.Landscape = this.printDocument.PageSetupData.Landscape; this.printDocument.PrinterSettings.DefaultPageSettings.Margins = margins; } this.printDocument.PageSetupData.StorePropertiesToRegistry(); DialogResult = DialogResult.OK; } private void printerButton_Click(object sender, System.EventArgs e) { PrintDialog printDialog = new System.Windows.Forms.PrintDialog(); printDialog.AllowPrintToFile = false; printDialog.Document = this.printDocument; try { if (DialogResult.OK == printDialog.ShowDialog()) { this.printDocument.PrinterSettings = printDialog.PrinterSettings; this.printDocument.DefaultPageSettings = printDialog.Document.DefaultPageSettings; if (this.printDocument.DefaultPageSettings.Landscape) this.landscapeRadioButton.Checked = true; else this.portraitRadioButton.Checked = true; InitializePaperInformation(); this.printDocument.Print(); } else { //todo: copy updated settings from the dialog to the print doc //in the worst case it's a no-op, in case user clicked apply/cancel it's the only way to //update the settings (see Winoe#3129 and VSWhidbey#403124 for more details) } } catch (Exception exception) { string errorString = DR.GetString(DR.SelectedPrinterIsInvalidErrorMessage); errorString += "\n" + exception.Message; DesignerHelpers.ShowError(this.serviceProvider, errorString); } } private void Margins_Validating(object sender, System.ComponentModel.CancelEventArgs e) { Margins margins = GetMarginsFromUI(); //get the current paper size Size physicalPageSize; PaperSize paperSize = this.paperSizeComboBox.SelectedItem as PaperSize; if (null != paperSize) physicalPageSize = new Size(paperSize.Width, paperSize.Height); else physicalPageSize = this.printDocument.DefaultPageSettings.Bounds.Size; //check the constrains int horizontalMarginsSum = margins.Left + margins.Right; int verticalMarginsSum = margins.Top + margins.Bottom; if (horizontalMarginsSum < physicalPageSize.Width && verticalMarginsSum < physicalPageSize.Height) return; //we are good //cancelling the change - constrains are not satisfied string errorString = DR.GetString(DR.EnteredMarginsAreNotValidErrorMessage); DesignerHelpers.ShowError(this.serviceProvider, errorString); e.Cancel = true; } private void headerTextComboBox_SelectedIndexChanged(object sender, System.EventArgs e) { this.headerCustom = this.headerTextComboBox.Text.Equals(this.headerFooterCustom); this.customHeaderText.Enabled = this.headerCustom; if (!this.headerCustom) this.customHeaderText.Text = this.headerTextComboBox.Text; } private void footerTextComboBox_SelectedIndexChanged(object sender, System.EventArgs e) { this.footerCustom = this.footerTextComboBox.Text.Equals(this.headerFooterCustom); this.customFooterText.Enabled = this.footerCustom; if (!this.footerCustom) this.customFooterText.Text = this.footerTextComboBox.Text; } private void paperSizeComboBox_SelectedIndexChanged(object sender, System.EventArgs e) { UpdateHeaderFooterMarginLimit(); } private void landscapeRadioButton_CheckedChanged(object sender, System.EventArgs e) { UpdateHeaderFooterMarginLimit(); } private void portraitRadioButton_CheckedChanged(object sender, System.EventArgs e) { UpdateHeaderFooterMarginLimit(); } private void UpdateHeaderFooterMarginLimit() { PaperSize paperSize = this.paperSizeComboBox.SelectedItem as PaperSize; if (paperSize != null) this.footerMarginInput.Maximum = this.headerMarginInput.Maximum = PrinterUnitToUIUnit(this.landscapeRadioButton.Checked ? paperSize.Width : paperSize.Height); } private void headerMarginInput_Validating(object sender, System.ComponentModel.CancelEventArgs e) { } private void footerMarginInput_Validating(object sender, System.ComponentModel.CancelEventArgs e) { } private void adjustToInput_ValueChanged(object sender, System.EventArgs e) { this.adjustToRadioButton.Checked = true; } private void fitToInputs_ValueChanged(object sender, System.EventArgs e) { this.fitToRadioButton.Checked = true; } #endregion #region Helpers private void InitializePaperInformation() { PrinterSettings.PaperSizeCollection paperSizeCollection = this.printDocument.PrinterSettings.PaperSizes; PrinterSettings.PaperSourceCollection paperSourceCollection = this.printDocument.PrinterSettings.PaperSources; this.paperSizeComboBox.Items.Clear(); this.paperSizeComboBox.DisplayMember = "PaperName"; foreach (PaperSize paperSize in paperSizeCollection) { if (paperSize.PaperName != null && paperSize.PaperName.Length > 0) { this.paperSizeComboBox.Items.Add(paperSize); if (null == this.paperSizeComboBox.SelectedItem && this.printDocument.DefaultPageSettings.PaperSize.Kind == paperSize.Kind && this.printDocument.DefaultPageSettings.PaperSize.Width == paperSize.Width && this.printDocument.DefaultPageSettings.PaperSize.Height == paperSize.Height) { this.paperSizeComboBox.SelectedItem = paperSize; this.printDocument.DefaultPageSettings.PaperSize = paperSize; } } } if (null == this.paperSizeComboBox.SelectedItem) { PaperKind paperKind = this.printDocument.DefaultPageSettings.PaperSize.Kind; this.printDocument.DefaultPageSettings = new PageSettings(this.printDocument.PrinterSettings); foreach (PaperSize paperSize in this.paperSizeComboBox.Items) { if (null == this.paperSizeComboBox.SelectedItem && paperKind == paperSize.Kind && this.printDocument.DefaultPageSettings.PaperSize.Width == paperSize.Width && this.printDocument.DefaultPageSettings.PaperSize.Height == paperSize.Height) { this.paperSizeComboBox.SelectedItem = paperSize; this.printDocument.DefaultPageSettings.PaperSize = paperSize; } } //We still did not find matching paper so not select first in the list if (null == this.paperSizeComboBox.SelectedItem && this.paperSizeComboBox.Items.Count > 0) { this.paperSizeComboBox.SelectedItem = this.paperSizeComboBox.Items[0] as PaperSize; this.printDocument.DefaultPageSettings.PaperSize = this.paperSizeComboBox.SelectedItem as PaperSize; } } ///////////////Select the appropriate paper source based on the pageSettings this.paperSourceComboBox.Items.Clear(); this.paperSourceComboBox.DisplayMember = "SourceName"; foreach (PaperSource paperSource in paperSourceCollection) { this.paperSourceComboBox.Items.Add(paperSource); if (null == this.paperSourceComboBox.SelectedItem && this.printDocument.DefaultPageSettings.PaperSource.Kind == paperSource.Kind && this.printDocument.DefaultPageSettings.PaperSource.SourceName == paperSource.SourceName) this.paperSourceComboBox.SelectedItem = paperSource; } if (null == this.paperSourceComboBox.SelectedItem && this.paperSourceComboBox.Items.Count > 0) { this.paperSourceComboBox.SelectedItem = this.paperSourceComboBox.Items[0] as PaperSource; this.printDocument.DefaultPageSettings.PaperSource = this.paperSourceComboBox.SelectedItem as PaperSource; } } // private void SetMarginsToUI(Margins margins) { this.marginsLeftInput.Value = PrinterUnitToUIUnit(margins.Left); this.marginsRightInput.Value = PrinterUnitToUIUnit(margins.Right); this.marginsTopInput.Value = PrinterUnitToUIUnit(margins.Top); this.marginsBottomInput.Value = PrinterUnitToUIUnit(margins.Bottom); } private Margins GetMarginsFromUI() { Margins margins = new Margins( UIUnitToPrinterUnit(this.marginsLeftInput.Value), UIUnitToPrinterUnit(this.marginsRightInput.Value), UIUnitToPrinterUnit(this.marginsTopInput.Value), UIUnitToPrinterUnit(this.marginsBottomInput.Value)); return margins; } private decimal PrinterUnitToUIUnit(int printerValue) { return Convert.ToDecimal((double)printerValue / 100.0d); //in 1/100 of inch } private int UIUnitToPrinterUnit(decimal uiValue) { return Convert.ToInt32((double)uiValue * 100.0d); //in 1/100 of inch } #endregion private void WorkflowPageSetupDialog_HelpButtonClicked(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = true; GetHelp(); } protected override void OnHelpRequested(HelpEventArgs hlpevent) { hlpevent.Handled = true; GetHelp(); } private void GetHelp() { DesignerHelpers.ShowHelpFromKeyword(this.serviceProvider, typeof(WorkflowPageSetupDialog).FullName + ".UI"); } } }
namespace System.Windows.Forms { using System; using System.ComponentModel; using System.Reactive; using System.Reactive.Linq; /// <summary> /// Extension methods providing IObservable wrappers for the events on PictureBox. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class ObservablePictureBoxEvents { /// <summary> /// Returns an observable sequence wrapping the CausesValidationChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the CausesValidationChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> CausesValidationChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.CausesValidationChanged += handler, handler => instance.CausesValidationChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the ForeColorChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the ForeColorChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> ForeColorChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.ForeColorChanged += handler, handler => instance.ForeColorChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the FontChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the FontChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> FontChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.FontChanged += handler, handler => instance.FontChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the ImeModeChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the ImeModeChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> ImeModeChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.ImeModeChanged += handler, handler => instance.ImeModeChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the LoadCompleted event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the LoadCompleted event on the PictureBox instance.</returns> public static IObservable<EventPattern<AsyncCompletedEventArgs>> LoadCompletedObservable(this PictureBox instance) { return Observable.FromEventPattern<AsyncCompletedEventHandler, AsyncCompletedEventArgs>( handler => instance.LoadCompleted += handler, handler => instance.LoadCompleted -= handler); } /// <summary> /// Returns an observable sequence wrapping the LoadProgressChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the LoadProgressChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<ProgressChangedEventArgs>> LoadProgressChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<ProgressChangedEventHandler, ProgressChangedEventArgs>( handler => instance.LoadProgressChanged += handler, handler => instance.LoadProgressChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the RightToLeftChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the RightToLeftChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> RightToLeftChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.RightToLeftChanged += handler, handler => instance.RightToLeftChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the SizeModeChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the SizeModeChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> SizeModeChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.SizeModeChanged += handler, handler => instance.SizeModeChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the TabStopChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the TabStopChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> TabStopChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.TabStopChanged += handler, handler => instance.TabStopChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the TabIndexChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the TabIndexChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> TabIndexChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.TabIndexChanged += handler, handler => instance.TabIndexChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the TextChanged event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the TextChanged event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> TextChangedObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.TextChanged += handler, handler => instance.TextChanged -= handler); } /// <summary> /// Returns an observable sequence wrapping the Enter event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the Enter event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> EnterObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.Enter += handler, handler => instance.Enter -= handler); } /// <summary> /// Returns an observable sequence wrapping the KeyUp event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the KeyUp event on the PictureBox instance.</returns> public static IObservable<EventPattern<KeyEventArgs>> KeyUpObservable(this PictureBox instance) { return Observable.FromEventPattern<KeyEventHandler, KeyEventArgs>( handler => instance.KeyUp += handler, handler => instance.KeyUp -= handler); } /// <summary> /// Returns an observable sequence wrapping the KeyDown event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the KeyDown event on the PictureBox instance.</returns> public static IObservable<EventPattern<KeyEventArgs>> KeyDownObservable(this PictureBox instance) { return Observable.FromEventPattern<KeyEventHandler, KeyEventArgs>( handler => instance.KeyDown += handler, handler => instance.KeyDown -= handler); } /// <summary> /// Returns an observable sequence wrapping the KeyPress event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the KeyPress event on the PictureBox instance.</returns> public static IObservable<EventPattern<KeyPressEventArgs>> KeyPressObservable(this PictureBox instance) { return Observable.FromEventPattern<KeyPressEventHandler, KeyPressEventArgs>( handler => instance.KeyPress += handler, handler => instance.KeyPress -= handler); } /// <summary> /// Returns an observable sequence wrapping the Leave event on the PictureBox instance. /// </summary> /// <param name="instance">The PictureBox instance to observe.</param> /// <returns>An observable sequence wrapping the Leave event on the PictureBox instance.</returns> public static IObservable<EventPattern<EventArgs>> LeaveObservable(this PictureBox instance) { return Observable.FromEventPattern<EventHandler, EventArgs>( handler => instance.Leave += handler, handler => instance.Leave -= handler); } } }