context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace MiaPlaza.ExpressionUtils { /// <summary> /// Tools to help comparing expressions /// </summary> public static class ExpressionComparing { class ExpressionStructureComparisonException : InvalidOperationException { public ExpressionStructureComparisonException(Expression a, Expression b, Exception inner) : base($"Could not compare '{a}' and '{b}'", inner) { } } /// <summary> /// A visitor that computes the hash of an expression, optionally looking only to a certain depth. /// </summary> class HashCodeVisitor : ExpressionVisitor { public readonly int? MaxDepth; public readonly bool IgnoreConstants; public int ResultHash = Hashing.FnvOffset; private int currentDepth = 0; public HashCodeVisitor(bool ignoreConstants, int? maxDepth) { MaxDepth = maxDepth; IgnoreConstants = ignoreConstants; } public override Expression Visit(Expression node) { if (node == null) { return null; } Hashing.Hash(ref ResultHash, (int)node.NodeType); currentDepth++; if (MaxDepth == null || MaxDepth > currentDepth) { base.Visit(node); } Hashing.Hash(ref ResultHash, -1); currentDepth--; return node; } protected override Expression VisitConstant(ConstantExpression node) { if (IgnoreConstants) { Hashing.Hash(ref ResultHash, -1); } else { Hashing.Hash(ref ResultHash, node.Value?.GetHashCode() ?? -1); } return base.VisitConstant(node); } protected override Expression VisitMember(MemberExpression node) { Hashing.Hash(ref ResultHash, node.Member.GetHashCode()); return base.VisitMember(node); } protected override Expression VisitLambda<T>(Expression<T> node) { Hashing.Hash(ref ResultHash, node.ReturnType.GetHashCode()); return base.VisitLambda<T>(node); } protected override Expression VisitParameter(ParameterExpression node) { Hashing.Hash(ref ResultHash, node.Type.GetHashCode()); return base.VisitParameter(node); } protected override Expression VisitMethodCall(MethodCallExpression node) { Hashing.Hash(ref ResultHash, node.Method.GetHashCode()); return base.VisitMethodCall(node); } } /// <summary> /// A visitor that compares two expressions with each other. /// </summary> class ExpressionComparingVisitor : ExpressionResultVisitor<bool> { public readonly bool IgnoreConstantsValues; Expression other; public ExpressionComparingVisitor(Expression other, bool ignoreConstantValues) { this.other = other; IgnoreConstantsValues = ignoreConstantValues; } protected bool Compare(Expression a, Expression b) { other = b; return GetResultFromExpression(a); } public override bool GetResultFromExpression(Expression expression) { #if DEBUG if (expression == null && other == null) { return true; } #else if (ReferenceEquals(expression, other)) { return true; } #endif if (expression == null || other == null) { return false; } if (expression.NodeType != other.NodeType) { return false; } if (expression.Type != other.Type) { return false; } return base.GetResultFromExpression(expression); } protected override bool GetResultFromBinary(BinaryExpression a) { var b = (BinaryExpression)other; return a.IsLifted == b.IsLifted && a.IsLiftedToNull == b.IsLiftedToNull && a.Method == b.Method && Compare(a.Left, b.Left) && Compare(a.Right, b.Right) && Compare(a.Conversion, b.Conversion); } protected override bool GetResultFromBlock(BlockExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromCatchBlock(CatchBlock a) { throw new NotImplementedException(); } protected override bool GetResultFromConditional(ConditionalExpression a) { var b = (ConditionalExpression)other; return Compare(a.Test, b.Test) && Compare(a.IfTrue, b.IfTrue) && Compare(a.IfFalse, b.IfFalse); } protected override bool GetResultFromConstant(ConstantExpression a) { var b = (ConstantExpression)other; return IgnoreConstantsValues || Equals(a.Value, b.Value); } protected override bool GetResultFromDebugInfo(DebugInfoExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromDefault(DefaultExpression a) => true; protected override bool GetResultFromDynamic(DynamicExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromElementInit(ElementInit a) { throw new NotImplementedException(); } protected override bool GetResultFromExtension(Expression a) { throw new NotImplementedException(); } protected override bool GetResultFromGoto(GotoExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromIndex(IndexExpression a) { var b = (IndexExpression)other; return a.Indexer == b.Indexer && Compare(a.Object, b.Object) && a.Arguments.SequenceEqualOrBothNull(b.Arguments, Compare); } protected override bool GetResultFromInvocation(InvocationExpression a) { var b = (InvocationExpression)other; return a.Expression == b.Expression && a.Arguments.SequenceEqualOrBothNull(b.Arguments, Compare); } protected override bool GetResultFromLabel(LabelExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromLabelTarget(LabelTarget a) { throw new NotImplementedException(); } protected override bool GetResultFromLambda<D>(Expression<D> a) { var b = (Expression<D>)other; return a.ReturnType == b.ReturnType && a.Parameters.SequenceEqualOrBothNull(b.Parameters, Compare) && Compare(a.Body, b.Body); } protected override bool GetResultFromListInit(ListInitExpression a) { var b = (ListInitExpression)other; return Compare(a.NewExpression, b.NewExpression) && a.Initializers.SequenceEqualOrBothNull(b.Initializers, (ia, ib) => ia.AddMethod == ib.AddMethod && ia.Arguments.SequenceEqualOrBothNull(ib.Arguments, Compare)); } protected override bool GetResultFromLoop(LoopExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromMember(MemberExpression a) { var b = (MemberExpression)other; return a.Member == b.Member && Compare(a.Expression, b.Expression); } protected override bool GetResultFromMemberInit(MemberInitExpression a) { var b = (MemberInitExpression)other; return a.Bindings.SequenceEqualOrBothNull(b.Bindings, (ba, bb) => ba.BindingType == bb.BindingType && ba.Member == bb.Member) && a.NewExpression == b.NewExpression; } protected override bool GetResultFromMethodCall(MethodCallExpression a) { var b = (MethodCallExpression)other; return a.Method == b.Method && Compare(a.Object, b.Object) && a.Arguments.SequenceEqualOrBothNull(b.Arguments, Compare); } protected override bool GetResultFromNew(NewExpression a) { var b = (NewExpression)other; return a.Constructor == b.Constructor && a.Members.SequenceEqualOrBothNull(b.Members) && a.Arguments.SequenceEqualOrBothNull(b.Arguments, Compare); } protected override bool GetResultFromNewArray(NewArrayExpression a) { var b = (NewArrayExpression)other; return a.Expressions.SequenceEqualOrBothNull(b.Expressions, Compare); } protected override bool GetResultFromParameter(ParameterExpression a) { var b = (ParameterExpression)other; return a.IsByRef == b.IsByRef && a.Name == b.Name; } protected override bool GetResultFromRuntimeVariables(RuntimeVariablesExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromSwitch(SwitchExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromSwitchCase(SwitchCase a) { throw new NotImplementedException(); } protected override bool GetResultFromTry(TryExpression a) { throw new NotImplementedException(); } protected override bool GetResultFromTypeBinary(TypeBinaryExpression a) { var b = (TypeBinaryExpression)other; return a.TypeOperand == b.TypeOperand && Compare(a.Expression, b.Expression); } protected override bool GetResultFromUnary(UnaryExpression a) { var b = (UnaryExpression)other; return a.IsLifted == b.IsLifted && a.IsLiftedToNull == b.IsLiftedToNull && a.Method == b.Method && Compare(a.Operand, b.Operand); } } public sealed class StructuralComparer : IEqualityComparer<Expression> { public readonly int? HashCodeExpressionDepth; public readonly bool IgnoreConstantsValues; public StructuralComparer(bool ignoreConstantsValues = false, int? hashCodeExpressionDepth = 5) { IgnoreConstantsValues = ignoreConstantsValues; HashCodeExpressionDepth = hashCodeExpressionDepth; } public int GetHashCode(Expression tree) => GetNodeTypeStructureHashCode(tree, IgnoreConstantsValues, HashCodeExpressionDepth); bool IEqualityComparer<Expression>.Equals(Expression x, Expression y) => StructuralIdentical(x, y, IgnoreConstantsValues); } /// <summary> /// Visits the first <paramref name="hashCodeExpressionDepth"/> layers of the expression tree and calculates a hash code based on the <see cref="ExpressionType"/>s there. /// </summary> /// <param name="tree"></param> /// <param name="hashCodeExpressionDepth"></param> /// <returns></returns> public static int GetNodeTypeStructureHashCode(this Expression tree, bool ignoreConstantsValues = false, int? hashCodeExpressionDepth = null) { var visitor = new HashCodeVisitor(ignoreConstantsValues, hashCodeExpressionDepth); visitor.Visit(tree); return visitor.ResultHash; } /// <summary> /// Compares the structure (kind and order of operations, operands recursively) of expressions. Basically does a recursive member equality check /// </summary> public static bool StructuralIdentical(this Expression x, Expression y, bool ignoreConstantValues = false) { try { return new ExpressionComparingVisitor(y, ignoreConstantValues).GetResultFromExpression(x); } catch (Exception ex) { throw new ExpressionStructureComparisonException(x, y, ex); } } } }
// 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.Windows.Input; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using SR = MS.Internal.PresentationCore.SR; using SRID = MS.Internal.PresentationCore.SRID; namespace System.Windows.Ink { #region Public APIs // =========================================================================================== /// <summary> /// delegate used for event handlers that are called when a stroke was was added, removed, or modified inside of a Stroke collection /// </summary> public delegate void StrokeCollectionChangedEventHandler(object sender, StrokeCollectionChangedEventArgs e); /// <summary> /// Event arg used when delegate a stroke is was added, removed, or modified inside of a Stroke collection /// </summary> public class StrokeCollectionChangedEventArgs : EventArgs { private StrokeCollection.ReadOnlyStrokeCollection _added; private StrokeCollection.ReadOnlyStrokeCollection _removed; private int _index = -1; /// <summary>Constructor</summary> internal StrokeCollectionChangedEventArgs(StrokeCollection added, StrokeCollection removed, int index) : this(added, removed) { _index = index; } /// <summary>Constructor</summary> public StrokeCollectionChangedEventArgs(StrokeCollection added, StrokeCollection removed) { if ( added == null && removed == null ) { throw new ArgumentException(SR.Get(SRID.CannotBothBeNull, "added", "removed")); } _added = ( added == null ) ? null : new StrokeCollection.ReadOnlyStrokeCollection(added); _removed = ( removed == null ) ? null : new StrokeCollection.ReadOnlyStrokeCollection(removed); } /// <summary>Set of strokes that where added, result may be an empty collection</summary> public StrokeCollection Added { get { if ( _added == null ) { _added = new StrokeCollection.ReadOnlyStrokeCollection(new StrokeCollection()); } return _added; } } /// <summary>Set of strokes that where removed, result may be an empty collection</summary> public StrokeCollection Removed { get { if ( _removed == null ) { _removed = new StrokeCollection.ReadOnlyStrokeCollection(new StrokeCollection()); } return _removed; } } /// <summary> /// The zero based starting index that was affected /// </summary> internal int Index { get { return _index; } } } // =========================================================================================== /// <summary> /// delegate used for event handlers that are called when a change to the drawing attributes associated with one or more strokes has occurred. /// </summary> public delegate void PropertyDataChangedEventHandler(object sender, PropertyDataChangedEventArgs e); /// <summary> /// Event arg used a change to the drawing attributes associated with one or more strokes has occurred. /// </summary> public class PropertyDataChangedEventArgs : EventArgs { private Guid _propertyGuid; private object _newValue; private object _previousValue; /// <summary>Constructor</summary> public PropertyDataChangedEventArgs(Guid propertyGuid, object newValue, object previousValue) { if ( newValue == null && previousValue == null ) { throw new ArgumentException(SR.Get(SRID.CannotBothBeNull, "newValue", "previousValue")); } _propertyGuid = propertyGuid; _newValue = newValue; _previousValue = previousValue; } /// <summary> /// Gets the property guid that represents the DrawingAttribute that changed /// </summary> public Guid PropertyGuid { get { return _propertyGuid; } } /// <summary> /// Gets the new value of the DrawingAttribute /// </summary> public object NewValue { get { return _newValue; } } /// <summary> /// Gets the previous value of the DrawingAttribute /// </summary> public object PreviousValue { get { return _previousValue; } } } // =========================================================================================== /// <summary> /// delegate used for event handlers that are called when the Custom attributes associated with an object have changed. /// </summary> internal delegate void ExtendedPropertiesChangedEventHandler(object sender, ExtendedPropertiesChangedEventArgs e); /// <summary> /// Event Arg used when the Custom attributes associated with an object have changed. /// </summary> internal class ExtendedPropertiesChangedEventArgs : EventArgs { private ExtendedProperty _oldProperty; private ExtendedProperty _newProperty; /// <summary>Constructor</summary> internal ExtendedPropertiesChangedEventArgs(ExtendedProperty oldProperty, ExtendedProperty newProperty) { if ( oldProperty == null && newProperty == null ) { throw new ArgumentNullException("oldProperty"); } _oldProperty = oldProperty; _newProperty = newProperty; } /// <summary> /// The value of the previous property. If the Changed event was caused /// by an ExtendedProperty being added, this value is null /// </summary> internal ExtendedProperty OldProperty { get { return _oldProperty; } } /// <summary> /// The value of the new property. If the Changed event was caused by /// an ExtendedProperty being removed, this value is null /// </summary> internal ExtendedProperty NewProperty { get { return _newProperty; } } } /// <summary> /// The delegate to use for the DefaultDrawingAttributesReplaced event /// </summary> public delegate void DrawingAttributesReplacedEventHandler(object sender, DrawingAttributesReplacedEventArgs e); /// <summary> /// DrawingAttributesReplacedEventArgs /// </summary> public class DrawingAttributesReplacedEventArgs : EventArgs { /// <summary> /// DrawingAttributesReplacedEventArgs /// </summary> /// <remarks> /// This must be public so InkCanvas can instance it /// </remarks> public DrawingAttributesReplacedEventArgs(DrawingAttributes newDrawingAttributes, DrawingAttributes previousDrawingAttributes) { if ( newDrawingAttributes == null ) { throw new ArgumentNullException("newDrawingAttributes"); } if ( previousDrawingAttributes == null ) { throw new ArgumentNullException("previousDrawingAttributes"); } _newDrawingAttributes = newDrawingAttributes; _previousDrawingAttributes = previousDrawingAttributes; } /// <summary> /// [TBS] /// </summary> public DrawingAttributes NewDrawingAttributes { get { return _newDrawingAttributes; } } /// <summary> /// [TBS] /// </summary> public DrawingAttributes PreviousDrawingAttributes { get { return _previousDrawingAttributes; } } private DrawingAttributes _newDrawingAttributes; private DrawingAttributes _previousDrawingAttributes; } /// <summary> /// The delegate to use for the StylusPointsReplaced event /// </summary> public delegate void StylusPointsReplacedEventHandler(object sender, StylusPointsReplacedEventArgs e); /// <summary> /// StylusPointsReplacedEventArgs /// </summary> public class StylusPointsReplacedEventArgs : EventArgs { /// <summary> /// StylusPointsReplacedEventArgs /// </summary> /// <remarks> /// This must be public so InkCanvas can instance it /// </remarks> public StylusPointsReplacedEventArgs(StylusPointCollection newStylusPoints, StylusPointCollection previousStylusPoints) { if ( newStylusPoints == null ) { throw new ArgumentNullException("newStylusPoints"); } if ( previousStylusPoints == null ) { throw new ArgumentNullException("previousStylusPoints"); } _newStylusPoints = newStylusPoints; _previousStylusPoints = previousStylusPoints; } /// <summary> /// [TBS] /// </summary> public StylusPointCollection NewStylusPoints { get { return _newStylusPoints; } } /// <summary> /// [TBS] /// </summary> public StylusPointCollection PreviousStylusPoints { get { return _previousStylusPoints; } } private StylusPointCollection _newStylusPoints; private StylusPointCollection _previousStylusPoints; } #endregion }
// Copyright (C) 2006-2010 Jim Tilander. See COPYING for and README for more details. using System; using EnvDTE; using System.Threading; using System.Collections.Generic; namespace Aurora { public static class AsyncProcess { private static int s_defaultTimeout = 30000; // in ms public delegate void OnDone(bool ok, object arg0); public static void Init() { m_helperThread = new System.Threading.Thread(new ThreadStart(ThreadMain)); m_helperThread.Start(); } public static void Term() { m_helperThread.Abort(); } public static bool Run(OutputWindowPane output, string executable, string commandline, string workingdir, OnDone callback, object callbackArg) { int timeout = 1000; if (!RunCommand(output, executable, commandline, workingdir, timeout)) { Log.Debug("Failed to run immediate (process hung?), trying again on a remote thread: " + commandline); return Schedule(output, executable, commandline, workingdir, callback, callbackArg); } else { if (null != callback) { callback(true, callbackArg); } } return true; } public static bool Schedule(OutputWindowPane output, string executable, string commandline, string workingdir, OnDone callback, object callbackArg) { return Schedule(output, executable, commandline, workingdir, callback, callbackArg, s_defaultTimeout); } public static bool Schedule(OutputWindowPane output, string executable, string commandline, string workingdir, OnDone callback, object callbackArg, int timeout) { CommandThread cmd = new CommandThread(); cmd.output = output; cmd.executable = executable; cmd.commandline = commandline; cmd.workingdir = workingdir; cmd.callback = callback; cmd.callbackArg = callbackArg; cmd.timeout = timeout; try { m_queueLock.WaitOne(); m_commandQueue.Enqueue(cmd); } finally { m_queueLock.ReleaseMutex(); } m_startEvent.Release(); Log.Debug("Scheduled {0} {1}\n", cmd.executable, cmd.commandline); return true; } // --------------------------------------------------------------------------------------------------------------------------------------------- // // BEGIN INTERNALS // static private Mutex m_queueLock = new Mutex(); static private Semaphore m_startEvent = new Semaphore(0, 9999); static private Queue<CommandThread> m_commandQueue = new Queue<CommandThread>(); static private System.Threading.Thread m_helperThread; static private void ThreadMain() { while(true) { m_startEvent.WaitOne(); CommandThread cmd = null; try { m_queueLock.WaitOne(); cmd = m_commandQueue.Dequeue(); } finally { m_queueLock.ReleaseMutex(); } try { System.Threading.Thread thread = new System.Threading.Thread(new ThreadStart(cmd.Run)); thread.Start(); } catch { } } } private class CommandThread { public string executable = ""; public string commandline = ""; public string workingdir = ""; public OutputWindowPane output = null; public OnDone callback = null; public object callbackArg = null; public int timeout = 10000; public void Run() { try { bool ok = RunCommand(output, executable, commandline, workingdir, timeout); if (null != callback) { callback(ok, callbackArg); } } catch { Log.Error("Caught unhandled exception in async process -- supressing so that we don't bring down Visual Studio"); } } } static private bool RunCommand(OutputWindowPane output, string executable, string commandline, string workingdir, int timeout) { try { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = executable; if( 0 == timeout ) { // We are not for these processes reading the stdout and thus they could if they wrote more // data on the output line hang. process.StartInfo.RedirectStandardOutput = false; process.StartInfo.RedirectStandardError = false; } else { process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; } process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = workingdir; process.StartInfo.Arguments = commandline; Log.Debug("executableName : " + executable); Log.Debug("workingDirectory : " + workingdir); Log.Debug("command : " + commandline); if(!process.Start()) { Log.Error("{0}: {1} Failed to start. Is Perforce installed and in the path?\n", executable, commandline); return false; } if (0 == timeout) { // Fire and forget task. return true; } bool exited = false; string alloutput = ""; using (Process.Handler stderr = new Process.Handler(), stdout = new Process.Handler()) { process.OutputDataReceived += stdout.OnOutput; process.BeginOutputReadLine(); process.ErrorDataReceived += stderr.OnOutput; process.BeginErrorReadLine(); exited = process.WaitForExit(timeout); /* * This causes the plugin to unexpectedly crash, since it brings the entire thread down, and thus the entire environment?!? * if (0 != process.ExitCode) { throw new Process.Error("Failed to execute {0} {1}, exit code was {2}", executable, process.StartInfo.Arguments, process.ExitCode); }*/ stderr.sentinel.WaitOne(); stdout.sentinel.WaitOne(); alloutput = stdout.buffer + "\n" + stderr.buffer; } if(!exited) { Log.Info("{0}: {1} timed out ({2} ms)", executable, commandline, timeout); process.Kill(); return false; } else { if(null != output) { output.OutputString(executable + ": " + commandline + "\n"); output.OutputString(alloutput); } System.Diagnostics.Debug.WriteLine(commandline + "\n"); System.Diagnostics.Debug.WriteLine(alloutput); if(0 != process.ExitCode) { Log.Debug("{0}: {1} exit code {2}", executable, commandline, process.ExitCode); return false; } } return true; } catch(System.ComponentModel.Win32Exception e) { Log.Error("{0}: {1} failed to spawn: {2}", executable, commandline, e.ToString()); return false; } } // // END INTERNALS // // --------------------------------------------------------------------------------------------------------------------------------------------- } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Microsoft.Extensions.Localization; using Moon.Collections; namespace Moon.Validation { /// <summary> /// The cache of Validation and Display attributes. /// </summary> internal class AttributeStore { private readonly ConcurrentDictionary<Type, TypeItem> items = new ConcurrentDictionary<Type, TypeItem>(); private readonly IStringLocalizerFactory stringLocalizerFactory; /// <summary> /// Initializes a new instance of the <see cref="AttributeStore" /> class. /// </summary> /// <param name="stringLocalizerFactory">The string localizer factory.</param> public AttributeStore(IStringLocalizerFactory stringLocalizerFactory) { this.stringLocalizerFactory = stringLocalizerFactory; } /// <summary> /// Retrieves the display name associated with the given type. /// </summary> /// <param name="objectContext">The context that describes the type.</param> public string GetTypeDisplayName(ValidationContext objectContext) => GetTypeItem(objectContext.ObjectType).DisplayName; /// <summary> /// Retrieves the type level validation attributes for the given type. /// </summary> /// <param name="objectContext">The context that describes the type.</param> public IEnumerable<ValidationAttribute> GetTypeValidationAttributes(ValidationContext objectContext) => GetTypeItem(objectContext.ObjectType).ValidationAttributes; /// <summary> /// Retrieves the display name associated with the given property. /// </summary> /// <param name="propertyContext">The context that describes the property.</param> public string GetPropertyDisplayName(ValidationContext propertyContext) { var typeItem = GetTypeItem(propertyContext.ObjectType); var propertyItem = typeItem.GetPropertyItem(propertyContext.MemberName.Split('.').Last()); return propertyItem.DisplayName; } /// <summary> /// Retrieves the set of validation attributes for the property. /// </summary> /// <param name="propertyContext">The context that describes the property.</param> public IEnumerable<ValidationAttribute> GetPropertyValidationAttributes(ValidationContext propertyContext) { var typeItem = GetTypeItem(propertyContext.ObjectType); var propertyItem = typeItem.GetPropertyItem(propertyContext.MemberName.Split('.').Last()); return propertyItem.ValidationAttributes; } private IStringLocalizer GetStringLocalizer(Type objectType) { IStringLocalizer stringLocalizer = null; var providerFactory = DataValidator.LocalizerProvider; if (stringLocalizerFactory != null && providerFactory != null) { stringLocalizer = providerFactory(objectType, stringLocalizerFactory); } return stringLocalizer; } private TypeItem GetTypeItem(Type type) { TypeItem item; if (!items.TryGetValue(type, out item)) { var attributes = CustomAttributeExtensions.GetCustomAttributes(type.GetTypeInfo(), true); items[type] = item = new TypeItem(this, type, attributes); } return item; } private abstract class StoreItem { protected StoreItem(AttributeStore store) { Store = store; } public string DisplayName { get; protected set; } public IEnumerable<ValidationAttribute> ValidationAttributes { get; protected set; } protected AttributeStore Store { get; } protected string GetDisplayName(IEnumerable<Attribute> attributes, Type objectType, string propertyName = null) { if (propertyName != null) { var stringLocalizer = Store.GetStringLocalizer(objectType); var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault(); if (stringLocalizer != null && displayAttribute?.ResourceType == null) { return displayAttribute?.GetName() ?? stringLocalizer[propertyName]; } return displayAttribute?.GetName() ?? propertyName; } return objectType.Name; } protected IEnumerable<ValidationAttribute> GetValidationAttributes(IEnumerable<Attribute> attributes, Type objectType, string propertyName = null) { var results = new List<ValidationAttribute>(); var stringLocalizer = Store.GetStringLocalizer(objectType); foreach (var attribute in attributes.OfType<ValidationAttribute>()) { if (stringLocalizer != null) { UpdateErrorMessage(stringLocalizer, attribute, propertyName); } results.Add(attribute); } return results; } private void UpdateErrorMessage(IStringLocalizer stringLocalizer, ValidationAttribute attribute, string propertyName) { if (CanUpdateErrorMessage(attribute)) { var validatorName = attribute.GetValidatorName(); attribute.ErrorMessage = propertyName != null ? GetErrorMessage(stringLocalizer, propertyName, validatorName) : stringLocalizer[validatorName]; } } private string GetErrorMessage(IStringLocalizer stringLocalizer, string propertyName, string validatorName) { var localized = stringLocalizer[$"{propertyName}_{validatorName}"]; return localized.ResourceNotFound ? stringLocalizer[$"_{validatorName}"] : localized; } private bool CanUpdateErrorMessage(ValidationAttribute attribute) => string.IsNullOrEmpty(attribute.ErrorMessageResourceName) && attribute.ErrorMessageResourceType == null; } private class TypeItem : StoreItem { private readonly Type objectType; private readonly ConcurrentDictionary<string, PropertyItem> propertyItems = new ConcurrentDictionary<string, PropertyItem>(); public TypeItem(AttributeStore store, Type objectType, IEnumerable<Attribute> attributes) : base(store) { DisplayName = GetDisplayName(attributes, objectType); ValidationAttributes = GetValidationAttributes(attributes, objectType); this.objectType = objectType; } public PropertyItem GetPropertyItem(string propertyName) { if (propertyItems.Count == 0) { AddPropertyItems(); } if (!propertyItems.ContainsKey(propertyName)) { throw new ArgumentException($"A property with name '{propertyName}' could not be found."); } return propertyItems[propertyName]; } private void AddPropertyItems() { var properties = objectType.GetRuntimeProperties() .Where(p => IsPublic(p) && p.GetIndexParameters().Empty()); foreach (var property in properties) { var attributes = CustomAttributeExtensions.GetCustomAttributes(property, true); propertyItems[property.Name] = new PropertyItem(Store, objectType, property.Name, attributes); } } private bool IsPublic(PropertyInfo property) { return property.GetMethod != null && property.GetMethod.IsPublic || property.SetMethod != null && property.SetMethod.IsPublic; } } private class PropertyItem : StoreItem { public PropertyItem(AttributeStore store, Type objectType, string propertyName, IEnumerable<Attribute> attributes) : base(store) { DisplayName = GetDisplayName(attributes, objectType, propertyName); ValidationAttributes = GetValidationAttributes(attributes, objectType, propertyName); } } } }
// 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 AndNotUInt64() { var test = new SimpleBinaryOpTest__AndNotUInt64(); 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 SimpleBinaryOpTest__AndNotUInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = 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.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.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<UInt64> _fld1; public Vector128<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndNotUInt64 testClass) { var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotUInt64 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((UInt64*)(pFld1)), Sse2.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndNotUInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public SimpleBinaryOpTest__AndNotUInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.AndNot( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.AndNot( Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.AndNot( Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2) { var result = Sse2.AndNot( Sse2.LoadVector128((UInt64*)(pClsVar1)), Sse2.LoadVector128((UInt64*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndNotUInt64(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndNotUInt64(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) fixed (Vector128<UInt64>* pFld2 = &test._fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((UInt64*)(pFld1)), Sse2.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((UInt64*)(pFld1)), Sse2.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.AndNot( Sse2.LoadVector128((UInt64*)(&test._fld1)), Sse2.LoadVector128((UInt64*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _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<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((ulong)(~left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ulong)(~left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
namespace GoogleApi.Entities.Translate.Common.Enums.Extensions { /// <summary> /// Language Extensions. /// </summary> public static class LanguageExtension { /// <summary> /// Gets the ISO-639-1 code for the specified <see cref="Language"/>. /// </summary> /// <param name="language">The <see cref="Language"/>.</param> /// <returns>The ISO-639-1 code matching the passed <paramref name="language"/>.</returns> public static string ToCode(this Language language) { switch (language) { case Language.Afrikaans: return "af"; case Language.Albanian: return "sq"; case Language.Amharic: return "am"; case Language.Arabic: return "ar"; case Language.Armenian: return "hy"; case Language.Azeerbaijani: return "az"; case Language.Basque: return "eu"; case Language.Belarusian: return "be"; case Language.Bengali: return "bn"; case Language.Bosnian: return "bs"; case Language.Bulgarian: return "bg"; case Language.Catalan: return "ca"; case Language.Cebuano: return "ceb"; case Language.Chichewa: return "ny"; case Language.Chinese: return "zh-CN"; case Language.Chinese_Simplified: return "zh-CN"; case Language.Chinese_Traditional: return "zh-TW"; case Language.Corsican: return "co"; case Language.Croatian: return "hr"; case Language.Czech: return "cs"; case Language.Danish: return "da"; case Language.Dutch: return "nl"; case Language.English: return "en"; case Language.Esperanto: return "eo"; case Language.Estonian: return "et"; case Language.Filipino: return "tl"; case Language.Finnish: return "fi"; case Language.French: return "fr"; case Language.Frisian: return "fy"; case Language.Galician: return "gl"; case Language.Georgian: return "ka"; case Language.German: return "de"; case Language.Greek: return "el"; case Language.Gujarati: return "gu"; case Language.Haitian_Creole: return "ht"; case Language.Hausa: return "ha"; case Language.Hawaiian: return "haw"; case Language.Hebrew: return "iw"; case Language.Hindi: return "hi"; case Language.Hmong: return "hmn"; case Language.Hungarian: return "hu"; case Language.Icelandic: return "is"; case Language.Igbo: return "ig"; case Language.Indonesian: return "id"; case Language.Irish: return "ga"; case Language.Italian: return "it"; case Language.Japanese: return "ja"; case Language.Javanese: return "jw"; case Language.Kannada: return "kn"; case Language.Kazakh: return "kk"; case Language.Khmer: return "km"; case Language.Korean: return "ko"; case Language.Kurdish: return "ku"; case Language.Kyrgyz: return "ky"; case Language.Lao: return "lo"; case Language.Latin: return "la"; case Language.Latvian: return "lv"; case Language.Lithuanian: return "lt"; case Language.Luxembourgish: return "lb"; case Language.Macedonian: return "mk"; case Language.Malagasy: return "mg"; case Language.Malay: return "ms"; case Language.Malayalam: return "ml"; case Language.Maltese: return "mt"; case Language.Maori: return "mi"; case Language.Marathi: return "mr"; case Language.Mongolian: return "mn"; case Language.Burmese: return "my"; case Language.Nepali: return "ne"; case Language.Norwegian: return "no"; case Language.Pashto: return "ps"; case Language.Persian: return "fa"; case Language.Polish: return "pl"; case Language.Portuguese: return "pt"; case Language.Punjabi: return "ma"; case Language.Romanian: return "ro"; case Language.Russian: return "ru"; case Language.Samoan: return "sm"; case Language.Scots_Gaelic: return "gd"; case Language.Serbian: return "sr"; case Language.Sesotho: return "st"; case Language.Shona: return "sn"; case Language.Sindhi: return "sd"; case Language.Sinhala: return "si"; case Language.Slovak: return "sk"; case Language.Slovenian: return "sl"; case Language.Somali: return "so"; case Language.Spanish: return "es"; case Language.Sundanese: return "su"; case Language.Swahili: return "sw"; case Language.Swedish: return "sv"; case Language.Tajik: return "tg"; case Language.Tamil: return "ta"; case Language.Telugu: return "te"; case Language.Thai: return "th"; case Language.Turkish: return "tr"; case Language.Ukrainian: return "uk"; case Language.Urdu: return "ur"; case Language.Uzbek: return "uz"; case Language.Vietnamese: return "vi"; case Language.Welsh: return "cy"; case Language.Xhosa: return "xh"; case Language.Yiddish: return "yi"; case Language.Yoruba: return "yo"; case Language.Zulu: return "zu"; case Language.HebrewOld: return "iw"; case Language.Kinyarwanda: return "rw"; case Language.Odia: return "or"; case Language.Tatar: return "tt"; case Language.Turkmen: return "tk"; case Language.Uyghur: return "ug"; default: return string.Empty; } } /// <summary> /// Determines whether the <see cref="Language"/> passed is comptabile with <see cref="Model.Nmt"/>. /// https://cloud.google.com/translate/docs/languages /// </summary> /// <param name="language">The <see cref="Language"/> to evaluate.</param> /// <returns>True, if compatable with <see cref="Model.Nmt"/>, otherwise false.</returns> public static bool IsValidNmt(this Language language) { switch (language) { case Language.Afrikaans: return true; case Language.Arabic: return true; case Language.Bulgarian: return true; case Language.Chinese_Simplified: return true; case Language.Chinese_Traditional: return true; case Language.Croatian: return true; case Language.Czech: return true; case Language.Danish: return true; case Language.Dutch: return true; case Language.English: return true; case Language.French: return true; case Language.German: return true; case Language.Greek: return true; case Language.Hebrew: return true; case Language.Hindi: return true; case Language.Icelandic: return true; case Language.Indonesian: return true; case Language.Italian: return true; case Language.Japanese: return true; case Language.Korean: return true; case Language.Norwegian: return true; case Language.Polish: return true; case Language.Portuguese: return true; case Language.Romanian: return true; case Language.Russian: return true; case Language.Slovak: return true; case Language.Spanish: return true; case Language.Swedish: return true; case Language.Thai: return true; case Language.Turkish: return true; case Language.Vietnamese: return true; case Language.Albanian: case Language.Amharic: case Language.Armenian: case Language.Azeerbaijani: case Language.Basque: case Language.Belarusian: case Language.Bengali: case Language.Bosnian: case Language.Catalan: case Language.Cebuano: case Language.Chichewa: case Language.Chinese: case Language.Corsican: case Language.Esperanto: case Language.Estonian: case Language.Filipino: case Language.Finnish: case Language.Frisian: case Language.Galician: case Language.Georgian: case Language.Gujarati: case Language.Haitian_Creole: case Language.Hausa: case Language.Hawaiian: case Language.Hmong: case Language.Hungarian: case Language.Igbo: case Language.Irish: case Language.Javanese: case Language.Kannada: case Language.Kazakh: case Language.Khmer: case Language.Kurdish: case Language.Kyrgyz: case Language.Lao: case Language.Latin: case Language.Latvian: case Language.Lithuanian: case Language.Luxembourgish: case Language.Macedonian: case Language.Malagasy: case Language.Malay: case Language.Malayalam: case Language.Maltese: case Language.Maori: case Language.Marathi: case Language.Mongolian: case Language.Burmese: case Language.Nepali: case Language.Pashto: case Language.Persian: case Language.Punjabi: case Language.Samoan: case Language.Scots_Gaelic: case Language.Serbian: case Language.Sesotho: case Language.Shona: case Language.Sindhi: case Language.Sinhala: case Language.Slovenian: case Language.Somali: case Language.Sundanese: case Language.Swahili: case Language.Tajik: case Language.Tamil: case Language.Telugu: case Language.Ukrainian: case Language.Urdu: case Language.Uzbek: case Language.Welsh: case Language.Xhosa: case Language.Yiddish: case Language.Yoruba: case Language.Zulu: case Language.HebrewOld: case Language.Kinyarwanda: case Language.Odia: case Language.Tatar: case Language.Turkmen: case Language.Uyghur: return false; default: return false; } } } }
// <copyright file="FirefoxDriver.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.IO; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Firefox { /// <summary> /// Provides a way to access Firefox to run tests. /// </summary> /// <remarks> /// When the FirefoxDriver object has been instantiated the browser will load. The test can then navigate to the URL under test and /// start your test. /// <para> /// In the case of the FirefoxDriver, you can specify a named profile to be used, or you can let the /// driver create a temporary, anonymous profile. A custom extension allowing the driver to communicate /// to the browser will be installed into the profile. /// </para> /// </remarks> /// <example> /// <code> /// [TestFixture] /// public class Testing /// { /// private IWebDriver driver; /// <para></para> /// [SetUp] /// public void SetUp() /// { /// driver = new FirefoxDriver(); /// } /// <para></para> /// [Test] /// public void TestGoogle() /// { /// driver.Navigate().GoToUrl("http://www.google.co.uk"); /// /* /// * Rest of the test /// */ /// } /// <para></para> /// [TearDown] /// public void TearDown() /// { /// driver.Quit(); /// } /// } /// </code> /// </example> public class FirefoxDriver : RemoteWebDriver { /// <summary> /// The name of the ICapabilities setting to use to define a custom Firefox profile. /// </summary> public static readonly string ProfileCapabilityName = "firefox_profile"; /// <summary> /// The name of the ICapabilities setting to use to define a custom location for the /// Firefox executable. /// </summary> public static readonly string BinaryCapabilityName = "firefox_binary"; /// <summary> /// The default port on which to communicate with the Firefox extension. /// </summary> public static readonly int DefaultPort = 7055; /// <summary> /// Indicates whether native events is enabled by default for this platform. /// </summary> public static readonly bool DefaultEnableNativeEvents = Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows); /// <summary> /// Indicates whether the driver will accept untrusted SSL certificates. /// </summary> public static readonly bool AcceptUntrustedCertificates = true; /// <summary> /// Indicates whether the driver assume the issuer of untrusted certificates is untrusted. /// </summary> public static readonly bool AssumeUntrustedCertificateIssuer = true; /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class. /// </summary> public FirefoxDriver() : this(new FirefoxOptions(null, null, null)) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class for a given profile. /// </summary> /// <param name="profile">A <see cref="FirefoxProfile"/> object representing the profile settings /// to be used in starting Firefox.</param> [Obsolete("FirefoxDriver should not be constructed with a FirefoxProfile object. Use FirefoxOptions instead. This constructor will be removed in a future release.")] public FirefoxDriver(FirefoxProfile profile) : this(new FirefoxOptions(profile, null, null)) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class for a given set of capabilities. /// </summary> /// <param name="capabilities">The <see cref="ICapabilities"/> object containing the desired /// capabilities of this FirefoxDriver.</param> [Obsolete("FirefoxDriver should not be constructed with a raw ICapabilities or DesiredCapabilities object. Use FirefoxOptions instead. This constructor will be removed in a future release.")] public FirefoxDriver(ICapabilities capabilities) : this(CreateOptionsFromCapabilities(capabilities)) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class for a given profile and binary environment. /// </summary> /// <param name="binary">A <see cref="FirefoxBinary"/> object representing the operating system /// environmental settings used when running Firefox.</param> /// <param name="profile">A <see cref="FirefoxProfile"/> object representing the profile settings /// to be used in starting Firefox.</param> [Obsolete("FirefoxDriver should not be constructed with a FirefoxBinary object. Use FirefoxOptions instead. This constructor will be removed in a future release.")] public FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile) : this(new FirefoxOptions(profile, binary, null)) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class for a given profile, binary environment, and timeout value. /// </summary> /// <param name="binary">A <see cref="FirefoxBinary"/> object representing the operating system /// environmental settings used when running Firefox.</param> /// <param name="profile">A <see cref="FirefoxProfile"/> object representing the profile settings /// to be used in starting Firefox.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> [Obsolete("FirefoxDriver should not be constructed with a FirefoxBinary object. Use FirefoxOptions instead. This constructor will be removed in a future release.")] public FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, TimeSpan commandTimeout) : this((FirefoxDriverService)null, new FirefoxOptions(profile, binary, null), commandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified options. Uses the Mozilla-provided Marionette driver implementation. /// </summary> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> public FirefoxDriver(FirefoxOptions options) : this(CreateService(options), options, RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified driver service. Uses the Mozilla-provided Marionette driver implementation. /// </summary> /// <param name="service">The <see cref="FirefoxDriverService"/> used to initialize the driver.</param> public FirefoxDriver(FirefoxDriverService service) : this(service, new FirefoxOptions(), RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path /// to the directory containing geckodriver.exe. /// </summary> /// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param> public FirefoxDriver(string geckoDriverDirectory) : this(geckoDriverDirectory, new FirefoxOptions()) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path /// to the directory containing geckodriver.exe and options. /// </summary> /// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> public FirefoxDriver(string geckoDriverDirectory, FirefoxOptions options) : this(geckoDriverDirectory, options, RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path /// to the directory containing geckodriver.exe, options, and command timeout. /// </summary> /// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> public FirefoxDriver(string geckoDriverDirectory, FirefoxOptions options, TimeSpan commandTimeout) : this(FirefoxDriverService.CreateDefaultService(geckoDriverDirectory), options, commandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified options, driver service, and timeout. Uses the Mozilla-provided Marionette driver implementation. /// </summary> /// <param name="service">The <see cref="FirefoxDriverService"/> to use.</param> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> public FirefoxDriver(FirefoxDriverService service, FirefoxOptions options, TimeSpan commandTimeout) : base(CreateExecutor(service, options, commandTimeout), ConvertOptionsToCapabilities(options)) { } /// <summary> /// Gets or sets the <see cref="IFileDetector"/> responsible for detecting /// sequences of keystrokes representing file paths and names. /// </summary> /// <remarks>The Firefox driver does not allow a file detector to be set, /// as the server component of the Firefox driver only allows uploads from /// the local computer environment. Attempting to set this property has no /// effect, but does not throw an exception. If you are attempting to run /// the Firefox driver remotely, use <see cref="RemoteWebDriver"/> in /// conjunction with a standalone WebDriver server.</remarks> public override IFileDetector FileDetector { get { return base.FileDetector; } set { } } /// <summary> /// Gets a value indicating whether the Firefox driver instance uses /// Mozilla's Marionette implementation. This is a temporary property /// and will be removed when Marionette is available for the release /// channel of Firefox. /// </summary> public bool IsMarionette { get { return this.IsSpecificationCompliant; } } /// <summary> /// In derived classes, the <see cref="PrepareEnvironment"/> method prepares the environment for test execution. /// </summary> protected virtual void PrepareEnvironment() { // Does nothing, but provides a hook for subclasses to do "stuff" } private static ICommandExecutor CreateExecutor(FirefoxDriverService service, FirefoxOptions options, TimeSpan commandTimeout) { ICommandExecutor executor = null; if (options.UseLegacyImplementation) { // Note: If BrowserExecutableLocation is null or empty, the legacy driver // will still do the right thing, and find Firefox in the default location. FirefoxBinary binary = new FirefoxBinary(options.BrowserExecutableLocation); FirefoxProfile profile = options.Profile; if (profile == null) { profile = new FirefoxProfile(); } executor = CreateExtensionConnection(binary, profile, commandTimeout); } else { if (service == null) { throw new ArgumentNullException("service", "You requested a service-based implementation, but passed in a null service object."); } return new DriverServiceCommandExecutor(service, commandTimeout); } return executor; } private static ICommandExecutor CreateExtensionConnection(FirefoxBinary binary, FirefoxProfile profile, TimeSpan commandTimeout) { FirefoxProfile profileToUse = profile; string suggestedProfile = Environment.GetEnvironmentVariable("webdriver.firefox.profile"); if (profileToUse == null && suggestedProfile != null) { profileToUse = new FirefoxProfileManager().GetProfile(suggestedProfile); } else if (profileToUse == null) { profileToUse = new FirefoxProfile(); } FirefoxDriverCommandExecutor executor = new FirefoxDriverCommandExecutor(binary, profileToUse, "localhost", commandTimeout); return executor; } private static ICapabilities ConvertOptionsToCapabilities(FirefoxOptions options) { if (options == null) { throw new ArgumentNullException("options", "options must not be null"); } ICapabilities capabilities = options.ToCapabilities(); if (options.UseLegacyImplementation) { capabilities = RemoveUnneededCapabilities(capabilities); } return capabilities; } private static ICapabilities RemoveUnneededCapabilities(ICapabilities capabilities) { DesiredCapabilities caps = capabilities as DesiredCapabilities; caps.CapabilitiesDictionary.Remove(FirefoxDriver.ProfileCapabilityName); caps.CapabilitiesDictionary.Remove(FirefoxDriver.BinaryCapabilityName); return caps; } private static FirefoxOptions CreateOptionsFromCapabilities(ICapabilities capabilities) { // This is awkward and hacky. To be removed when the legacy driver is retired. FirefoxBinary binary = ExtractBinary(capabilities); FirefoxProfile profile = ExtractProfile(capabilities); DesiredCapabilities desiredCaps = RemoveUnneededCapabilities(capabilities) as DesiredCapabilities; FirefoxOptions options = new FirefoxOptions(profile, binary, desiredCaps); return options; } private static FirefoxBinary ExtractBinary(ICapabilities capabilities) { if (capabilities.GetCapability(BinaryCapabilityName) != null) { string file = capabilities.GetCapability(BinaryCapabilityName).ToString(); return new FirefoxBinary(file); } return new FirefoxBinary(); } private static FirefoxProfile ExtractProfile(ICapabilities capabilities) { FirefoxProfile profile = new FirefoxProfile(); if (capabilities.GetCapability(ProfileCapabilityName) != null) { object raw = capabilities.GetCapability(ProfileCapabilityName); FirefoxProfile rawAsProfile = raw as FirefoxProfile; string rawAsString = raw as string; if (rawAsProfile != null) { profile = rawAsProfile; } else if (rawAsString != null) { try { profile = FirefoxProfile.FromBase64String(rawAsString); } catch (IOException e) { throw new WebDriverException("Unable to create profile from specified string", e); } } } if (capabilities.GetCapability(CapabilityType.Proxy) != null) { Proxy proxy = null; object raw = capabilities.GetCapability(CapabilityType.Proxy); Proxy rawAsProxy = raw as Proxy; Dictionary<string, object> rawAsMap = raw as Dictionary<string, object>; if (rawAsProxy != null) { proxy = rawAsProxy; } else if (rawAsMap != null) { proxy = new Proxy(rawAsMap); } profile.SetProxyPreferences(proxy); } if (capabilities.GetCapability(CapabilityType.AcceptSslCertificates) != null) { bool acceptCerts = (bool)capabilities.GetCapability(CapabilityType.AcceptSslCertificates); profile.AcceptUntrustedCertificates = acceptCerts; } return profile; } private static FirefoxDriverService CreateService(FirefoxOptions options) { if (options != null && options.UseLegacyImplementation) { return null; } return FirefoxDriverService.CreateDefaultService(); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Strategies.Reporting.Algo File: CsvStrategyReport.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Strategies.Reporting { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Ecng.Collections; using StockSharp.Algo.Strategies; using StockSharp.Localization; /// <summary> /// The generator of report on equity in the csv format. /// </summary> public class CsvStrategyReport : StrategyReport { private readonly string _separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator; /// <summary> /// Initializes a new instance of the <see cref="CsvStrategyReport"/>. /// </summary> /// <param name="strategy">The strategy, requiring the report generation.</param> /// <param name="fileName">The name of the file for the report generation in the csv format.</param> public CsvStrategyReport(Strategy strategy, string fileName) : this(new[] { strategy }, fileName) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); } /// <summary> /// Initializes a new instance of the <see cref="CsvStrategyReport"/>. /// </summary> /// <param name="strategies">Strategies, requiring the report generation.</param> /// <param name="fileName">The name of the file for the report generation in the csv format.</param> public CsvStrategyReport(IEnumerable<Strategy> strategies, string fileName) : base(strategies, fileName) { } /// <summary> /// To generate the report. /// </summary> public override void Generate() { using (var writer = new StreamWriter(FileName)) { foreach (var strategy in Strategies) { WriteValues(writer, LocalizedStrings.Strategy, LocalizedStrings.Security, LocalizedStrings.Portfolio, LocalizedStrings.Str1321, LocalizedStrings.Str862, LocalizedStrings.PnL, LocalizedStrings.Str159, LocalizedStrings.Str163, LocalizedStrings.Str161); WriteValues(writer, strategy.Name, strategy.Security != null ? strategy.Security.Id : string.Empty, strategy.Portfolio != null ? strategy.Portfolio.Name : string.Empty, strategy.TotalWorkingTime, strategy.Position, strategy.PnL, strategy.Commission, strategy.Slippage, strategy.Latency); var parameters = strategy.Parameters.SyncGet(c => c.ToArray()); WriteValues(writer, LocalizedStrings.Str1322); WriteValues(writer, parameters.Select(p => (object)p.Name).ToArray()); WriteValues(writer, parameters.Select(p => p.Value is TimeSpan ? Format((TimeSpan)p.Value) : p.Value).ToArray()); var statParameters = strategy.StatisticManager.Parameters.SyncGet(c => c.ToArray()); WriteValues(writer, LocalizedStrings.Str436); WriteValues(writer, statParameters.Select(p => (object)p.Name).ToArray()); WriteValues(writer, statParameters.Select(p => p.Value is TimeSpan ? Format((TimeSpan)p.Value) : p.Value).ToArray()); WriteValues(writer, LocalizedStrings.Orders); WriteValues(writer, LocalizedStrings.Str1190, LocalizedStrings.Transaction, LocalizedStrings.Str128, LocalizedStrings.Time, LocalizedStrings.Price, LocalizedStrings.Str1323, LocalizedStrings.Str1324, LocalizedStrings.State, LocalizedStrings.Str1325, LocalizedStrings.Volume, LocalizedStrings.Type, LocalizedStrings.Str1326, LocalizedStrings.Str1327); foreach (var order in strategy.Orders) { WriteValues(writer, order.Id, order.TransactionId, Format(order.Direction), order.Time, order.Price, order.GetAveragePrice(strategy.Connector), Format(order.State), order.IsMatched() ? LocalizedStrings.Str1328 : (order.IsCanceled() ? LocalizedStrings.Str1329 : string.Empty), order.Balance, order.Volume, Format(order.Type), Format(order.LatencyRegistration), Format(order.LatencyCancellation)); } WriteValues(writer, LocalizedStrings.Str985); WriteValues(writer, LocalizedStrings.Str1192, LocalizedStrings.Transaction, LocalizedStrings.Time, LocalizedStrings.Price, LocalizedStrings.Volume, LocalizedStrings.Str128, LocalizedStrings.Str1190, LocalizedStrings.Str1330, LocalizedStrings.Str163); foreach (var trade in strategy.MyTrades) { WriteValues(writer, trade.Trade.Id, trade.Order.TransactionId, Format(trade.Trade.Time), trade.Trade.Price, trade.Trade.Volume, Format(trade.Order.Direction), trade.Order.Id, strategy.PnLManager.ProcessMessage(trade.ToMessage()).PnL, trade.Slippage); } } } } private void WriteValues(TextWriter writer, params object[] values) { for (var i = 0; i < values.Length; i++) { var value = values[i]; if (value is DateTimeOffset) value = Format((DateTimeOffset)value); else if (value is TimeSpan) value = Format((TimeSpan)value); writer.Write(value); if (i < (values.Length - 1)) writer.Write(_separator); } writer.WriteLine(); } //private void Save() //{ // using (var sw = new StreamWriter(FileName)) // { // sw.WriteLine("; All Trades; Long Trades; Short Trades"); // sw.WriteLine("Net Profit; " + _strategyStatistics.NetProfit + "; " + _strategyStatistics.NetLongProfit + // "; " + _strategyStatistics.NetShortProfit); // sw.WriteLine("Number of Trades; " + _strategyStatistics.NumberOfTrades + "; " + // _strategyStatistics.NumberOfLongTrades + "; " + // _strategyStatistics.NumberOfShortTrades); // sw.WriteLine("Average Profit; " + _strategyStatistics.AverageProfit + "; " + // _strategyStatistics.AverageLongProfit + "; " + _strategyStatistics.AverageShortProfit); // sw.WriteLine("Average Profit %; " + _strategyStatistics.AverageNetProfitPrc + "%; " + // _strategyStatistics.AverageLongNetProfitPrc + "%; " + // _strategyStatistics.AverageShortNetProfitPrc + "%"); // sw.WriteLine(";;;"); // sw.WriteLine("Winning Trades; " + _strategyStatistics.WinningTrades + "; " + // _strategyStatistics.WinningLongTrades + "; " + _strategyStatistics.LosingLongTrades); // sw.WriteLine("Win Rate; " + _strategyStatistics.WinRate + "%; " + _strategyStatistics.WinLongRate + "%; " + // _strategyStatistics.WinShortRate + "%"); // sw.WriteLine("Gross Profit; " + _strategyStatistics.GrossProfit + "; " + _strategyStatistics.GrossLongProfit + // "; " + _strategyStatistics.GrossShortProfit); // sw.WriteLine("Average Profit; " + _strategyStatistics.AverageWinProfit + "; " + // _strategyStatistics.AverageWinLongProfit + "; " + // _strategyStatistics.AverageWinShortProfit); // sw.WriteLine("Average Profit %; " + _strategyStatistics.AverageWinProfitPrc + "%; " + // _strategyStatistics.AverageWinLongProfitPrc + "%; " + // _strategyStatistics.AverageWinShortProfitPrc + "%"); // sw.WriteLine(";;;"); // sw.WriteLine("Losing Trades; " + _strategyStatistics.LosingTrades + "; " + // _strategyStatistics.LosingLongTrades + "; " + _strategyStatistics.LosingShortTrades); // sw.WriteLine("Loss Rate; " + _strategyStatistics.LossRate + "%; " + _strategyStatistics.LossLongRate + "%; " + // _strategyStatistics.LossShortRate + "%"); // sw.WriteLine("Gross Loss; " + _strategyStatistics.GrossLoss + "; " + _strategyStatistics.GrossLongLoss + // "; " + _strategyStatistics.GrossShortLoss); // sw.WriteLine("Average Loss; " + _strategyStatistics.AverageLoss + "; " + _strategyStatistics.AverageLongLoss + // "; " + _strategyStatistics.AverageShortLoss); // sw.WriteLine("Average Loss %; " + _strategyStatistics.AverageLossPrc + "%; " + // _strategyStatistics.AverageLongLossPrc + "%; " + // _strategyStatistics.AverageShortLossPrc + "%"); // sw.WriteLine(";;;"); // sw.WriteLine("Maximum Drawdown; " + _strategyStatistics.MaxDrawdown + "; " + // _strategyStatistics.MaxLongDrawdown + "; " + _strategyStatistics.MaxShortDrawdown); // sw.WriteLine("Profit Factor; " + _strategyStatistics.ProfitFactor + "; " + // _strategyStatistics.ProfitFactorLong + "; " + _strategyStatistics.ProfitFactorShort); // sw.WriteLine("Recovery Factor; " + _strategyStatistics.RecoveryFactor + "; " + // _strategyStatistics.RecoveryFactorLong + "; " + // _strategyStatistics.RecoveryFactorShort); // sw.WriteLine("Payoff Ratio; " + _strategyStatistics.PayoffRatio + "; " + _strategyStatistics.PayoffRatioLong + // "; " + _strategyStatistics.PayoffRatioShort); // sw.WriteLine("Smoothness Factor; " + _strategyStatistics.SmoothnessFactor); // sw.WriteLine(";;;"); // sw.WriteLine(";;;"); // sw.WriteLine(";;;"); // var index = 0; // sw.WriteLine( // "Position; Quantity; Entry Date; Entry Price; Exit Date; Exit Price; Equity; Long; Short; Median;"); // foreach (var kvp in _strategyStatistics.TradePairs) // { // sw.WriteLine( // kvp.Value.FirstTrade.OrderDirection + ";" + // kvp.Value.FirstTrade.Volume + ";" + // kvp.Value.FirstTrade.Time + ";" + // kvp.Value.FirstTrade.Price + ";" + // kvp.Value.SecondTrade.Time + ";" + // kvp.Value.SecondTrade.Price + ";" + // _strategyStatistics.Equity[index] + ";" + // _strategyStatistics.LongEquity[index] + ";" + // _strategyStatistics.ShortEquity[index] + ";" + // _strategyStatistics.EquityMedian[index]); // index++; // } // } //} } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Multiplayer; using osu.Game.Online.Rooms; using osu.Game.Online.Rooms.RoomStatuses; using osu.Game.Overlays; using osu.Game.Rulesets.Osu; using osu.Game.Screens.OnlinePlay.Lounge; using osu.Game.Screens.OnlinePlay.Lounge.Components; using osu.Game.Screens.OnlinePlay.Match; using osu.Game.Tests.Beatmaps; using osuTK; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneDrawableRoom : OsuTestScene { [Cached] protected readonly OverlayColourProvider ColourProvider = new OverlayColourProvider(OverlayColourScheme.Plum); private readonly Bindable<Room> selectedRoom = new Bindable<Room>(); [Test] public void TestMultipleStatuses() { AddStep("create rooms", () => { Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Size = new Vector2(0.9f), Spacing = new Vector2(10), Children = new Drawable[] { createLoungeRoom(new Room { Name = { Value = "Multiplayer room" }, Status = { Value = new RoomStatusOpen() }, EndDate = { Value = DateTimeOffset.Now.AddDays(1) }, Type = { Value = MatchType.HeadToHead }, Playlist = { new PlaylistItem(new TestBeatmap(new OsuRuleset().RulesetInfo) { BeatmapInfo = { StarRating = 2.5 } }.BeatmapInfo) } }), createLoungeRoom(new Room { Name = { Value = "Multiplayer room" }, Status = { Value = new RoomStatusOpen() }, EndDate = { Value = DateTimeOffset.Now.AddDays(1) }, Type = { Value = MatchType.HeadToHead }, Playlist = { new PlaylistItem(new TestBeatmap(new OsuRuleset().RulesetInfo) { BeatmapInfo = { StarRating = 2.5, Metadata = { Artist = "very very very very very very very very very long artist", ArtistUnicode = "very very very very very very very very very long artist", Title = "very very very very very very very very very very very long title", TitleUnicode = "very very very very very very very very very very very long title", } } }.BeatmapInfo) } }), createLoungeRoom(new Room { Name = { Value = "Playlist room with multiple beatmaps" }, Status = { Value = new RoomStatusPlaying() }, EndDate = { Value = DateTimeOffset.Now.AddDays(1) }, Playlist = { new PlaylistItem(new TestBeatmap(new OsuRuleset().RulesetInfo) { BeatmapInfo = { StarRating = 2.5 } }.BeatmapInfo), new PlaylistItem(new TestBeatmap(new OsuRuleset().RulesetInfo) { BeatmapInfo = { StarRating = 4.5 } }.BeatmapInfo) } }), createLoungeRoom(new Room { Name = { Value = "Finished room" }, Status = { Value = new RoomStatusEnded() }, EndDate = { Value = DateTimeOffset.Now }, }), createLoungeRoom(new Room { Name = { Value = "Spotlight room" }, Status = { Value = new RoomStatusOpen() }, Category = { Value = RoomCategory.Spotlight }, }), } }; }); } [Test] public void TestEnableAndDisablePassword() { DrawableRoom drawableRoom = null; Room room = null; AddStep("create room", () => Child = drawableRoom = createLoungeRoom(room = new Room { Name = { Value = "Room with password" }, Status = { Value = new RoomStatusOpen() }, Type = { Value = MatchType.HeadToHead }, })); AddUntilStep("wait for panel load", () => drawableRoom.ChildrenOfType<DrawableRoomParticipantsList>().Any()); AddAssert("password icon hidden", () => Precision.AlmostEquals(0, drawableRoom.ChildrenOfType<DrawableRoom.PasswordProtectedIcon>().Single().Alpha)); AddStep("set password", () => room.Password.Value = "password"); AddAssert("password icon visible", () => Precision.AlmostEquals(1, drawableRoom.ChildrenOfType<DrawableRoom.PasswordProtectedIcon>().Single().Alpha)); AddStep("unset password", () => room.Password.Value = string.Empty); AddAssert("password icon hidden", () => Precision.AlmostEquals(0, drawableRoom.ChildrenOfType<DrawableRoom.PasswordProtectedIcon>().Single().Alpha)); } [Test] public void TestMultiplayerRooms() { AddStep("create rooms", () => Child = new FillFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Direction = FillDirection.Vertical, Spacing = new Vector2(5), Children = new[] { new DrawableMatchRoom(new Room { Name = { Value = "A host-only room" }, QueueMode = { Value = QueueMode.HostOnly }, Type = { Value = MatchType.HeadToHead } }), new DrawableMatchRoom(new Room { Name = { Value = "An all-players, team-versus room" }, QueueMode = { Value = QueueMode.AllPlayers }, Type = { Value = MatchType.TeamVersus } }), new DrawableMatchRoom(new Room { Name = { Value = "A round-robin room" }, QueueMode = { Value = QueueMode.AllPlayersRoundRobin }, Type = { Value = MatchType.HeadToHead } }), } }); } private DrawableRoom createLoungeRoom(Room room) { room.Host.Value ??= new APIUser { Username = "peppy", Id = 2 }; if (room.RecentParticipants.Count == 0) { room.RecentParticipants.AddRange(Enumerable.Range(0, 20).Select(i => new APIUser { Id = i, Username = $"User {i}" })); } return new DrawableLoungeRoom(room) { MatchingFilter = true, SelectedRoom = { BindTarget = selectedRoom } }; } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; using Trisoft.ISHRemote.HelperClasses; using System.Collections.Generic; namespace Trisoft.ISHRemote.Cmdlets.Field { /// <summary> /// <para type="synopsis">The Set-IshMetadataField -IshSession $ishSession cmdlet creates value fields based on the parameters provided When IshFields object is passed through the pipeline then new value field is added according to the parameters provided.</para> /// <para type="description">The Set-IshMetadataField -IshSession $ishSession cmdlet creates value fields based on the parameters provided When IshFields object is passed through the pipeline then new value field is added according to the parameters provided.</para> /// </summary> /// <example> /// <code> /// $ishSession = New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -PSCredential Admin /// Set-IshMetadataField -IshSession $ishSession -Name "USERNAME" /// </code> /// <para>Creates an IshFields structure holding one IshMetadataField with name USERNAME and defaults to level None.</para> /// </example> [Cmdlet(VerbsCommon.Set, "IshMetadataField", SupportsShouldProcess = false)] [OutputType(typeof(IshField), typeof(IshObject), typeof(IshFolder), typeof(IshEvent))] [Alias("Set-IshRequiredCurrentMetadataField")] public sealed class SetIshMetadataField : FieldCmdlet { /// <summary> /// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFieldGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshEventGroup")] [ValidateNotNullOrEmpty] public IshSession IshSession { get; set; } /// <summary> /// <para type="description">The field name</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFieldGroup")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectGroup")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshEventGroup")] public string Name { get; set; } /// <summary> /// <para type="description">The field level</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFieldGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshEventGroup")] public Enumerations.Level Level { get { return _level; } set { _level = value; } } /// <summary> /// <para type="description">The field value</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFieldGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshEventGroup")] public string Value { get; set; } /// <summary> /// <para type="description">The value type</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFieldGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshEventGroup")] public Enumerations.ValueType ValueType { get { return _valueType; } set { _valueType = value; } } /// <summary> /// <para type="description">The fields container object</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipeline = true, ParameterSetName = "IshFieldGroup")] public IshField[] IshField { get; set; } /// <summary> /// <para type="description">The objects container object</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshObjectGroup")] public IshObject[] IshObject { get; set; } /// <summary> /// <para type="description">The objects container object, specialized for folder handling</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshFolderGroup")] public IshFolder[] IshFolder { get; set; } /// <summary> /// <para type="description">The objects container object, specialized for event handling</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshEventGroup")] public IshEvent[] IshEvent { get; set; } #region Private fields /// <summary> /// Private fields to store the parameters and provide a default for non-mandatory parameters /// </summary> private Enumerations.Level _level = Enumerations.Level.None; private Enumerations.ValueType _valueType = Enumerations.ValueType.Value; private IshMetadataField _ishMetadataField = null; private List<IshField> _incomingIshField = new List<IshField>(); #endregion protected override void BeginProcessing() { if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); } if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); } WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}"); base.BeginProcessing(); } protected override void ProcessRecord() { try { Value = (Value == null) ? "" : Value; WriteDebug("name[" + Name + "] level[" + Level + "] value[" + Value + "] valueType[" + ValueType + "]"); _ishMetadataField = new IshMetadataField(Name, Level, ValueType, Value); if (IshField != null) { foreach (IshField ishField in IshField) { _incomingIshField.Add(ishField); } } else if (IshObject != null) { foreach (IshObject ishObject in IshObject) { ishObject.IshFields.AddOrUpdateField(_ishMetadataField, Enumerations.ActionMode.Update); WriteObject(ishObject, true); } } else if (IshFolder != null) { foreach (IshFolder ishFolder in IshFolder) { ishFolder.IshFields.AddOrUpdateField(_ishMetadataField, Enumerations.ActionMode.Update); WriteObject(ishFolder, true); } } else if (IshEvent != null) { foreach (IshEvent ishEvent in IshEvent) { ishEvent.IshFields.AddOrUpdateField(_ishMetadataField, Enumerations.ActionMode.Update); WriteObject(ishEvent, true); } } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } protected override void EndProcessing() { try { if (IshObject == null && IshFolder == null && IshEvent == null) { IshFields ishFields = new IshFields(_incomingIshField); ishFields.AddOrUpdateField(_ishMetadataField, Enumerations.ActionMode.Update); WriteObject(ishFields.Fields(), true); } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } finally { base.EndProcessing(); } } } }
// 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 Xunit; namespace System.Linq.Tests.LegacyTests { public class SingleOrDefaultTests { public class SingleOrDefault003 { private static int SingleOrDefault001() { var q = from x in new[] { 0.12335f } select x; var rst1 = q.SingleOrDefault(); var rst2 = q.SingleOrDefault(); return ((rst1 == rst2) ? 0 : 1); } private static int SingleOrDefault002() { var q = from x in new[] { "" } select x; Func<string, bool> predicate = Functions.IsEmpty; var rst1 = q.SingleOrDefault(predicate); var rst2 = q.SingleOrDefault(predicate); return ((rst1 == rst2) ? 0 : 1); } public static int Main() { int ret = RunTest(SingleOrDefault001) + RunTest(SingleOrDefault002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault1a { // source is of type IList, source is empty public static int Test1a() { int?[] source = { }; int? expected = null; IList<int?> list = source as IList<int?>; if (list == null) return 1; var actual = source.SingleOrDefault(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault1b { // source is of type IList, source has only one element public static int Test1b() { int[] source = { 4 }; int expected = 4; IList<int> list = source as IList<int>; if (list == null) return 1; var actual = source.SingleOrDefault(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault1c { // source is of type IList, source has > 1 element public static int Test1c() { int[] source = { 4, 4, 4, 4, 4 }; IList<int> list = source as IList<int>; if (list == null) return 1; try { var actual = source.SingleOrDefault(); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test1c(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault1d { // source is NOT of type IList, source is empty public static int Test1d() { IEnumerable<int> source = Functions.NumRange(0, 0); int expected = default(int); IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.SingleOrDefault(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1d(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault1e { // source is NOT of type IList, source has only one element public static int Test1e() { IEnumerable<int> source = Functions.NumRange(-5, 1); int expected = -5; IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.SingleOrDefault(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1e(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault1f { // source is NOT of type IList, source has > 1 element public static int Test1f() { IEnumerable<int> source = Functions.NumRange(3, 5); IList<int> list = source as IList<int>; if (list != null) return 1; try { var actual = source.SingleOrDefault(); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test1f(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault2a { // source is empty public static int Test2a() { int[] source = { }; Func<int, bool> predicate = Functions.IsEven; int expected = default(int); var actual = source.SingleOrDefault(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault2b { // source has 1 element and predicate is true public static int Test2b() { int[] source = { 4 }; Func<int, bool> predicate = Functions.IsEven; int expected = 4; var actual = source.SingleOrDefault(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault2c { // source has 1 element and predicate is false public static int Test2c() { int[] source = { 3 }; Func<int, bool> predicate = Functions.IsEven; int expected = default(int); var actual = source.SingleOrDefault(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2c(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault2d { // source has > 1 element and predicate is false for all public static int Test2d() { int[] source = { 3, 1, 7, 9, 13, 19 }; Func<int, bool> predicate = Functions.IsEven; int expected = default(int); var actual = source.SingleOrDefault(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2d(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault2e { // source has > 1 element and predicate is true only for last element public static int Test2e() { int[] source = { 3, 1, 7, 9, 13, 19, 20 }; Func<int, bool> predicate = Functions.IsEven; int expected = 20; var actual = source.SingleOrDefault(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2e(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class SingleOrDefault2f { // source has > 1 element and predicate is true for 1st and 5th element public static int Test2f() { int[] source = { 2, 3, 1, 7, 10, 13, 19, 9 }; Func<int, bool> predicate = Functions.IsEven; try { var actual = source.SingleOrDefault(predicate); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test2f(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
using System; using System.IO; using NAudio.Wave.SampleProviders; namespace NAudio.Wave { /// <summary> /// This class writes WAV data to a .wav file on disk /// </summary> public class WaveFileWriter : Stream { private Stream outStream; private BinaryWriter writer; private long dataSizePos; private long factSampleCountPos; private int dataChunkSize = 0; private WaveFormat format; private string filename; /// <summary> /// Creates a 16 bit Wave File from an ISampleProvider /// BEWARE: the source provider must not return data indefinitely /// </summary> /// <param name="filename">The filename to write to</param> /// <param name="sourceProvider">The source sample provider</param> public static void CreateWaveFile16(string filename, ISampleProvider sourceProvider) { CreateWaveFile(filename, new SampleToWaveProvider16(sourceProvider)); } /// <summary> /// Creates a Wave file by reading all the data from a WaveProvider /// BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished, /// or the Wave File will grow indefinitely. /// </summary> /// <param name="filename">The filename to use</param> /// <param name="sourceProvider">The source WaveProvider</param> public static void CreateWaveFile(string filename, IWaveProvider sourceProvider) { using (var writer = new WaveFileWriter(filename, sourceProvider.WaveFormat)) { long outputLength = 0; var buffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond * 4]; while (true) { int bytesRead = sourceProvider.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { // end of source provider break; } outputLength += bytesRead; if (outputLength > Int32.MaxValue) { throw new InvalidOperationException("WAV File cannot be greater than 2GB. Check that sourceProvider is not an endless stream."); } writer.Write(buffer, 0, bytesRead); } } } /// <summary> /// WaveFileWriter that actually writes to a stream /// </summary> /// <param name="outStream">Stream to be written to</param> /// <param name="format">Wave format to use</param> public WaveFileWriter(Stream outStream, WaveFormat format) { this.outStream = outStream; this.format = format; this.writer = new BinaryWriter(outStream, System.Text.Encoding.UTF8); this.writer.Write(System.Text.Encoding.UTF8.GetBytes("RIFF")); this.writer.Write((int)0); // placeholder this.writer.Write(System.Text.Encoding.UTF8.GetBytes("WAVE")); this.writer.Write(System.Text.Encoding.UTF8.GetBytes("fmt ")); format.Serialize(this.writer); CreateFactChunk(); WriteDataChunkHeader(); } /// <summary> /// Creates a new WaveFileWriter /// </summary> /// <param name="filename">The filename to write to</param> /// <param name="format">The Wave Format of the output data</param> public WaveFileWriter(string filename, WaveFormat format) : this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), format) { this.filename = filename; } private void WriteDataChunkHeader() { this.writer.Write(System.Text.Encoding.UTF8.GetBytes("data")); dataSizePos = this.outStream.Position; this.writer.Write((int)0); // placeholder } private void CreateFactChunk() { if (HasFactChunk()) { this.writer.Write(System.Text.Encoding.UTF8.GetBytes("fact")); this.writer.Write((int)4); factSampleCountPos = this.outStream.Position; this.writer.Write((int)0); // number of samples } } private bool HasFactChunk() { return this.format.Encoding != WaveFormatEncoding.Pcm && this.format.BitsPerSample != 0; } /// <summary> /// The wave file name or null if not applicable /// </summary> public string Filename { get { return filename; } } /// <summary> /// Number of bytes of audio in the data chunk /// </summary> public override long Length { get { return dataChunkSize; } } /// <summary> /// WaveFormat of this wave file /// </summary> public WaveFormat WaveFormat { get { return format; } } /// <summary> /// Returns false: Cannot read from a WaveFileWriter /// </summary> public override bool CanRead { get { return false; } } /// <summary> /// Returns true: Can write to a WaveFileWriter /// </summary> public override bool CanWrite { get { return true; } } /// <summary> /// Returns false: Cannot seek within a WaveFileWriter /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Read is not supported for a WaveFileWriter /// </summary> public override int Read(byte[] buffer, int offset, int count) { throw new InvalidOperationException("Cannot read from a WaveFileWriter"); } /// <summary> /// Seek is not supported for a WaveFileWriter /// </summary> public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException("Cannot seek within a WaveFileWriter"); } /// <summary> /// SetLength is not supported for WaveFileWriter /// </summary> /// <param name="value"></param> public override void SetLength(long value) { throw new InvalidOperationException("Cannot set length of a WaveFileWriter"); } /// <summary> /// Gets the Position in the WaveFile (i.e. number of bytes written so far) /// </summary> public override long Position { get { return dataChunkSize; } set { throw new InvalidOperationException("Repositioning a WaveFileWriter is not supported"); } } /// <summary> /// Appends bytes to the WaveFile (assumes they are already in the correct format) /// </summary> /// <param name="data">the buffer containing the wave data</param> /// <param name="offset">the offset from which to start writing</param> /// <param name="count">the number of bytes to write</param> [Obsolete("Use Write instead")] public void WriteData(byte[] data, int offset, int count) { Write(data, offset, count); } /// <summary> /// Appends bytes to the WaveFile (assumes they are already in the correct format) /// </summary> /// <param name="data">the buffer containing the wave data</param> /// <param name="offset">the offset from which to start writing</param> /// <param name="count">the number of bytes to write</param> public override void Write(byte[] data, int offset, int count) { outStream.Write(data, offset, count); dataChunkSize += count; } private byte[] value24 = new byte[3]; // keep this around to save us creating it every time /// <summary> /// Writes a single sample to the Wave file /// </summary> /// <param name="sample">the sample to write (assumed floating point with 1.0f as max value)</param> public void WriteSample(float sample) { if (WaveFormat.BitsPerSample == 16) { writer.Write((Int16)(Int16.MaxValue * sample)); dataChunkSize += 2; } else if (WaveFormat.BitsPerSample == 24) { var value = BitConverter.GetBytes((Int32)(Int32.MaxValue * sample)); value24[0] = value[1]; value24[1] = value[2]; value24[2] = value[3]; writer.Write(value24); dataChunkSize += 3; } else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.Extensible) { writer.Write(UInt16.MaxValue * (Int32)sample); dataChunkSize += 4; } else if (WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat) { writer.Write(sample); dataChunkSize += 4; } else { throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported"); } } /// <summary> /// Writes 32 bit floating point samples to the Wave file /// They will be converted to the appropriate bit depth depending on the WaveFormat of the WAV file /// </summary> /// <param name="samples">The buffer containing the floating point samples</param> /// <param name="offset">The offset from which to start writing</param> /// <param name="count">The number of floating point samples to write</param> public void WriteSamples(float[] samples, int offset, int count) { for (int n = 0; n < count; n++) { WriteSample(samples[offset + n]); } } /// <summary> /// Writes 16 bit samples to the Wave file /// </summary> /// <param name="samples">The buffer containing the 16 bit samples</param> /// <param name="offset">The offset from which to start writing</param> /// <param name="count">The number of 16 bit samples to write</param> [Obsolete("Use WriteSamples instead")] public void WriteData(short[] samples, int offset, int count) { WriteSamples(samples, offset, count); } /// <summary> /// Writes 16 bit samples to the Wave file /// </summary> /// <param name="samples">The buffer containing the 16 bit samples</param> /// <param name="offset">The offset from which to start writing</param> /// <param name="count">The number of 16 bit samples to write</param> public void WriteSamples(short[] samples, int offset, int count) { // 16 bit PCM data if (WaveFormat.BitsPerSample == 16) { for (int sample = 0; sample < count; sample++) { writer.Write(samples[sample + offset]); } dataChunkSize += (count * 2); } // 24 bit PCM data else if (WaveFormat.BitsPerSample == 24) { byte[] value; for (int sample = 0; sample < count; sample++) { value = BitConverter.GetBytes(UInt16.MaxValue * (Int32)samples[sample + offset]); value24[0] = value[1]; value24[1] = value[2]; value24[2] = value[3]; writer.Write(value24); } dataChunkSize += (count * 3); } // 32 bit PCM data else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.Extensible) { for (int sample = 0; sample < count; sample++) { writer.Write(UInt16.MaxValue * (Int32)samples[sample + offset]); } dataChunkSize += (count * 4); } // IEEE float data else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat) { for (int sample = 0; sample < count; sample++) { writer.Write((float)samples[sample + offset] / (float)(Int16.MaxValue + 1)); } dataChunkSize += (count * 4); } else { throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported"); } } /// <summary> /// Ensures data is written to disk /// </summary> public override void Flush() { writer.Flush(); } #region IDisposable Members /// <summary> /// Actually performs the close,making sure the header contains the correct data /// </summary> /// <param name="disposing">True if called from <see>Dispose</see></param> protected override void Dispose(bool disposing) { if (disposing) { if (outStream != null) { try { UpdateHeader(writer); } finally { // in a finally block as we don't want the FileStream to run its disposer in // the GC thread if the code above caused an IOException (e.g. due to disk full) outStream.Close(); // will close the underlying base stream outStream = null; } } } } /// <summary> /// Updates the header with file size information /// </summary> protected virtual void UpdateHeader(BinaryWriter writer) { this.Flush(); UpdateRiffChunk(writer); UpdateFactChunk(writer); UpdateDataChunk(writer); } private void UpdateDataChunk(BinaryWriter writer) { writer.Seek((int)dataSizePos, SeekOrigin.Begin); writer.Write((int)(dataChunkSize)); } private void UpdateRiffChunk(BinaryWriter writer) { writer.Seek(4, SeekOrigin.Begin); writer.Write((int)(outStream.Length - 8)); } private void UpdateFactChunk(BinaryWriter writer) { if (HasFactChunk()) { int bitsPerSample = (format.BitsPerSample * format.Channels); if (bitsPerSample != 0) { writer.Seek((int)factSampleCountPos, SeekOrigin.Begin); writer.Write((int)((dataChunkSize * 8) / bitsPerSample)); } } } /// <summary> /// Finaliser - should only be called if the user forgot to close this WaveFileWriter /// </summary> ~WaveFileWriter() { System.Diagnostics.Debug.Assert(false, "WaveFileWriter was not disposed"); Dispose(false); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Engine.Maps; using Signum.Engine.DynamicQuery; using Signum.Entities.Processes; using Signum.Entities; using Signum.Engine.Basics; using System.Reflection; using Signum.Utilities.Reflection; using Signum.Entities.Authorization; using System.Linq.Expressions; using Signum.Utilities; using Signum.Entities.Basics; using Signum.Engine.Operations; using System.Threading; namespace Signum.Engine.Processes { public static class PackageLogic { [AutoExpressionField] public static IQueryable<PackageLineEntity> Lines(this PackageEntity p) => As.Expression(() => Database.Query<PackageLineEntity>().Where(pl => pl.Package.Is(p))); public static void AssertStarted(SchemaBuilder sb) { sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null!, true, true))); } public static void Start(SchemaBuilder sb, bool packages, bool packageOperations) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { ProcessLogic.AssertStarted(sb); sb.Settings.AssertImplementedBy((ProcessExceptionLineEntity pel) => pel.Line, typeof(PackageLineEntity)); sb.Include<PackageLineEntity>() .WithQuery(() => pl => new { Entity = pl, pl.Package, pl.Id, pl.Target, pl.Result, pl.FinishTime, }); QueryLogic.Queries.Register(PackageQuery.PackageLineLastProcess, () => from pl in Database.Query<PackageLineEntity>() let p = pl.Package.Entity.LastProcess() select new { Entity = pl, pl.Package, pl.Id, pl.Target, pl.Result, pl.FinishTime, LastProcess = p, Exception = pl.Exception(p), }); QueryLogic.Expressions.Register((PackageEntity p) => p.Lines(), () => ProcessMessage.Lines.NiceToString()); if (packages) { sb.Settings.AssertImplementedBy((PackageLineEntity pl) => pl.Package, typeof(PackageEntity)); sb.Settings.AssertImplementedBy((ProcessEntity pe) => pe.Data, typeof(PackageEntity)); sb.Include<PackageEntity>() .WithQuery(() => pk => new { Entity = pk, pk.Id, pk.Name, }); QueryLogic.Queries.Register(PackageQuery.PackageLastProcess, () => from pk in Database.Query<PackageEntity>() let pe = pk.LastProcess() select new { Entity = pk, pk.Id, pk.Name, NumLines = pk.Lines().Count(), LastProcess = pe, NumErrors = pk.Lines().Count(l => l.Exception(pe) != null), }); ExceptionLogic.DeleteLogs += ExceptionLogic_DeletePackages<PackageEntity>; } if (packageOperations) { sb.Settings.AssertImplementedBy((PackageLineEntity pl) => pl.Package, typeof(PackageOperationEntity)); sb.Settings.AssertImplementedBy((ProcessEntity pe) => pe.Data, typeof(PackageOperationEntity)); sb.Include<PackageOperationEntity>() .WithQuery(() => pk => new { Entity = pk, pk.Id, pk.Name, pk.Operation, }); QueryLogic.Queries.Register(PackageQuery.PackageOperationLastProcess, () => from p in Database.Query<PackageOperationEntity>() let pe = p.LastProcess() select new { Entity = p, p.Id, p.Name, p.Operation, NumLines = p.Lines().Count(), LastProcess = pe, NumErrors = p.Lines().Count(l => l.Exception(pe) != null), }); ProcessLogic.Register(PackageOperationProcess.PackageOperation, new PackageOperationAlgorithm()); ExceptionLogic.DeleteLogs += ExceptionLogic_DeletePackages<PackageOperationEntity>; } } } public static void ExceptionLogic_DeletePackages<T>(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token) where T : PackageEntity { var query = Database.Query<T>().Where(pack => !Database.Query<ProcessEntity>().Any(pr => pr.Data == pack)); query.SelectMany(a => a.Lines()).UnsafeDeleteChunksLog(parameters, sb, token); query.Where(a => !a.Lines().Any()).UnsafeDeleteChunksLog(parameters, sb, token); } public static PackageEntity CreateLines(this PackageEntity package, IEnumerable<Lite<IEntity>> lites) { package.Save(); int inserts = lites.GroupBy(a => a.EntityType).Sum(gr => gr.GroupsOf(100).Sum(gr2 => giInsertPackageLines.GetInvoker(gr.Key)(package, gr2))); return package; } public static PackageEntity CreateLines(this PackageEntity package, IEnumerable<IEntity> entities) { package.Save(); int inserts = entities.GroupBy(a => a.GetType()).Sum(gr => gr.GroupsOf(100).Sum(gr2 => giInsertPackageLines.GetInvoker(gr.Key)(package, gr2.Select(a => a.ToLite())))); return package; } public static PackageEntity CreateLinesQuery<T>(this PackageEntity package, IQueryable<T> entities) where T : Entity { package.Save(); entities.UnsafeInsert(e => new PackageLineEntity { Package = package.ToLite(), Target = e, }); return package; } static readonly GenericInvoker<Func<PackageEntity, IEnumerable<Lite<IEntity>>, int>> giInsertPackageLines = new GenericInvoker<Func<PackageEntity, IEnumerable<Lite<IEntity>>, int>>( (package, lites) => InsertPackageLines<Entity>(package, lites)); static int InsertPackageLines<T>(PackageEntity package, IEnumerable<Lite<IEntity>> lites) where T :Entity { return Database.Query<T>().Where(p => lites.Contains(p.ToLite())).UnsafeInsert(p => new PackageLineEntity { Package = package.ToLite(), Target = p, }); } public static ProcessEntity CreatePackageOperation(IEnumerable<Lite<IEntity>> entities, OperationSymbol operation, params object?[]? operationArgs) { return ProcessLogic.Create(PackageOperationProcess.PackageOperation, new PackageOperationEntity() { Operation = operation, OperationArgs = operationArgs, }.CreateLines(entities)); } public static void RegisterUserTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition) { TypeConditionLogic.RegisterCompile<ProcessEntity>(typeCondition, pe => pe.User.Is(UserEntity.Current)); TypeConditionLogic.Register<PackageOperationEntity>(typeCondition, po => Database.Query<ProcessEntity>().WhereCondition(typeCondition).Any(pe => pe.Data == po)); TypeConditionLogic.Register<PackageLineEntity>(typeCondition, pl => ((PackageOperationEntity)pl.Package.Entity).InCondition(typeCondition)); } } public class PackageOperationAlgorithm : IProcessAlgorithm { public void Execute(ExecutingProcess executingProcess) { PackageOperationEntity package = (PackageOperationEntity)executingProcess.Data!; OperationSymbol operationSymbol = package.Operation; var args = package.OperationArgs; executingProcess.ForEachLine(package.Lines().Where(a => a.FinishTime == null), line => { OperationType operationType = OperationLogic.OperationType(line.Target.GetType(), operationSymbol); switch (operationType) { case OperationType.Execute: OperationLogic.ServiceExecute(line.Target, operationSymbol, args); break; case OperationType.Delete: OperationLogic.ServiceDelete(line.Target, operationSymbol, args); break; case OperationType.ConstructorFrom: { var result = OperationLogic.ServiceConstructFrom(line.Target, operationSymbol, args); line.Result = result.ToLite(); } break; default: throw new InvalidOperationException("Unexpected operation type {0}".FormatWith(operationType)); } line.FinishTime = TimeZoneManager.Now; line.Save(); }); } } public class PackageDeleteAlgorithm<T> : IProcessAlgorithm where T : class, IEntity { public DeleteSymbol<T> DeleteSymbol { get; private set; } public PackageDeleteAlgorithm(DeleteSymbol<T> deleteSymbol) { this.DeleteSymbol = deleteSymbol ?? throw new ArgumentNullException("operatonKey"); } public virtual void Execute(ExecutingProcess executingProcess) { PackageEntity package = (PackageEntity)executingProcess.Data!; var args = package.OperationArgs; executingProcess.ForEachLine(package.Lines().Where(a => a.FinishTime == null), line => { ((T)(IEntity)line.Target).Delete(DeleteSymbol, args); line.FinishTime = TimeZoneManager.Now; line.Save(); }); } } public class PackageSave<T> : IProcessAlgorithm where T : class, IEntity { public virtual void Execute(ExecutingProcess executingProcess) { PackageEntity package = (PackageEntity)executingProcess.Data!; var args = package.OperationArgs; using (OperationLogic.AllowSave<T>()) executingProcess.ForEachLine(package.Lines().Where(a => a.FinishTime == null), line => { ((T)(object)line.Target).Save(); line.FinishTime = TimeZoneManager.Now; line.Save(); }); } } public class PackageExecuteAlgorithm<T> : IProcessAlgorithm where T : class, IEntity { public ExecuteSymbol<T> Symbol { get; private set; } public PackageExecuteAlgorithm(ExecuteSymbol<T> symbol) { this.Symbol = symbol ?? throw new ArgumentNullException("operationKey"); } public virtual void Execute(ExecutingProcess executingProcess) { PackageEntity package = (PackageEntity)executingProcess.Data!; var args = package.OperationArgs; executingProcess.ForEachLine(package.Lines().Where(a => a.FinishTime == null), line => { ((T)(object)line.Target).Execute(Symbol, args); line.FinishTime = TimeZoneManager.Now; line.Save(); }); } } public class PackageConstructFromAlgorithm<F, T> : IProcessAlgorithm where T : class, IEntity where F : class, IEntity { public ConstructSymbol<T>.From<F> Symbol { get; private set; } public PackageConstructFromAlgorithm(ConstructSymbol<T>.From<F> symbol) { this.Symbol = symbol; } public virtual void Execute(ExecutingProcess executingProcess) { PackageEntity package = (PackageEntity)executingProcess.Data!; var args = package.OperationArgs; executingProcess.ForEachLine(package.Lines().Where(a => a.FinishTime == null), line => { var result = ((F)(object)line.Target).ConstructFrom(Symbol, args); if (result.IsNew) result.Save(); line.Result = ((Entity)(IEntity)result).ToLite(); line.FinishTime = TimeZoneManager.Now; line.Save(); }); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { #if !NET35 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NLog.Config; using NLog.Targets; using Xunit; public class AsyncTaskTargetTest : NLogTestBase { [Target("AsyncTaskTest")] class AsyncTaskTestTarget : AsyncTaskTarget { private readonly AutoResetEvent _writeEvent = new AutoResetEvent(false); internal readonly ConcurrentQueue<string> Logs = new ConcurrentQueue<string>(); internal int WriteTasks => _writeTasks; protected int _writeTasks; public Type RequiredDependency { get; set; } public bool WaitForWriteEvent(int timeoutMilliseconds = 1000) { if (_writeEvent.WaitOne(TimeSpan.FromMilliseconds(timeoutMilliseconds))) { Thread.Sleep(25); return true; } return false; } protected override void InitializeTarget() { base.InitializeTarget(); if (RequiredDependency != null) { try { var resolveServiceMethod = typeof(Target).GetMethod(nameof(ResolveService), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); resolveServiceMethod = resolveServiceMethod.MakeGenericMethod(new[] { RequiredDependency }); resolveServiceMethod.Invoke(this, NLog.Internal.ArrayHelper.Empty<object>()); } catch (System.Reflection.TargetInvocationException ex) { throw ex.InnerException; } } } protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) { Interlocked.Increment(ref _writeTasks); return WriteLogQueue(logEvent, token); } protected async Task WriteLogQueue(LogEventInfo logEvent, CancellationToken token) { if (logEvent.Message == "EXCEPTION") throw new InvalidOperationException("AsyncTaskTargetTest Failure"); else if (logEvent.Message == "ASYNCEXCEPTION") await Task.Delay(10, token).ContinueWith((t) => { throw new InvalidOperationException("AsyncTaskTargetTest Async Failure"); }).ConfigureAwait(false); else if (logEvent.Message == "TIMEOUT") await Task.Delay(15000, token).ConfigureAwait(false); else { if (logEvent.Message == "SLEEP") Task.Delay(5000, token).GetAwaiter().GetResult(); await Task.Delay(10, token).ContinueWith((t) => Logs.Enqueue(RenderLogEvent(Layout, logEvent)), token).ContinueWith(async (t) => await Task.Delay(10).ConfigureAwait(false)).ConfigureAwait(false); } _writeEvent.Set(); } } class AsyncTaskBatchTestTarget : AsyncTaskTestTarget { protected override async Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken) { Interlocked.Increment(ref _writeTasks); for (int i = 0; i < logEvents.Count; ++i) await WriteLogQueue(logEvents[i], cancellationToken); } protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken) { throw new NotImplementedException(); } } class AsyncTaskBatchExceptionTestTarget : AsyncTaskTestTarget { public List<int> retryDelayLog = new List<int>(); protected override async Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken) { await Task.Delay(50); throw new Exception("Failed to write to message queue, or something"); } protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken) { throw new NotImplementedException(); } protected override bool RetryFailedAsyncTask(Exception exception, CancellationToken cancellationToken, int retryCountRemaining, out TimeSpan retryDelay) { var shouldRetry = base.RetryFailedAsyncTask(exception, cancellationToken, retryCountRemaining, out retryDelay); retryDelayLog.Add((int)retryDelay.TotalMilliseconds); return shouldRetry; } } [Fact] public void AsyncTaskTarget_TestLogging() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${threadid}|${level}|${message}|${mdlc:item=Test}" }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); NLog.Common.InternalLogger.LogLevel = LogLevel.Off; int managedThreadId = 0; Task task; using (ScopeContext.PushProperty("Test", 42)) { task = Task.Run(() => { managedThreadId = Thread.CurrentThread.ManagedThreadId; logger.Trace("TTT"); logger.Debug("DDD"); logger.Info("III"); logger.Warn("WWW"); logger.Error("EEE"); logger.Fatal("FFF"); }); } Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); task.Wait(); LogManager.Flush(); Assert.Equal(6, asyncTarget.Logs.Count); while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { Assert.Equal(0, logEventMessage.IndexOf(managedThreadId.ToString() + "|")); Assert.EndsWith("|42", logEventMessage); } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_SkipAsyncTargetWrapper() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets async='true'> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; Assert.NotNull(logFactory.Configuration.FindTargetByName<AsyncTaskTestTarget>("asyncDebug")); Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.AsyncTargetWrapper>("debug")); } [Fact] public void AsyncTaskTarget_SkipDefaultAsyncWrapper() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='AsyncWrapper' /> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; Assert.NotNull(logFactory.Configuration.FindTargetByName<AsyncTaskTestTarget>("asyncDebug")); Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.AsyncTargetWrapper>("debug")); } [Fact] public void AsyncTaskTarget_AllowDefaultBufferWrapper() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='BufferingWrapper' /> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.BufferingTargetWrapper>("asyncDebug")); Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.BufferingTargetWrapper>("debug")); } [Fact] public void AsyncTaskTarget_TestAsyncException() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 50 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "ASYNCEXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestTimeout() { RetryingIntegrationTest(3, () => { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", TaskTimeoutSeconds = 1 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); logger.Trace("TTT"); logger.Debug("TIMEOUT"); logger.Info("III"); logger.Warn("WWW"); logger.Error("EEE"); logger.Fatal("FFF"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(5, asyncTarget.Logs.Count); while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { Assert.Equal(-1, logEventMessage.IndexOf("Debug|")); } LogManager.Configuration = null; }); } [Fact] public void AsyncTaskTarget_TestRetryAsyncException() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 10, RetryCount = 3 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "ASYNCEXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 4, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestRetryException() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 10, RetryCount = 3 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "EXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 4, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestBatchWriting() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", BatchSize = 3, TaskDelayMilliseconds = 10 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal / 2, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.Equal(ordinal++, logLevel.Ordinal); } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestBatchRetryTimings() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchExceptionTestTarget { Layout = "${level}", BatchSize = 10, TaskDelayMilliseconds = 10, RetryCount = 5, RetryDelayMilliseconds = 3 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); logger.Log(LogLevel.Info, "test"); LogManager.Flush(); // The zero at the end of the array is used when there will be no more retries. Assert.Equal(new[] { 3, 6, 12, 24, 48, 0 }, asyncTarget.retryDelayLog); LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestFakeBatchWriting() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", BatchSize = 3, TaskDelayMilliseconds = 10 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.Equal(ordinal++, logLevel.Ordinal); } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestSlowBatchWriting() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 200 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); DateTime utcNow = DateTime.UtcNow; logger.Log(LogLevel.Info, LogLevel.Info.ToString().ToUpperInvariant()); logger.Log(LogLevel.Fatal, "SLEEP"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.Single(asyncTarget.Logs); logger.Log(LogLevel.Error, LogLevel.Error.ToString().ToUpperInvariant()); asyncTarget.Dispose(); // Trigger fast shutdown LogManager.Configuration = null; TimeSpan shutdownTime = DateTime.UtcNow - utcNow; Assert.True(shutdownTime < TimeSpan.FromSeconds(4), $"Shutdown took {shutdownTime.TotalMilliseconds} msec"); } [Fact] public void AsyncTaskTarget_TestThrottleOnTaskDelay() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 50, BatchSize = 10, }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 10; ++j) { logger.Log(LogLevel.Info, i.ToString()); Thread.Sleep(20); } Assert.True(asyncTarget.WaitForWriteEvent()); } Assert.True(asyncTarget.Logs.Count > 25, $"{asyncTarget.Logs.Count} LogEvents are too few after {asyncTarget.WriteTasks} writes"); Assert.True(asyncTarget.WriteTasks < 20, $"{asyncTarget.WriteTasks} writes are too many."); } [Fact] public void AsynTaskTarget_AutoFlushWrapper() { var logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 5000, BatchSize = 10, }; var autoFlush = new NLog.Targets.Wrappers.AutoFlushTargetWrapper("autoflush", asyncTarget); autoFlush.Condition = "level > LogLevel.Warn"; SimpleConfigurator.ConfigureForTargetLogging(autoFlush, LogLevel.Trace); logger.Info("Hello World"); Assert.Empty(asyncTarget.Logs); logger.Error("Goodbye World"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); } [Fact] public void AsyncTaskTarget_FlushWhenBlocked() { // Arrange var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 10000, BatchSize = 10, QueueLimit = 10, OverflowAction = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Block, }; logConfig.AddRuleForAllLevels(asyncTarget); logFactory.Configuration = logConfig; var logger = logFactory.GetLogger(nameof(AsyncTaskTarget_FlushWhenBlocked)); // Act for (int i = 0; i < 10; ++i) logger.Info("Testing {0}", i); logFactory.Flush(TimeSpan.FromSeconds(5)); // Assert Assert.Equal(1, asyncTarget.WriteTasks); } [Fact] public void AsyncTaskTarget_MissingDependency_EnqueueLogEvents() { using (new NoThrowNLogExceptions()) { // Arrange var logFactory = new LogFactory(); logFactory.ThrowConfigExceptions = true; var logConfig = new LoggingConfiguration(logFactory); var asyncTarget = new AsyncTaskTestTarget() { Name = "asynctarget", RequiredDependency = typeof(IMisingDependencyClass) }; logConfig.AddRuleForAllLevels(asyncTarget); logFactory.Configuration = logConfig; var logger = logFactory.GetLogger(nameof(AsyncTaskTarget_MissingDependency_EnqueueLogEvents)); // Act logger.Info("Hello World"); Assert.False(asyncTarget.WaitForWriteEvent(50)); logFactory.ServiceRepository.RegisterService(typeof(IMisingDependencyClass), new MisingDependencyClass()); // Assert Assert.True(asyncTarget.WaitForWriteEvent()); } } private interface IMisingDependencyClass { } private class MisingDependencyClass : IMisingDependencyClass { } } #endif }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using NodaTime; using QuantConnect.Benchmarks; using QuantConnect.Brokerages; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Notifications; using QuantConnect.Orders; using QuantConnect.Scheduling; using QuantConnect.Securities; using System.Collections.Concurrent; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Securities.Future; using QuantConnect.Securities.Option; using QuantConnect.Storage; namespace QuantConnect.Interfaces { /// <summary> /// Defines an event fired from within an algorithm instance. /// </summary> /// <typeparam name="T">The event type</typeparam> /// <param name="algorithm">The algorithm that fired the event</param> /// <param name="eventData">The event data</param> public delegate void AlgorithmEvent<in T>(IAlgorithm algorithm, T eventData); /// <summary> /// Interface for QuantConnect algorithm implementations. All algorithms must implement these /// basic members to allow interaction with the Lean Backtesting Engine. /// </summary> public interface IAlgorithm : ISecurityInitializerProvider, IAccountCurrencyProvider { /// <summary> /// Event fired when an algorithm generates a insight /// </summary> event AlgorithmEvent<GeneratedInsightsCollection> InsightsGenerated; /// <summary> /// Gets the time keeper instance /// </summary> ITimeKeeper TimeKeeper { get; } /// <summary> /// Data subscription manager controls the information and subscriptions the algorithms recieves. /// Subscription configurations can be added through the Subscription Manager. /// </summary> SubscriptionManager SubscriptionManager { get; } /// <summary> /// Security object collection class stores an array of objects representing representing each security/asset /// we have a subscription for. /// </summary> /// <remarks>It is an IDictionary implementation and can be indexed by symbol</remarks> SecurityManager Securities { get; } /// <summary> /// Gets the collection of universes for the algorithm /// </summary> UniverseManager UniverseManager { get; } /// <summary> /// Security portfolio management class provides wrapper and helper methods for the Security.Holdings class such as /// IsLong, IsShort, TotalProfit /// </summary> /// <remarks>Portfolio is a wrapper and helper class encapsulating the Securities[].Holdings objects</remarks> SecurityPortfolioManager Portfolio { get; } /// <summary> /// Security transaction manager class controls the store and processing of orders. /// </summary> /// <remarks>The orders and their associated events are accessible here. When a new OrderEvent is recieved the algorithm portfolio is updated.</remarks> SecurityTransactionManager Transactions { get; } /// <summary> /// Gets the brokerage model used to emulate a real brokerage /// </summary> IBrokerageModel BrokerageModel { get; } /// <summary> /// Gets the brokerage message handler used to decide what to do /// with each message sent from the brokerage /// </summary> IBrokerageMessageHandler BrokerageMessageHandler { get; set; } /// <summary> /// Notification manager for storing and processing live event messages /// </summary> NotificationManager Notify { get; } /// <summary> /// Gets schedule manager for adding/removing scheduled events /// </summary> ScheduleManager Schedule { get; } /// <summary> /// Gets or sets the history provider for the algorithm /// </summary> IHistoryProvider HistoryProvider { get; set; } /// <summary> /// Gets or sets the current status of the algorithm /// </summary> AlgorithmStatus Status { get; set; } /// <summary> /// Gets whether or not this algorithm is still warming up /// </summary> bool IsWarmingUp { get; } /// <summary> /// Public name for the algorithm. /// </summary> /// <remarks>Not currently used but preserved for API integrity</remarks> string Name { get; set; } /// <summary> /// Current date/time in the algorithm's local time zone /// </summary> DateTime Time { get; } /// <summary> /// Gets the time zone of the algorithm /// </summary> DateTimeZone TimeZone { get; } /// <summary> /// Current date/time in UTC. /// </summary> DateTime UtcTime { get; } /// <summary> /// Algorithm start date for backtesting, set by the SetStartDate methods. /// </summary> DateTime StartDate { get; } /// <summary> /// Get Requested Backtest End Date /// </summary> DateTime EndDate { get; } /// <summary> /// AlgorithmId for the backtest /// </summary> string AlgorithmId { get; } /// <summary> /// Algorithm is running on a live server. /// </summary> bool LiveMode { get; } /// <summary> /// Gets the subscription settings to be used when adding securities via universe selection /// </summary> UniverseSettings UniverseSettings { get; } /// <summary> /// Debug messages from the strategy: /// </summary> ConcurrentQueue<string> DebugMessages { get; } /// <summary> /// Error messages from the strategy: /// </summary> ConcurrentQueue<string> ErrorMessages { get; } /// <summary> /// Log messages from the strategy: /// </summary> ConcurrentQueue<string> LogMessages { get; } /// <summary> /// Gets the run time error from the algorithm, or null if none was encountered. /// </summary> Exception RunTimeError { get; set; } /// <summary> /// Customizable dynamic statistics displayed during live trading: /// </summary> ConcurrentDictionary<string, string> RuntimeStatistics { get; } /// <summary> /// Gets the function used to define the benchmark. This function will return /// the value of the benchmark at a requested date/time /// </summary> IBenchmark Benchmark { get; } /// <summary> /// Gets the Trade Builder to generate trades from executions /// </summary> ITradeBuilder TradeBuilder { get; } /// <summary> /// Gets the user settings for the algorithm /// </summary> IAlgorithmSettings Settings { get; } /// <summary> /// Gets the option chain provider, used to get the list of option contracts for an underlying symbol /// </summary> IOptionChainProvider OptionChainProvider { get; } /// <summary> /// Gets the future chain provider, used to get the list of future contracts for an underlying symbol /// </summary> IFutureChainProvider FutureChainProvider { get; } /// <summary> /// Gets the object store, used for persistence /// </summary> ObjectStore ObjectStore { get; } /// <summary> /// Returns the current Slice object /// </summary> Slice CurrentSlice { get; } /// <summary> /// Initialise the Algorithm and Prepare Required Data: /// </summary> void Initialize(); /// <summary> /// Called by setup handlers after Initialize and allows the algorithm a chance to organize /// the data gather in the Initialize method /// </summary> void PostInitialize(); /// <summary> /// Called when the algorithm has completed initialization and warm up. /// </summary> void OnWarmupFinished(); /// <summary> /// Gets the parameter with the specified name. If a parameter /// with the specified name does not exist, null is returned /// </summary> /// <param name="name">The name of the parameter to get</param> /// <returns>The value of the specified parameter, or null if not found</returns> string GetParameter(string name); /// <summary> /// Sets the parameters from the dictionary /// </summary> /// <param name="parameters">Dictionary containing the parameter names to values</param> void SetParameters(Dictionary<string, string> parameters); /// <summary> /// Checks if the provided asset is shortable at the brokerage /// </summary> /// <param name="symbol">Symbol to check if it is shortable</param> /// <param name="quantity">Order quantity to check if shortable</param> /// <returns></returns> bool Shortable(Symbol symbol, decimal quantity); /// <summary> /// Sets the brokerage model used to resolve transaction models, settlement models, /// and brokerage specified ordering behaviors. /// </summary> /// <param name="brokerageModel">The brokerage model used to emulate the real /// brokerage</param> void SetBrokerageModel(IBrokerageModel brokerageModel); // <summary> // v1.0 Handler for Tick Events [DEPRECATED June-2014] // </summary> // <param name="ticks">Tick Data Packet</param> //void OnTick(Dictionary<string, List<Tick>> ticks); // <summary> // v1.0 Handler for TradeBar Events [DEPRECATED June-2014] // </summary> // <param name="tradebars">TradeBar Data Packet</param> //void OnTradeBar(Dictionary<string, TradeBar> tradebars); // <summary> // v2.0 Handler for Generic Data Events // </summary> //void OnData(Ticks ticks); //void OnData(TradeBars tradebars); /// <summary> /// v3.0 Handler for all data types /// </summary> /// <param name="slice">The current slice of data</param> void OnData(Slice slice); /// <summary> /// Used to send data updates to algorithm framework models /// </summary> /// <param name="slice">The current data slice</param> void OnFrameworkData(Slice slice); /// <summary> /// Event fired each time that we add/remove securities from the data feed /// </summary> /// <param name="changes">Security additions/removals for this time step</param> void OnSecuritiesChanged(SecurityChanges changes); /// <summary> /// Used to send security changes to algorithm framework models /// </summary> /// <param name="changes">Security additions/removals for this time step</param> void OnFrameworkSecuritiesChanged(SecurityChanges changes); /// <summary> /// Invoked at the end of every time step. This allows the algorithm /// to process events before advancing to the next time step. /// </summary> void OnEndOfTimeStep(); /// <summary> /// Send debug message /// </summary> /// <param name="message"></param> void Debug(string message); /// <summary> /// Save entry to the Log /// </summary> /// <param name="message">String message</param> void Log(string message); /// <summary> /// Send an error message for the algorithm /// </summary> /// <param name="message">String message</param> void Error(string message); /// <summary> /// Margin call event handler. This method is called right before the margin call orders are placed in the market. /// </summary> /// <param name="requests">The orders to be executed to bring this algorithm within margin limits</param> void OnMarginCall(List<SubmitOrderRequest> requests); /// <summary> /// Margin call warning event handler. This method is called when Portfolio.MarginRemaining is under 5% of your Portfolio.TotalPortfolioValue /// </summary> void OnMarginCallWarning(); /// <summary> /// Call this method at the end of each day of data. /// </summary> /// <remarks>Deprecated because different assets have different market close times, /// and because Python does not support two methods with the same name</remarks> [Obsolete("This method is deprecated. Please use this overload: OnEndOfDay(Symbol symbol)")] void OnEndOfDay(); /// <summary> /// Call this method at the end of each day of data. /// </summary> void OnEndOfDay(Symbol symbol); /// <summary> /// Call this event at the end of the algorithm running. /// </summary> void OnEndOfAlgorithm(); /// <summary> /// EXPERTS ONLY:: [-!-Async Code-!-] /// New order event handler: on order status changes (filled, partially filled, cancelled etc). /// </summary> /// <param name="newEvent">Event information</param> void OnOrderEvent(OrderEvent newEvent); /// <summary> /// Option assignment event handler. On an option assignment event for short legs the resulting information is passed to this method. /// </summary> /// <param name="assignmentEvent">Option exercise event details containing details of the assignment</param> /// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks> void OnAssignmentOrderEvent(OrderEvent assignmentEvent); /// <summary> /// Brokerage message event handler. This method is called for all types of brokerage messages. /// </summary> void OnBrokerageMessage(BrokerageMessageEvent messageEvent); /// <summary> /// Brokerage disconnected event handler. This method is called when the brokerage connection is lost. /// </summary> void OnBrokerageDisconnect(); /// <summary> /// Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection. /// </summary> void OnBrokerageReconnect(); /// <summary> /// Set the DateTime Frontier: This is the master time and is /// </summary> /// <param name="time"></param> void SetDateTime(DateTime time); /// <summary> /// Set the start date for the backtest /// </summary> /// <param name="start">Datetime Start date for backtest</param> /// <remarks>Must be less than end date and within data available</remarks> void SetStartDate(DateTime start); /// <summary> /// Set the end date for a backtest. /// </summary> /// <param name="end">Datetime value for end date</param> /// <remarks>Must be greater than the start date</remarks> void SetEndDate(DateTime end); /// <summary> /// Set the algorithm Id for this backtest or live run. This can be used to identify the order and equity records. /// </summary> /// <param name="algorithmId">unique 32 character identifier for backtest or live server</param> void SetAlgorithmId(string algorithmId); /// <summary> /// Set the algorithm as initialized and locked. No more cash or security changes. /// </summary> void SetLocked(); /// <summary> /// Gets whether or not this algorithm has been locked and fully initialized /// </summary> bool GetLocked(); /// <summary> /// Add a Chart object to algorithm collection /// </summary> /// <param name="chart">Chart object to add to collection.</param> void AddChart(Chart chart); /// <summary> /// Get the chart updates since the last request: /// </summary> /// <param name="clearChartData"></param> /// <returns>List of Chart Updates</returns> List<Chart> GetChartUpdates(bool clearChartData = false); /// <summary> /// Set a required SecurityType-symbol and resolution for algorithm /// </summary> /// <param name="securityType">SecurityType Enum: Equity, Commodity, FOREX or Future</param> /// <param name="symbol">Symbol Representation of the MarketType, e.g. AAPL</param> /// <param name="resolution">Resolution of the MarketType required: MarketData, Second or Minute</param> /// <param name="market">The market the requested security belongs to, such as 'usa' or 'fxcm'</param> /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice.</param> /// <param name="leverage">leverage for this security</param> /// <param name="extendedMarketHours">ExtendedMarketHours send in data from 4am - 8pm, not used for FOREX</param> Security AddSecurity(SecurityType securityType, string symbol, Resolution? resolution, string market, bool fillDataForward, decimal leverage, bool extendedMarketHours); /// <summary> /// Creates and adds a new single <see cref="Future"/> contract to the algorithm /// </summary> /// <param name="symbol">The futures contract symbol</param> /// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param> /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param> /// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param> /// <returns>The new <see cref="Future"/> security</returns> Future AddFutureContract(Symbol symbol, Resolution? resolution = null, bool fillDataForward = true, decimal leverage = 0m); /// <summary> /// Creates and adds a new single <see cref="Option"/> contract to the algorithm /// </summary> /// <param name="symbol">The option contract symbol</param> /// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param> /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param> /// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param> /// <returns>The new <see cref="Option"/> security</returns> Option AddOptionContract(Symbol symbol, Resolution? resolution = null, bool fillDataForward = true, decimal leverage = 0m); /// <summary> /// Removes the security with the specified symbol. This will cancel all /// open orders and then liquidate any existing holdings /// </summary> /// <param name="symbol">The symbol of the security to be removed</param> bool RemoveSecurity(Symbol symbol); /// <summary> /// Sets the account currency cash symbol this algorithm is to manage. /// </summary> /// <remarks>Has to be called during <see cref="Initialize"/> before /// calling <see cref="SetCash(decimal)"/> or adding any <see cref="Security"/></remarks> /// <param name="accountCurrency">The account currency cash symbol to set</param> void SetAccountCurrency(string accountCurrency); /// <summary> /// Set the starting capital for the strategy /// </summary> /// <param name="startingCash">decimal starting capital, default $100,000</param> void SetCash(decimal startingCash); /// <summary> /// Set the cash for the specified symbol /// </summary> /// <param name="symbol">The cash symbol to set</param> /// <param name="startingCash">Decimal cash value of portfolio</param> /// <param name="conversionRate">The current conversion rate for the</param> void SetCash(string symbol, decimal startingCash, decimal conversionRate = 0); /// <summary> /// Liquidate your portfolio holdings: /// </summary> /// <param name="symbolToLiquidate">Specific asset to liquidate, defaults to all.</param> /// <param name="tag">Custom tag to know who is calling this.</param> /// <returns>list of order ids</returns> List<int> Liquidate(Symbol symbolToLiquidate = null, string tag = "Liquidated"); /// <summary> /// Set live mode state of the algorithm run: Public setter for the algorithm property LiveMode. /// </summary> /// <param name="live">Bool live mode flag</param> void SetLiveMode(bool live); /// <summary> /// Sets <see cref="IsWarmingUp"/> to false to indicate this algorithm has finished its warm up /// </summary> void SetFinishedWarmingUp(); /// <summary> /// Gets the date/time warmup should begin /// </summary> /// <returns></returns> IEnumerable<HistoryRequest> GetWarmupHistoryRequests(); /// <summary> /// Set the maximum number of orders the algortihm is allowed to process. /// </summary> /// <param name="max">Maximum order count int</param> void SetMaximumOrders(int max); /// <summary> /// Sets the implementation used to handle messages from the brokerage. /// The default implementation will forward messages to debug or error /// and when a <see cref="BrokerageMessageType.Error"/> occurs, the algorithm /// is stopped. /// </summary> /// <param name="handler">The message handler to use</param> void SetBrokerageMessageHandler(IBrokerageMessageHandler handler); /// <summary> /// Set the historical data provider /// </summary> /// <param name="historyProvider">Historical data provider</param> void SetHistoryProvider(IHistoryProvider historyProvider); /// <summary> /// Get the last known price using the history provider. /// Useful for seeding securities with the correct price /// </summary> /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param> /// <returns>A single <see cref="BaseData"/> object with the last known price</returns> BaseData GetLastKnownPrice(Security security); /// <summary> /// Set the runtime error /// </summary> /// <param name="exception">Represents error that occur during execution</param> void SetRunTimeError(Exception exception); /// <summary> /// Set the state of a live deployment /// </summary> /// <param name="status">Live deployment status</param> void SetStatus(AlgorithmStatus status); /// <summary> /// Set the available <see cref="TickType"/> supported by each <see cref="SecurityType"/> in <see cref="SecurityManager"/> /// </summary> /// <param name="availableDataTypes">>The different <see cref="TickType"/> each <see cref="Security"/> supports</param> void SetAvailableDataTypes(Dictionary<SecurityType, List<TickType>> availableDataTypes); /// <summary> /// Sets the option chain provider, used to get the list of option contracts for an underlying symbol /// </summary> /// <param name="optionChainProvider">The option chain provider</param> void SetOptionChainProvider(IOptionChainProvider optionChainProvider); /// <summary> /// Sets the future chain provider, used to get the list of future contracts for an underlying symbol /// </summary> /// <param name="futureChainProvider">The future chain provider</param> void SetFutureChainProvider(IFutureChainProvider futureChainProvider); /// <summary> /// Sets the current slice /// </summary> /// <param name="slice">The Slice object</param> void SetCurrentSlice(Slice slice); /// <summary> /// Provide the API for the algorithm. /// </summary> /// <param name="api">Initiated API</param> void SetApi(IApi api); /// <summary> /// Sets the object store /// </summary> /// <param name="objectStore">The object store</param> void SetObjectStore(IObjectStore objectStore); } }
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 FamilyTreeExplorer.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using MyGeneration.dOOdads; namespace CSharp { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { if(!SQL()) Console.WriteLine("SQL Failed"); if(!ACCESS()) Console.WriteLine("ACCESS Failed"); if(!ORACLE()) Console.WriteLine("ORACLE Failed"); if(!VISTADB()) Console.WriteLine("VISTADB Failed"); if(!FIREBIRD_1()) Console.WriteLine("FIREBIRD_1 Failed"); if(!FIREBIRD_3()) Console.WriteLine("FIREBIRD_3 Failed"); if(!FIREBIRD_3_TRUE()) Console.WriteLine("FIREBIRD_3_TRUE Failed"); if(!POSTGRESQL()) Console.WriteLine("POSTGRESQL Failed"); if(!MYSQL4()) Console.WriteLine("MYSQL4 Failed"); if(!SQLITE()) Console.WriteLine("SQLITE Failed"); Console.WriteLine("DONE"); Console.ReadLine(); } static bool SQL() { try { // LoadAll CSharp.SQL.Employees emps = new CSharp.SQL.Employees(); emps.FlushData(); emps.ConnectionString = "User ID=sa;Initial Catalog=Northwind;Data Source=griffo"; if(!emps.Query.Load()) { return false; // ERROR } // LoadByPrimaryKey int id = emps.EmployeeID; emps = new CSharp.SQL.Employees(); emps.ConnectionString = "User ID=sa;Initial Catalog=Northwind;Data Source=griffo"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.SQL.Employees(); emps.ConnectionString = "User ID=sa;Initial Catalog=Northwind;Data Source=griffo"; emps.AddNew(); emps.FirstName = "trella1"; emps.LastName = "trella1"; emps.AddNew(); emps.FirstName = "trella2"; emps.LastName = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.SQL.Employees(); emps.ConnectionString = "User ID=sa;Initial Catalog=Northwind;Data Source=griffo"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LastName = emps.LastName + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.SQL.Employees emps1 = new CSharp.SQL.Employees(); emps1.ConnectionString = "User ID=sa;Initial Catalog=Northwind;Data Source=griffo"; emps1.AddNew(); emps1.FirstName = "trella1_tx1"; emps1.LastName = "trella1_tx1"; CSharp.SQL.Employees emps2 = new CSharp.SQL.Employees(); emps2.ConnectionString = "User ID=sa;Initial Catalog=Northwind;Data Source=griffo"; emps2.AddNew(); emps2.FirstName = "trella1_tx2"; emps2.LastName = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.SQL.Employees(); emps.ConnectionString = "User ID=sa;Initial Catalog=Northwind;Data Source=griffo"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool ACCESS() { try { // LoadAll CSharp.ACCESS.Employees emps = new CSharp.ACCESS.Employees(); emps.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=C:\Access\NewNorthwind.mdb;"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey int id = emps.EmployeeID; emps = new CSharp.ACCESS.Employees(); emps.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=C:\Access\NewNorthwind.mdb;"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.ACCESS.Employees(); emps.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=C:\Access\NewNorthwind.mdb;"; emps.AddNew(); emps.FirstName = "trella1"; emps.LastName = "trella1"; emps.AddNew(); emps.FirstName = "trella2"; emps.LastName = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.ACCESS.Employees(); emps.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=C:\Access\NewNorthwind.mdb;"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LastName = emps.LastName + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.ACCESS.Employees emps1 = new CSharp.ACCESS.Employees(); emps1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=C:\Access\NewNorthwind.mdb;"; emps1.AddNew(); emps1.FirstName = "trella1_tx1"; emps1.LastName = "trella1_tx1"; CSharp.ACCESS.Employees emps2 = new CSharp.ACCESS.Employees(); emps2.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=C:\Access\NewNorthwind.mdb;"; emps2.AddNew(); emps2.FirstName = "trella1_tx2"; emps2.LastName = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.ACCESS.Employees(); emps.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=C:\Access\NewNorthwind.mdb;"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool ORACLE() { try { // LoadAll CSharp.ORACLE.EMPLOYEES emps = new CSharp.ORACLE.EMPLOYEES(); emps.ConnectionString = @"Password=sa;Persist Security Info=True;User ID=GRIFFO;Data Source=dbMeta"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey decimal id = emps.EMPLOYEE_ID; emps = new CSharp.ORACLE.EMPLOYEES(); emps.ConnectionString = @"Password=sa;Persist Security Info=True;User ID=GRIFFO;Data Source=dbMeta"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.ORACLE.EMPLOYEES(); emps.ConnectionString = @"Password=sa;Persist Security Info=True;User ID=GRIFFO;Data Source=dbMeta"; emps.AddNew(); emps.FIRST_NAME = "trella1"; emps.LAST_NAME = "trella1"; emps.AddNew(); emps.FIRST_NAME = "trella2"; emps.LAST_NAME = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.ORACLE.EMPLOYEES(); emps.ConnectionString = @"Password=sa;Persist Security Info=True;User ID=GRIFFO;Data Source=dbMeta"; emps.Where.FIRST_NAME.Value = "trella%"; emps.Where.FIRST_NAME.Operator = WhereParameter.Operand.Like; emps.Where.LAST_NAME.Value = "trella%"; emps.Where.LAST_NAME.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LAST_NAME = emps.LAST_NAME + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.ORACLE.EMPLOYEES emps1 = new CSharp.ORACLE.EMPLOYEES(); emps1.ConnectionString = @"Password=sa;Persist Security Info=True;User ID=GRIFFO;Data Source=dbMeta"; emps1.AddNew(); emps1.FIRST_NAME = "trella1_tx1"; emps1.LAST_NAME = "trella1_tx1"; CSharp.ORACLE.EMPLOYEES emps2 = new CSharp.ORACLE.EMPLOYEES(); emps2.ConnectionString = @"Password=sa;Persist Security Info=True;User ID=GRIFFO;Data Source=dbMeta"; emps2.AddNew(); emps2.FIRST_NAME = "trella1_tx2"; emps2.LAST_NAME = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.ORACLE.EMPLOYEES(); emps.ConnectionString = @"Password=sa;Persist Security Info=True;User ID=GRIFFO;Data Source=dbMeta"; emps.Where.FIRST_NAME.Value = "trella%"; emps.Where.FIRST_NAME.Operator = WhereParameter.Operand.Like; emps.Where.LAST_NAME.Value = "trella%"; emps.Where.LAST_NAME.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool FIREBIRD_1() { try { // LoadAll CSharp.FIREBIRD.DIALECT1.EMPLOYEES emps = new CSharp.FIREBIRD.DIALECT1.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP1.FBD;User=SYSDBA;Password=masterkey;Dialect=1;Server=griffo"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey int id = emps.EMPLOYEE_ID; emps = new CSharp.FIREBIRD.DIALECT1.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP1.FBD;User=SYSDBA;Password=masterkey;Dialect=1;Server=griffo"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.FIREBIRD.DIALECT1.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP1.FBD;User=SYSDBA;Password=masterkey;Dialect=1;Server=griffo"; emps.AddNew(); emps.FIRST_NAME = "trella1"; emps.LAST_NAME = "trella1"; emps.AddNew(); emps.FIRST_NAME = "trella2"; emps.LAST_NAME = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.FIREBIRD.DIALECT1.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP1.FBD;User=SYSDBA;Password=masterkey;Dialect=1;Server=griffo"; emps.Where.FIRST_NAME.Value = "trella%"; emps.Where.FIRST_NAME.Operator = WhereParameter.Operand.Like; emps.Where.LAST_NAME.Value = "trella%"; emps.Where.LAST_NAME.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LAST_NAME = emps.LAST_NAME + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.FIREBIRD.DIALECT1.EMPLOYEES emps1 = new CSharp.FIREBIRD.DIALECT1.EMPLOYEES(); emps1.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP1.FBD;User=SYSDBA;Password=masterkey;Dialect=1;Server=griffo"; emps1.AddNew(); emps1.FIRST_NAME = "trella1_tx1"; emps1.LAST_NAME = "trella1_tx1"; CSharp.FIREBIRD.DIALECT1.EMPLOYEES emps2 = new CSharp.FIREBIRD.DIALECT1.EMPLOYEES(); emps2.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP1.FBD;User=SYSDBA;Password=masterkey;Dialect=1;Server=griffo"; emps2.AddNew(); emps2.FIRST_NAME = "trella1_tx2"; emps2.LAST_NAME = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.FIREBIRD.DIALECT1.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP1.FBD;User=SYSDBA;Password=masterkey;Dialect=1;Server=griffo"; emps.Where.FIRST_NAME.Value = "trella%"; emps.Where.FIRST_NAME.Operator = WhereParameter.Operand.Like; emps.Where.LAST_NAME.Value = "trella%"; emps.Where.LAST_NAME.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool FIREBIRD_3() { try { // LoadAll CSharp.FIREBIRD.DIALECT3.EMPLOYEES emps = new CSharp.FIREBIRD.DIALECT3.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP3.FBD;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey int id = emps.EMPLOYEE_ID; emps = new CSharp.FIREBIRD.DIALECT3.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP3.FBD;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.FIREBIRD.DIALECT3.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP3.FBD;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps.AddNew(); emps.FIRST_NAME = "trella1"; emps.LAST_NAME = "trella1"; emps.AddNew(); emps.FIRST_NAME = "trella2"; emps.LAST_NAME = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.FIREBIRD.DIALECT3.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP3.FBD;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps.Where.FIRST_NAME.Value = "trella%"; emps.Where.FIRST_NAME.Operator = WhereParameter.Operand.Like; emps.Where.LAST_NAME.Value = "trella%"; emps.Where.LAST_NAME.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LAST_NAME = emps.LAST_NAME + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.FIREBIRD.DIALECT3.EMPLOYEES emps1 = new CSharp.FIREBIRD.DIALECT3.EMPLOYEES(); emps1.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP3.FBD;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps1.AddNew(); emps1.FIRST_NAME = "trella1_tx1"; emps1.LAST_NAME = "trella1_tx1"; CSharp.FIREBIRD.DIALECT3.EMPLOYEES emps2 = new CSharp.FIREBIRD.DIALECT3.EMPLOYEES(); emps2.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP3.FBD;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps2.AddNew(); emps2.FIRST_NAME = "trella1_tx2"; emps2.LAST_NAME = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.FIREBIRD.DIALECT3.EMPLOYEES(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMP3.FBD;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps.Where.FIRST_NAME.Value = "trella%"; emps.Where.FIRST_NAME.Operator = WhereParameter.Operand.Like; emps.Where.LAST_NAME.Value = "trella%"; emps.Where.LAST_NAME.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool FIREBIRD_3_TRUE() { try { // LoadAll CSharp.FIREBIRD.DIALECT3_TRUE.Employees emps = new CSharp.FIREBIRD.DIALECT3_TRUE.Employees(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMPTRUE3.FDB;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey long id = emps.EmployeeID; emps = new CSharp.FIREBIRD.DIALECT3_TRUE.Employees(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMPTRUE3.FDB;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.FIREBIRD.DIALECT3_TRUE.Employees(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMPTRUE3.FDB;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps.AddNew(); emps.FirstName = "trella1"; emps.LastName = "trella1"; emps.AddNew(); emps.FirstName = "trella2"; emps.LastName = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.FIREBIRD.DIALECT3_TRUE.Employees(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMPTRUE3.FDB;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LastName = emps.LastName + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.FIREBIRD.DIALECT3_TRUE.Employees emps1 = new CSharp.FIREBIRD.DIALECT3_TRUE.Employees(); emps1.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMPTRUE3.FDB;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps1.AddNew(); emps1.FirstName = "trella1_tx1"; emps1.LastName = "trella1_tx1"; CSharp.FIREBIRD.DIALECT3_TRUE.Employees emps2 = new CSharp.FIREBIRD.DIALECT3_TRUE.Employees(); emps2.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMPTRUE3.FDB;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps2.AddNew(); emps2.FirstName = "trella1_tx2"; emps2.LastName = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.FIREBIRD.DIALECT3_TRUE.Employees(); emps.ConnectionString = @"Database=C:\dOOdad_UnitTesting\EMPTRUE3.FDB;User=SYSDBA;Password=masterkey;Dialect=3;Server=griffo"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool POSTGRESQL() { try { // LoadAll CSharp.POSTGRESQL.employees emps = new CSharp.POSTGRESQL.employees(); emps.ConnectionString = @"Server=www.punktech.com;User Id=postgres;Password=password;Database=griffo;port=5432;"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey int id = emps.EmployeeID; emps = new CSharp.POSTGRESQL.employees(); emps.ConnectionString = @"Server=www.punktech.com;User Id=postgres;Password=password;Database=griffo;port=5432;"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.POSTGRESQL.employees(); emps.ConnectionString = @"Server=www.punktech.com;User Id=postgres;Password=password;Database=griffo;port=5432;"; emps.AddNew(); emps.FirstName = "trella1"; emps.LastName = "trella1"; emps.AddNew(); emps.FirstName = "trella2"; emps.LastName = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.POSTGRESQL.employees(); emps.ConnectionString = @"Server=www.punktech.com;User Id=postgres;Password=password;Database=griffo;port=5432;"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LastName = emps.LastName + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.POSTGRESQL.employees emps1 = new CSharp.POSTGRESQL.employees(); emps1.ConnectionString = @"Server=www.punktech.com;User Id=postgres;Password=password;Database=griffo;port=5432;"; emps1.AddNew(); emps1.FirstName = "trella1_tx1"; emps1.LastName = "trella1_tx1"; CSharp.POSTGRESQL.employees emps2 = new CSharp.POSTGRESQL.employees(); emps2.ConnectionString = @"Server=www.punktech.com;User Id=postgres;Password=password;Database=griffo;port=5432;"; emps2.AddNew(); emps2.FirstName = "trella1_tx2"; emps2.LastName = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.POSTGRESQL.employees(); emps.ConnectionString = @"Server=www.punktech.com;User Id=postgres;Password=password;Database=griffo;port=5432;"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool VISTADB() { try { // LoadAll CSharp.VISTADB.Employees emps = new CSharp.VISTADB.Employees(); emps.ConnectionString = @"DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb;"; emps.Query.AddResultColumn(CSharp.VISTADB.Employees.ColumnNames.EmployeeID); emps.Query.AddResultColumn(CSharp.VISTADB.Employees.ColumnNames.LastName); emps.Query.AddOrderBy(CSharp.VISTADB.Employees.ColumnNames.LastName, WhereParameter.Dir.ASC); emps.Query.Top = 2; if(!emps.Query.Load()) { return false; // ERROR } // LoadAll emps = new CSharp.VISTADB.Employees(); emps.ConnectionString = @"DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb;"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey int id = emps.EmployeeID; emps = new CSharp.VISTADB.Employees(); emps.ConnectionString = @"DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb;"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.VISTADB.Employees(); emps.ConnectionString = @"DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb;"; emps.AddNew(); emps.FirstName = "trella1"; emps.LastName = "trella1"; emps.AddNew(); emps.FirstName = "trella2"; emps.LastName = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.VISTADB.Employees(); emps.ConnectionString = @"DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb;"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LastName = emps.LastName + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.VISTADB.Employees emps1 = new CSharp.VISTADB.Employees(); emps1.ConnectionString = @"DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb;"; emps1.AddNew(); emps1.FirstName = "trella1_tx1"; emps1.LastName = "trella1_tx1"; CSharp.VISTADB.Employees emps2 = new CSharp.VISTADB.Employees(); emps2.ConnectionString = @"DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb;"; emps2.AddNew(); emps2.FirstName = "trella1_tx2"; emps2.LastName = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.VISTADB.Employees(); emps.ConnectionString = @"DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb;"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool MYSQL4() { try { // LoadAll CSharp.MySQL4.employee emps = new CSharp.MySQL4.employee(); emps.ConnectionString = @"Database=Test;Data Source=Griffo;User Id=anonymous;"; emps.Query.AddResultColumn(CSharp.MySQL4.employee.ColumnNames.EmployeeID); emps.Query.AddResultColumn(CSharp.MySQL4.employee.ColumnNames.LastName); emps.Query.AddOrderBy(CSharp.MySQL4.employee.ColumnNames.LastName, WhereParameter.Dir.ASC); emps.Query.Top = 2; if(!emps.Query.Load()) { return false; // ERROR } // LoadAll emps = new CSharp.MySQL4.employee(); emps.ConnectionString = @"Database=Test;Data Source=Griffo;User Id=anonymous;"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey uint id = emps.EmployeeID; emps = new CSharp.MySQL4.employee(); emps.ConnectionString = @"Database=Test;Data Source=Griffo;User Id=anonymous;"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.MySQL4.employee(); emps.ConnectionString = @"Database=Test;Data Source=Griffo;User Id=anonymous;"; emps.AddNew(); emps.FirstName = "trella1"; emps.LastName = "trella1"; emps.AddNew(); emps.FirstName = "trella2"; emps.LastName = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.MySQL4.employee(); emps.ConnectionString = @"Database=Test;Data Source=Griffo;User Id=anonymous;"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LastName = emps.LastName + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.MySQL4.employee emps1 = new CSharp.MySQL4.employee(); emps1.ConnectionString = @"Database=Test;Data Source=Griffo;User Id=anonymous;"; emps1.AddNew(); emps1.FirstName = "trella1_tx1"; emps1.LastName = "trella1_tx1"; CSharp.MySQL4.employee emps2 = new CSharp.MySQL4.employee(); emps2.ConnectionString = @"Database=Test;Data Source=Griffo;User Id=anonymous;"; emps2.AddNew(); emps2.FirstName = "trella1_tx2"; emps2.LastName = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.MySQL4.employee(); emps.ConnectionString = @"Database=Test;Data Source=Griffo;User Id=anonymous;"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } static bool SQLITE() { try { // LoadAll CSharp.SQLite.vwEmployees vemps = new CSharp.SQLite.vwEmployees(); vemps.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3;"; vemps.Query.AddResultColumn(CSharp.SQLite.Employees.ColumnNames.EmployeeID); vemps.Query.AddResultColumn(CSharp.SQLite.Employees.ColumnNames.LastName); vemps.Query.AddOrderBy(CSharp.SQLite.Employees.ColumnNames.LastName, WhereParameter.Dir.ASC); vemps.Query.Top = 2; if(!vemps.Query.Load()) { return false; // ERROR } // LoadAll CSharp.SQLite.Employees emps = new CSharp.SQLite.Employees(); emps.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3;"; emps.Query.AddResultColumn(CSharp.SQLite.Employees.ColumnNames.EmployeeID); emps.Query.AddResultColumn(CSharp.SQLite.Employees.ColumnNames.LastName); emps.Query.AddOrderBy(CSharp.SQLite.Employees.ColumnNames.LastName, WhereParameter.Dir.ASC); emps.Query.Top = 2; if(!emps.Query.Load()) { return false; // ERROR } // LoadAll emps = new CSharp.SQLite.Employees(); emps.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3;"; if(!emps.LoadAll()) { return false; // ERROR } // LoadByPrimaryKey long id = emps.EmployeeID; emps = new CSharp.SQLite.Employees(); emps.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3;"; if(!emps.LoadByPrimaryKey(id)) { return false; // ERROR } // AddNew/Save emps = new CSharp.SQLite.Employees(); emps.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3"; emps.AddNew(); emps.FirstName = "trella1"; emps.LastName = "trella1"; emps.AddNew(); emps.FirstName = "trella2"; emps.LastName = "trella2"; emps.Save(); // Query.Load/Update/Save emps = new CSharp.SQLite.Employees(); emps.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } do emps.LastName = emps.LastName + ":new"; while(emps.MoveNext()); emps.Save(); // Transaction CSharp.SQLite.Employees emps1 = new CSharp.SQLite.Employees(); emps1.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3"; emps1.AddNew(); emps1.FirstName = "trella1_tx1"; emps1.LastName = "trella1_tx1"; CSharp.SQLite.Employees emps2 = new CSharp.SQLite.Employees(); emps2.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3"; emps2.AddNew(); emps2.FirstName = "trella1_tx2"; emps2.LastName = "trella1_tx2"; TransactionMgr.ThreadTransactionMgr().BeginTransaction(); emps1.Save(); emps2.Save(); TransactionMgr.ThreadTransactionMgr().CommitTransaction(); // Query.Load/MarkAsDeleted/Save emps = new CSharp.SQLite.Employees(); emps.ConnectionString = @"Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3"; emps.Where.FirstName.Value = "trella%"; emps.Where.FirstName.Operator = WhereParameter.Operand.Like; emps.Where.LastName.Value = "trella%"; emps.Where.LastName.Operator = WhereParameter.Operand.Like; if(!emps.Query.Load()) { return false; // ERROR } emps.DeleteAll(); emps.Save(); } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } finally { TransactionMgr.ThreadTransactionMgrReset(); } return true; } } }
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 nH.Api.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; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { [Flags] internal enum GetValueFlags { None = 0x0, IncludeTypeName = 0x1, IncludeObjectId = 0x2, } // This class provides implementation for the "displaying values as strings" aspect of the default (C#) Formatter component. internal abstract partial class Formatter { internal string GetValueString(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options, GetValueFlags flags) { if (value.IsError()) { return (string)value.HostObjectValue; } if (UsesHexadecimalNumbers(inspectionContext)) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } var lmrType = value.Type.GetLmrType(); if (IsPredefinedType(lmrType) && !lmrType.IsObject()) { if (lmrType.IsString()) { var stringValue = (string)value.HostObjectValue; if (stringValue == null) { return _nullString; } return IncludeObjectId( value, FormatString(stringValue, options), flags); } else if (lmrType.IsCharacter()) { return IncludeObjectId( value, FormatLiteral((char)value.HostObjectValue, options | ObjectDisplayOptions.IncludeCodePoints), flags); } else { return IncludeObjectId( value, FormatPrimitive(value, options & ~ObjectDisplayOptions.UseQuotes, inspectionContext), flags); } } else if (value.IsNull && !lmrType.IsPointer) { return _nullString; } else if (lmrType.IsEnum) { return IncludeObjectId( value, GetEnumDisplayString(lmrType, value, options, (flags & GetValueFlags.IncludeTypeName) != 0, inspectionContext), flags); } else if (lmrType.IsArray) { return IncludeObjectId( value, GetArrayDisplayString(lmrType, value.ArrayDimensions, value.ArrayLowerBounds, options), flags); } else if (lmrType.IsPointer) { // NOTE: the HostObjectValue will have a size corresponding to the process bitness // and FormatPrimitive will adjust accordingly. var tmp = FormatPrimitive(value, ObjectDisplayOptions.UseHexadecimalNumbers, inspectionContext); // Always in hex. Debug.Assert(tmp != null); return tmp; } else if (lmrType.IsNullable()) { var nullableValue = value.GetNullableValue(inspectionContext); // It should be impossible to nest nullables, so this recursion should introduce only a single extra stack frame. return nullableValue == null ? _nullString : GetValueString(nullableValue, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName); } // "value.EvaluateToString()" will check "Call string-conversion function on objects in variables windows" // (Tools > Options setting) and call "value.ToString()" if appropriate. return IncludeObjectId( value, string.Format(_defaultFormat, value.EvaluateToString(inspectionContext) ?? inspectionContext.GetTypeName(value.Type, CustomTypeInfo: null, FormatSpecifiers: NoFormatSpecifiers)), flags); } /// <summary> /// Gets the string representation of a character literal without including the numeric code point. /// </summary> internal string GetValueStringForCharacter(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options) { Debug.Assert(value.Type.GetLmrType().IsCharacter()); if (UsesHexadecimalNumbers(inspectionContext)) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } var charTemp = FormatLiteral((char)value.HostObjectValue, options); Debug.Assert(charTemp != null); return charTemp; } internal bool HasUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { return GetUnderlyingString(value, inspectionContext) != null; } internal string GetUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { RawStringDataItem dataItem = value.GetDataItem<RawStringDataItem>(); if (dataItem != null) { return dataItem.RawString; } string underlyingString = GetUnderlyingStringImpl(value, inspectionContext); dataItem = new RawStringDataItem(underlyingString); value.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem); return underlyingString; } private string GetUnderlyingStringImpl(DkmClrValue value, DkmInspectionContext inspectionContext) { Debug.Assert(!value.IsError()); if (value.IsNull) { return null; } var lmrType = value.Type.GetLmrType(); if (lmrType.IsEnum || lmrType.IsArray || lmrType.IsPointer) { return null; } if (lmrType.IsNullable()) { var nullableValue = value.GetNullableValue(inspectionContext); return nullableValue != null ? GetUnderlyingStringImpl(nullableValue, inspectionContext) : null; } if (lmrType.IsString()) { return (string)value.HostObjectValue; } else if (!IsPredefinedType(lmrType)) { // Check for special cased non-primitives that have underlying strings if (lmrType.IsType("System.Data.SqlTypes", "SqlString")) { var fieldValue = value.GetFieldValue(InternalWellKnownMemberNames.SqlStringValue, inspectionContext); return fieldValue.HostObjectValue as string; } else if (lmrType.IsOrInheritsFrom("System.Xml.Linq", "XNode")) { return value.EvaluateToString(inspectionContext); } } return null; } #pragma warning disable RS0010 /// <remarks> /// The corresponding native code is in EEUserStringBuilder::ErrTryAppendConstantEnum. /// The corresponding roslyn code is in /// <see cref="M:Microsoft.CodeAnalysis.SymbolDisplay.AbstractSymbolDisplayVisitor`1.AddEnumConstantValue(Microsoft.CodeAnalysis.INamedTypeSymbol, System.Object, System.Boolean)"/>. /// NOTE: no curlies for enum values. /// </remarks> #pragma warning restore RS0010 private string GetEnumDisplayString(Type lmrType, DkmClrValue value, ObjectDisplayOptions options, bool includeTypeName, DkmInspectionContext inspectionContext) { Debug.Assert(lmrType.IsEnum); Debug.Assert(value != null); object underlyingValue = value.HostObjectValue; Debug.Assert(underlyingValue != null); string displayString; ArrayBuilder<EnumField> fields = ArrayBuilder<EnumField>.GetInstance(); FillEnumFields(fields, lmrType); // We will normalize/extend all enum values to ulong to ensure that we are always comparing the full underlying value. ulong valueForComparison = ConvertEnumUnderlyingTypeToUInt64(underlyingValue, Type.GetTypeCode(lmrType)); var typeToDisplayOpt = includeTypeName ? lmrType : null; if (valueForComparison != 0 && IsFlagsEnum(lmrType)) { displayString = GetNamesForFlagsEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt); } else { displayString = GetNameForEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt); } fields.Free(); return displayString ?? FormatPrimitive(value, options, inspectionContext); } private static void FillEnumFields(ArrayBuilder<EnumField> fields, Type lmrType) { var fieldInfos = lmrType.GetFields(); var enumTypeCode = Type.GetTypeCode(lmrType); foreach (var info in fieldInfos) { if (!info.IsSpecialName) // Skip __value. { fields.Add(new EnumField(info.Name, ConvertEnumUnderlyingTypeToUInt64(info.GetRawConstantValue(), enumTypeCode))); } } fields.Sort(EnumField.Comparer); } internal static void FillUsedEnumFields(ArrayBuilder<EnumField> usedFields, ArrayBuilder<EnumField> fields, ulong underlyingValue) { var remaining = underlyingValue; foreach (var field in fields) { var fieldValue = field.Value; if (fieldValue == 0) continue; // Otherwise, we'd tack the zero flag onto everything. if ((remaining & fieldValue) == fieldValue) { remaining -= fieldValue; usedFields.Add(field); if (remaining == 0) break; } } // The value contained extra bit flags that didn't correspond to any enum field. We will // report "no fields used" here so the Formatter will just display the underlying value. if (remaining != 0) { usedFields.Clear(); } } private static bool IsFlagsEnum(Type lmrType) { Debug.Assert(lmrType.IsEnum); var attributes = lmrType.GetCustomAttributesData(); foreach (var attribute in attributes) { // NOTE: AttributeType is not available in 2.0 if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute") { return true; } } return false; } private static bool UsesHexadecimalNumbers(DkmInspectionContext inspectionContext) { Debug.Assert(inspectionContext != null); return inspectionContext.Radix == 16; } /// <summary> /// Convert a boxed primitive (generally of the backing type of an enum) into a ulong. /// </summary> protected static ulong ConvertEnumUnderlyingTypeToUInt64(object value, TypeCode typeCode) { Debug.Assert(value != null); unchecked { switch (typeCode) { case TypeCode.SByte: return (ulong)(sbyte)value; case TypeCode.Int16: return (ulong)(short)value; case TypeCode.Int32: return (ulong)(int)value; case TypeCode.Int64: return (ulong)(long)value; case TypeCode.Byte: return (byte)value; case TypeCode.UInt16: return (ushort)value; case TypeCode.UInt32: return (uint)value; case TypeCode.UInt64: return (ulong)value; default: throw ExceptionUtilities.UnexpectedValue(typeCode); } } } internal string GetEditableValue(DkmClrValue value, DkmInspectionContext inspectionContext) { if (value.IsError()) { return null; } if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ReadOnly)) { return null; } var type = value.Type.GetLmrType(); if (type.IsEnum) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName); } else if (type.IsDecimal()) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.IncludeTypeSuffix, GetValueFlags.None); } // The legacy EE didn't special-case strings or chars (when ",nq" was used, // you had to manually add quotes when editing) but it makes sense to // always automatically quote (non-null) strings and chars when editing. else if (type.IsString()) { if (!value.IsNull) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.UseQuotes, GetValueFlags.None); } } else if (type.IsCharacter()) { return this.GetValueStringForCharacter(value, inspectionContext, ObjectDisplayOptions.UseQuotes); } return null; } internal string FormatPrimitive(DkmClrValue value, ObjectDisplayOptions options, DkmInspectionContext inspectionContext) { Debug.Assert(value != null); object obj; if (value.Type.GetLmrType().IsDateTime()) { DkmClrValue dateDataValue = value.GetFieldValue(DateTimeUtilities.DateTimeDateDataFieldName, inspectionContext); Debug.Assert(dateDataValue.HostObjectValue != null); obj = DateTimeUtilities.ToDateTime((ulong)dateDataValue.HostObjectValue); } else { Debug.Assert(value.HostObjectValue != null); obj = value.HostObjectValue; } return FormatPrimitiveObject(obj, options); } private static string IncludeObjectId(DkmClrValue value, string valueStr, GetValueFlags flags) { Debug.Assert(valueStr != null); return (flags & GetValueFlags.IncludeObjectId) == 0 ? valueStr : value.IncludeObjectId(valueStr); } #region Language-specific value formatting behavior internal abstract string GetArrayDisplayString(Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options); internal abstract string GetArrayIndexExpression(int[] indices); internal abstract string GetCastExpression(string argument, string type, bool parenthesizeArgument = false /* ignored in Visual Basic */, bool parenthesizeEntireExpression = false /* ignored in Visual Basic */); internal abstract string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt); internal abstract string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt); internal abstract string GetObjectCreationExpression(string type, string arguments); internal abstract string FormatLiteral(char c, ObjectDisplayOptions options); internal abstract string FormatLiteral(int value, ObjectDisplayOptions options); internal abstract string FormatPrimitiveObject(object value, ObjectDisplayOptions options); internal abstract string FormatString(string str, ObjectDisplayOptions options); #endregion } }
using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.Zip; using SIL.IO; using System.Drawing; using System; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Xml; using Bloom.ImageProcessing; using SIL.Windows.Forms.ImageToolbox; using SIL.Xml; using System.Collections.Generic; using Bloom.web.controllers; namespace Bloom.Book { public class BookCompressor { public const string BloomPubExtensionWithDot = ".bloomd"; public static string LastVersionCode { get; private set; } // these image files may need to be reduced before being stored in the compressed output file internal static readonly string[] ImageFileExtensions = { ".tif", ".tiff", ".png", ".bmp", ".jpg", ".jpeg" }; // Since BL-8956, we whitelist files so that only those we expect will make it through the // compression process. // These audio file extensions are the only ones we expect in the 'audio' folder. internal static readonly string[] AudioFileExtensions = { ".mp3", ".wav", ".ogg" }; // This video file extension is the only one we expect in the 'video' folder. internal static readonly string[] VideoFileExtensions = { ".mp4" }; // These file extensions are the only ones that will be included in the compressed version // at the top book level. internal static readonly string[] BookLevelFileExtensionsLowerCase = { ".svg", ".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".otf", ".ttf", ".woff", ".htm", ".css", ".json", ".txt", ".js", ".distribution" }; internal static void MakeSizedThumbnail(Book book, string destinationFolder, int heightAndWidth) { // If this fails to create a 'coverImage200.jpg', either the cover image is missing or it's only a placeholder. // If this is a new book, the file may exist already, but we want to make sure it's up-to-date. // If this is an older book, we need the .bloomd to have it so that Harvester will be able to access it. BookThumbNailer.GenerateImageForWeb(book); var coverImagePath = book.GetCoverImagePath(); if (coverImagePath == null) { var blankImage = Path.Combine(FileLocationUtilities.DirectoryOfApplicationOrSolution, "DistFiles", "Blank.png"); if (RobustFile.Exists(blankImage)) coverImagePath = blankImage; } if(coverImagePath != null) { var thumbPath = Path.Combine(destinationFolder, "thumbnail.png"); RuntimeImageProcessor.GenerateEBookThumbnail(coverImagePath, thumbPath, heightAndWidth, heightAndWidth,System.Drawing.ColorTranslator.FromHtml(book.GetCoverColor())); } } /// <summary> /// Zips a directory containing a Bloom collection, along with all files and subdirectories /// </summary> /// <param name="outputPath">The location to which to create the output zip file</param> /// <param name="directoryToCompress">The directory to add recursively</param> /// <param name="dirNamePrefix">string to prefix to the zip entry name</param> /// <param name="forReaderTools">If True, then some pre-processing will be done to the contents of decodable /// and leveled readers before they are added to the ZipStream</param> /// <param name="excludeAudio">If true, the contents of the audio directory will not be included</param> public static void CompressCollectionDirectory(string outputPath, string directoryToCompress, string dirNamePrefix, bool forReaderTools, bool excludeAudio) { CompressDirectory(outputPath, directoryToCompress, dirNamePrefix, forReaderTools, excludeAudio, depthFromCollection: 0); } /// <summary> /// Zips a directory containing a Bloom book, along with all files and subdirectories /// </summary> /// <param name="outputPath">The location to which to create the output zip file</param> /// <param name="directoryToCompress">The directory to add recursively</param> /// <param name="dirNamePrefix">string to prefix to the zip entry name</param> /// <param name="forReaderTools">If True, then some pre-processing will be done to the contents of decodable /// and leveled readers before they are added to the ZipStream</param> /// <param name="excludeAudio">If true, the contents of the audio directory will not be included</param> /// <param name="reduceImages">If true, image files are reduced in size to no larger than the max size before saving</para> /// <param name="omitMetaJson">If true, meta.json is excluded (typically for HTML readers).</param> public static void CompressBookDirectory(string outputPath, string directoryToCompress, string dirNamePrefix, bool forReaderTools = false, bool excludeAudio = false, bool reduceImages = false, bool omitMetaJson = false, bool wrapWithFolder = true, string pathToFileForSha = null) { CompressDirectory(outputPath, directoryToCompress, dirNamePrefix, forReaderTools, excludeAudio, reduceImages, omitMetaJson, wrapWithFolder, pathToFileForSha, depthFromCollection: 1); } private static void CompressDirectory(string outputPath, string directoryToCompress, string dirNamePrefix, bool forReaderTools = false, bool excludeAudio = false, bool reduceImages = false, bool omitMetaJson = false, bool wrapWithFolder = true, string pathToFileForSha = null, int depthFromCollection = 1) { using (var fsOut = RobustFile.Create(outputPath)) { using (var zipStream = new ZipOutputStream(fsOut)) { zipStream.SetLevel(9); int dirNameOffset; if (wrapWithFolder) { // zip entry names will start with the compressed folder name (zip will contain the // compressed folder as a folder...we do this in bloompacks, not sure why). var rootName = Path.GetFileName(directoryToCompress); dirNameOffset = directoryToCompress.Length - rootName.Length; } else { // zip entry names will start with the files or directories at the root of the book folder // (zip root will contain the folder contents...suitable for compressing a single book into // a zip, as with .bloomd files) dirNameOffset = directoryToCompress.Length + 1; } CompressDirectory(directoryToCompress, zipStream, dirNameOffset, dirNamePrefix, depthFromCollection, forReaderTools, excludeAudio, reduceImages, omitMetaJson, pathToFileForSha); zipStream.IsStreamOwner = true; // makes the Close() also close the underlying stream zipStream.Close(); } } } /// <summary> /// Adds a directory, along with all files and subdirectories, to the ZipStream. /// </summary> /// <param name="directoryToCompress">The directory to add recursively</param> /// <param name="zipStream">The ZipStream to which the files and directories will be added</param> /// <param name="dirNameOffset">This number of characters will be removed from the full directory or file name /// before creating the zip entry name</param> /// <param name="dirNamePrefix">string to prefix to the zip entry name</param> /// <param name="depthFromCollection">int with the number of folders away it is from the collection folder. The collection folder itself is 0, /// a book is 1, a subfolder of the book is 2, etc.</param> /// <param name="forReaderTools">If True, then some pre-processing will be done to the contents of decodable /// and leveled readers before they are added to the ZipStream</param> /// <param name="excludeAudio">If true, the contents of the audio directory will not be included</param> /// <param name="reduceImages">If true, image files are reduced in size to no larger than the max size before saving</para> /// <param name="omitMetaJson">If true, meta.json is excluded (typically for HTML readers).</param> private static void CompressDirectory(string directoryToCompress, ZipOutputStream zipStream, int dirNameOffset, string dirNamePrefix, int depthFromCollection, bool forReaderTools, bool excludeAudio, bool reduceImages, bool omitMetaJson = false, string pathToFileForSha = null) { var folderName = Path.GetFileName(directoryToCompress).ToLowerInvariant(); if (!IsValidBookFolder(folderName, excludeAudio, depthFromCollection)) return; var files = Directory.GetFiles(directoryToCompress); // Don't get distracted by HTML files in any folder other than the book folder. // These HTML files in other locations aren't generated by Bloom. They may not have the format Bloom expects, // causing needless parsing errors to be thrown if we attempt to read them using Bloom code. bool shouldScanHtml = depthFromCollection == 1; // 1 means 1 level below the collection level, i.e. this is the book level var bookFile = shouldScanHtml ? BookStorage.FindBookHtmlInFolder(directoryToCompress) : null; XmlDocument dom = null; List<string> imagesToGiveTransparentBackgrounds = null; List<string> imagesToPreserveResolution = null; // Tests can also result in bookFile being null. if (!String.IsNullOrEmpty(bookFile)) { var originalContent = File.ReadAllText(bookFile, Encoding.UTF8); dom = XmlHtmlConverter.GetXmlDomFromHtml(originalContent); var fullScreenAttr = dom.GetElementsByTagName("body").Cast<XmlElement>().First().Attributes["data-bffullscreenpicture"]?.Value; if (fullScreenAttr != null && fullScreenAttr.IndexOf("bloomReader", StringComparison.InvariantCulture) >= 0) { // This feature (currently used for motion books in landscape mode) triggers an all-black background, // due to a rule in bookFeatures.less. // Making white pixels transparent on an all-black background makes line-art disappear, // which is bad (BL-6564), so just make an empty list in this case. imagesToGiveTransparentBackgrounds = new List<string>(); } else { imagesToGiveTransparentBackgrounds = FindCoverImages(dom); } imagesToPreserveResolution = FindImagesToPreserveResolution(dom); FindBackgroundAudioFiles(dom); } else { imagesToGiveTransparentBackgrounds = new List<string>(); imagesToPreserveResolution = new List<string>(); } // Some of the knowledge about IncludedFileExtensions might one day move into this method. // But we'd have to check carefully the other places it is used. var localOnlyFiles = BookStorage.LocalOnlyFiles(directoryToCompress); foreach (var filePath in files) { if (!FileIsWhitelisted(filePath, depthFromCollection)) continue; // BL-2246: skip putting this one into the BloomPack or .bloomd if (IsUnneededWaveFile(filePath, depthFromCollection)) continue; if (localOnlyFiles.Contains(filePath)) continue; var fileName = Path.GetFileName(filePath).ToLowerInvariant(); if (fileName.StartsWith(BookStorage.PrefixForCorruptHtmFiles)) continue; // Various stuff we keep in the book folder that is useful for editing or bloom library // or displaying collections but not needed by the reader. The most important is probably // eliminating the pdf, which can be very large. Note that we do NOT eliminate the // basic thumbnail.png, as we want eventually to extract that to use in the Reader UI. if (fileName == "thumbnail-70.png" || fileName == "thumbnail-256.png") continue; if (fileName == "meta.json" && omitMetaJson) continue; FileInfo fi = new FileInfo(filePath); var entryName = dirNamePrefix + filePath.Substring(dirNameOffset); // Makes the name in zip based on the folder entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName) { DateTime = fi.LastWriteTime, IsUnicodeText = true }; // encode filename and comment in UTF8 byte[] modifiedContent = {}; // if this is a ReaderTools book, call GetBookReplacedWithTemplate() to get the contents if (forReaderTools && (bookFile == filePath)) { modifiedContent = Encoding.UTF8.GetBytes(GetBookReplacedWithTemplate(filePath)); newEntry.Size = modifiedContent.Length; } else if (forReaderTools && (Path.GetFileName(filePath) == "meta.json")) { modifiedContent = Encoding.UTF8.GetBytes(GetMetaJsonModfiedForTemplate(filePath)); newEntry.Size = modifiedContent.Length; } else if (reduceImages && ImageFileExtensions.Contains(Path.GetExtension(filePath).ToLowerInvariant())) { fileName = Path.GetFileName(filePath); // restore original capitalization if (imagesToPreserveResolution.Contains(fileName)) { modifiedContent = RobustFile.ReadAllBytes(filePath); } else { // Cover images should be transparent if possible. Others don't need to be. var makeBackgroundTransparent = imagesToGiveTransparentBackgrounds.Contains(fileName); modifiedContent = GetImageBytesForElectronicPub(filePath, makeBackgroundTransparent); } newEntry.Size = modifiedContent.Length; } else if (Path.GetExtension(filePath).ToLowerInvariant() == ".bloomcollection") { modifiedContent = Encoding.UTF8.GetBytes(GetBloomCollectionModifiedForTemplate(filePath)); newEntry.Size = modifiedContent.Length; } // CompressBookForDevice is always called with reduceImages set. else if (reduceImages && bookFile == filePath) { SignLanguageApi.ProcessVideos(HtmlDom.SelectChildVideoElements(dom.DocumentElement).Cast<XmlElement>(), directoryToCompress); var newContent = XmlHtmlConverter.ConvertDomToHtml5(dom); modifiedContent = Encoding.UTF8.GetBytes(newContent); newEntry.Size = modifiedContent.Length; if (pathToFileForSha != null) { // Make an extra entry containing the sha var sha = Book.ComputeHashForAllBookRelatedFiles(pathToFileForSha); var name = "version.txt"; // must match what BloomReader is looking for in NewBookListenerService.IsBookUpToDate() MakeExtraEntry(zipStream, name, sha); LastVersionCode = sha; } } else { newEntry.Size = fi.Length; } zipStream.PutNextEntry(newEntry); if (modifiedContent.Length > 0) { using (var memStream = new MemoryStream(modifiedContent)) { // There is some minimum buffer size (44 was too small); I don't know exactly what it is, // but 1024 makes it happy. StreamUtils.Copy(memStream, zipStream, new byte[Math.Max(modifiedContent.Length, 1024)]); } } else { // Zip the file in buffered chunks byte[] buffer = new byte[4096]; using (var streamReader = RobustFile.OpenRead(filePath)) { StreamUtils.Copy(streamReader, zipStream, buffer); } } zipStream.CloseEntry(); } var folders = Directory.GetDirectories(directoryToCompress); foreach (var folder in folders) { var dirName = Path.GetFileName(folder); if ((dirName == null) || (dirName.ToLowerInvariant() == "sample texts")) continue; // Don't want to bundle these up // Skip all subsubfolders, unless they are inside of 'activities'. if (depthFromCollection == 2 && !IsInActivitiesFolder(folder, depthFromCollection)) continue; CompressDirectory(folder, zipStream, dirNameOffset, dirNamePrefix, depthFromCollection + 1, forReaderTools, excludeAudio, reduceImages); } } // We let files through as long as they are in the 'activities' folder (widgets) or they have // one of the whitelisted extensions (BL-8956). // This method should return 'false' only if the .bloomd doesn't need this file. private static bool FileIsWhitelisted(string filePath, int depthFromCollection) { var fileExtensionLc = Path.GetExtension(filePath).ToLowerInvariant(); // Whitelist appropriate book folder level files (also applies to Collection-level files for BloomPacks) if (depthFromCollection < 2) return BookLevelFileExtensionsLowerCase.Contains(fileExtensionLc); if (depthFromCollection == 2) { var dirName = Path.GetFileName(Path.GetDirectoryName(filePath)); // Whitelist appropriate 'audio' folder files if (dirName == "audio") return AudioFileExtensions.Contains(fileExtensionLc); // Whitelist appropriate 'video' folder files if (dirName == "video") return VideoFileExtensions.Contains(fileExtensionLc); } // Whitelist any file inside of 'activities' folder at any level. if (depthFromCollection > 2 && IsInActivitiesFolder(filePath, depthFromCollection)) return true; // We accept any file in 'activities' and its subfolders // Found a file we don't need return false; } private readonly static string[] validSubFolders = { "audio", "video", "activities" }; private static bool IsValidBookFolder(string folderName, bool excludeAudio, int depthFromCollection) { // 'depthFromCollection' of 2 corresponds to the level where we want to see only the valid subfolders. // We only check depth 2. We don't check depth 1, because it is not a subfolder. We don't check // farther down, because we limit the subfolders at depth 2 and if we get deeper, we are probably // inside of 'activities' where we want everything. if (depthFromCollection != 2) return true; if (excludeAudio && folderName == "audio") return false; // BL-8956 If we have users who store other folders of (to us) junk in their book folder or // if the user somehow (as we've seen) gets a book folder embedded in another book folder, // we don't want to include those folders in our output. return validSubFolders.Contains(folderName); } private static bool IsInActivitiesFolder(string filePath, int depthFromCollection) { const string activityFolderName = "activities"; var pathToCheck = Path.GetDirectoryName(filePath); for(int i = depthFromCollection; i > 0 ; i--) { if (pathToCheck.EndsWith(Path.DirectorySeparatorChar + activityFolderName)) return true; pathToCheck = Path.GetDirectoryName(pathToCheck); } return false; } private static HashSet<string> _backgroundAudioFiles = new HashSet<string>(); private static void FindBackgroundAudioFiles(XmlDocument dom) { _backgroundAudioFiles.Clear(); foreach (var div in dom.DocumentElement.SafeSelectNodes("//div[@data-backgroundaudio]").Cast<XmlElement>()) { var filename = div.GetStringAttribute("data-backgroundaudio"); if (!String.IsNullOrEmpty(filename)) _backgroundAudioFiles.Add(filename); } } /// <summary> /// We used to record narration in a .wav file that got converted to mp3 if the user set /// up LAME when we published the book. LAME is now freely available so we automatically /// convert narration to mp3 as soon as we record it. But we never want to upload old /// narration .wav files. On the other hand, the user can select .wav files for background /// music, and we don't try to convert those so they do need to be uploaded. We detect /// this situation by saving background audio (music) filenames in an earlier pass from /// scanning the XHTML file and saving the set of filenames found. /// </summary> private static bool IsUnneededWaveFile(string filePath, int depthFromCollection) { if (Path.GetExtension(filePath).ToLowerInvariant() != ".wav") return false; // not a wave file var filename = Path.GetFileName(filePath); return !_backgroundAudioFiles.Contains(filename); } private const string kBackgroundImage = "background-image:url('"; // must match format string in HtmlDom.SetImageElementUrl() private static List<string> FindCoverImages (XmlDocument xmlDom) { var transparentImageFiles = new List<string>(); foreach (var div in xmlDom.SafeSelectNodes("//div[contains(concat(' ',@class,' '),' coverColor ')]//div[contains(@class,'bloom-imageContainer')]").Cast<XmlElement>()) { var style = div.GetAttribute("style"); if (!String.IsNullOrEmpty(style) && style.Contains(kBackgroundImage)) { System.Diagnostics.Debug.Assert(div.GetStringAttribute("class").Contains("bloom-backgroundImage")); // extract filename from the background-image style transparentImageFiles.Add(ExtractFilenameFromBackgroundImageStyleUrl(style)); } else { // extract filename from child img element var img = div.SelectSingleNode("//img[@src]"); if (img != null) transparentImageFiles.Add(System.Web.HttpUtility.UrlDecode(img.GetStringAttribute("src"))); } } return transparentImageFiles; } private static List<string> FindImagesToPreserveResolution(XmlDocument dom) { var preservedImages = new List<string>(); foreach (var div in dom.SafeSelectNodes("//div[contains(@class,'marginBox')]//div[contains(@class,'bloom-preserveResolution')]").Cast<XmlElement>()) { var style = div.GetAttribute("style"); if (!string.IsNullOrEmpty(style) && style.Contains(kBackgroundImage)) { System.Diagnostics.Debug.Assert(div.GetStringAttribute("class").Contains("bloom-backgroundImage")); preservedImages.Add(ExtractFilenameFromBackgroundImageStyleUrl(style)); } } foreach (var img in dom.SafeSelectNodes("//div[contains(@class,'marginBox')]//img[contains(@class,'bloom-preserveResolution')]").Cast<XmlElement>()) { preservedImages.Add(System.Web.HttpUtility.UrlDecode(img.GetStringAttribute("src"))); } return preservedImages; } private static string ExtractFilenameFromBackgroundImageStyleUrl(string style) { var filename = style.Substring(style.IndexOf(kBackgroundImage) + kBackgroundImage.Length); filename = filename.Substring(0, filename.IndexOf("'")); return System.Web.HttpUtility.UrlDecode(filename); } private static void MakeExtraEntry(ZipOutputStream zipStream, string name, string content) { ZipEntry entry = new ZipEntry(name); var shaBytes = Encoding.UTF8.GetBytes(content); entry.Size = shaBytes.Length; zipStream.PutNextEntry(entry); using (var memStream = new MemoryStream(shaBytes)) { StreamUtils.Copy(memStream, zipStream, new byte[1024]); } zipStream.CloseEntry(); } private static string GetMetaJsonModfiedForTemplate(string path) { var meta = BookMetaData.FromString(RobustFile.ReadAllText(path)); meta.IsSuitableForMakingShells = true; return meta.Json; } /// <summary> /// Remove any SubscriptionCode element content and replace any BrandingProjectName element /// content with the text "Default". We don't want to publish Bloom Enterprise subscription /// codes after all! /// </summary> /// <remarks> /// See https://issues.bloomlibrary.org/youtrack/issue/BL-6938. /// </remarks> private static string GetBloomCollectionModifiedForTemplate(string filePath) { var dom = new XmlDocument(); dom.PreserveWhitespace = true; dom.Load(filePath); foreach (var node in dom.SafeSelectNodes("//SubscriptionCode").Cast<XmlElement>().ToArray()) { node.RemoveAll(); // should happen at most once } foreach (var node in dom.SafeSelectNodes("//BrandingProjectName").Cast<XmlElement>().ToArray()) { node.RemoveAll(); // should happen at most once node.AppendChild(dom.CreateTextNode("Default")); } return dom.OuterXml; } /// <summary> /// Does some pre-processing on reader files /// </summary> /// <param name="bookPath"></param> private static string GetBookReplacedWithTemplate(string bookPath) { //TODO: the following, which is the original code before late in 3.6, just modified the tags in the HTML //Whereas currently, we use the meta.json as the authoritative source. //TODO Should we just get rid of these tags in the HTML? Can they be accessed from javascript? If so, //then they will be needed eventually (as we involve c# less in the UI) var text = RobustFile.ReadAllText(bookPath, Encoding.UTF8); // Note that we're getting rid of preceding newline but not following one. Hopefully we cleanly remove a whole line. // I'm not sure the </meta> ever occurs in html files, but just in case we'll match if present. var regex = new Regex("\\s*<meta\\s+name=(['\\\"])lockedDownAsShell\\1 content=(['\\\"])true\\2>(</meta>)? *"); var match = regex.Match(text); if (match.Success) text = text.Substring(0, match.Index) + text.Substring(match.Index + match.Length); // BL-2476: Readers made from BloomPacks should have the formatting dialog disabled regex = new Regex("\\s*<meta\\s+name=(['\\\"])pageTemplateSource\\1 content=(['\\\"])(Leveled|Decodable) Reader\\2>(</meta>)? *"); match = regex.Match(text); if (match.Success) { // has the lockFormatting meta tag been added already? var regexSuppress = new Regex("\\s*<meta\\s+name=(['\\\"])lockFormatting\\1 content=(['\\\"])(.*)\\2>(</meta>)? *"); var matchSuppress = regexSuppress.Match(text); if (matchSuppress.Success) { // the meta tag already exists, make sure the value is "true" if (matchSuppress.Groups[3].Value.ToLower() != "true") { text = text.Substring(0, matchSuppress.Groups[3].Index) + "true" + text.Substring(matchSuppress.Groups[3].Index + matchSuppress.Groups[3].Length); } } else { // the meta tag has not been added, add it now text = text.Insert(match.Index + match.Length, "\r\n <meta name=\"lockFormatting\" content=\"true\"></meta>"); } } return text; } // See discussion in BL-5385 private const int kMaxWidth = 600; private const int kMaxHeight = 600; /// <summary> /// For electronic books, we want to limit the dimensions of images since they'll be displayed /// on small screens. More importantly, we want to limit the size of the image file since it /// will often be transmitted over slow network connections. So rather than merely zipping up /// an image file, we set its dimensions to within our desired limit (currently 600x600px) and /// generate the bytes in the desired format. If the original image is already small enough, we /// retain its dimensions. We also make png images have transparent backgrounds if requested so /// that they will work for cover pages. If transparency is not needed, the original image file /// bytes are returned if that results in a smaller final image file. /// </summary> /// <remarks> /// Note that we have to write png files with 32-bit color even if the orginal file used 1-bit /// 4-bit, or 8-bit grayscale. So .png files may come out bigger even when the dimensions /// shrink, and likely will be bigger when the dimensions stay the same. This might be a /// limitation of the underlying .Net/Windows and Mono/Linux code, or might be needed for /// transparent backgrounds. /// </remarks> /// <returns>The bytes of the (possibly) adjusted image.</returns> internal static byte[] GetImageBytesForElectronicPub(string filePath, bool needsTransparentBackground) { var originalBytes = RobustFile.ReadAllBytes(filePath); using (var originalImage = PalasoImage.FromFileRobustly(filePath)) { var image = originalImage.Image; int originalWidth = image.Width; int originalHeight = image.Height; var appearsToBeJpeg = ImageUtils.AppearsToBeJpeg(originalImage); if (originalWidth > kMaxWidth || originalHeight > kMaxHeight || !appearsToBeJpeg) { // Preserve the aspect ratio float scaleX = (float)kMaxWidth / (float)originalWidth; float scaleY = (float)kMaxHeight / (float)originalHeight; // no point in ever expanding, even if we're making a new image just for transparency. float scale = Math.Min(1.0f, Math.Min(scaleX, scaleY)); // New width and height maintaining the aspect ratio int newWidth = (int)(originalWidth * scale); int newHeight = (int)(originalHeight * scale); var imagePixelFormat = image.PixelFormat; switch (imagePixelFormat) { // These three formats are not supported for bitmaps to be drawn on using Graphics.FromImage. // So use the default bitmap format. // Enhance: if these are common it may be worth research to find out whether there are better options. // - possibly the 'reduced' image might not be reduced...even though smaller, the indexed format // might be so much more efficient that it is smaller. However, even if that is true, it doesn't // necessarily follow that it takes less memory to render on the device. So it's not obvious that // we should keep the original just because it's a smaller file. // - possibly we don't need a 32-bit bitmap? Unfortunately the 1bpp/4bpp/8bpp only tells us // that the image uses two, 16, or 256 distinct colors, not what they are or what precision they have. case PixelFormat.Format1bppIndexed: case PixelFormat.Format4bppIndexed: case PixelFormat.Format8bppIndexed: imagePixelFormat = PixelFormat.Format32bppArgb; break; } // OTOH, always using 32-bit format for .png files keeps us from having problems in BloomReader // like BL-5740 (where 24bit format files came out in BR with black backgrounds). if (!appearsToBeJpeg) imagePixelFormat = PixelFormat.Format32bppArgb; // Image files may have unknown formats which can be read, but not written. // See https://issues.bloomlibrary.org/youtrack/issue/BH-5812. imagePixelFormat = EnsureValidPixelFormat(imagePixelFormat); var needTransparencyConversion = !appearsToBeJpeg && needsTransparentBackground && !ImageUtils.HasTransparency(image); using (var newImage = new Bitmap(newWidth, newHeight, imagePixelFormat)) { // Draws the image in the specified size with quality mode set to HighQuality using (Graphics graphics = Graphics.FromImage(newImage)) { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; using (var imageAttributes = new ImageAttributes()) { // See https://stackoverflow.com/a/11850971/7442826 // Fixes the 50% gray border issue on bright white or dark images imageAttributes.SetWrapMode(WrapMode.TileFlipXY); // In addition to possibly scaling, we want PNG images to have transparent backgrounds. if (needTransparencyConversion) { // This specifies that all white or very-near-white pixels (all color components at least 253/255) // will be made transparent. imageAttributes.SetColorKey(Color.FromArgb(253, 253, 253), Color.White); } var destRect = new Rectangle(0, 0, newWidth, newHeight); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes); } } // Save the file in the same format as the original, and return its bytes. using (var tempFile = TempFile.WithExtension(Path.GetExtension(filePath))) { // This uses default quality settings for jpgs...one site says this is // 75 quality on a scale that runs from 0-100. For most images, this // should give a quality barely distinguishable from uncompressed and still save // about 7/8 of the file size. Lower quality settings rapidly lose quality // while only saving a little space; higher ones rapidly use more space // with only marginal quality improvement. // See https://photo.stackexchange.com/questions/30243/what-quality-to-choose-when-converting-to-jpg // for more on quality and https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-set-jpeg-compression-level // for how to control the quality setting if we decide to (RobustImageIO has // suitable overloads). RobustImageIO.SaveImage(newImage, tempFile.Path, image.RawFormat); // Copy the metadata from the original file to the new file. var metadata = SIL.Windows.Forms.ClearShare.Metadata.FromFile(filePath); if (!metadata.IsEmpty) metadata.Write(tempFile.Path); var newBytes = RobustFile.ReadAllBytes(tempFile.Path); if (newBytes.Length < originalBytes.Length || needTransparencyConversion) return newBytes; } } } } return originalBytes; } private static PixelFormat EnsureValidPixelFormat(PixelFormat imagePixelFormat) { // If it's a standard, known format, return the input value. // Otherwise, return our old standby, 32bppArgb. switch (imagePixelFormat) { case PixelFormat.Format1bppIndexed: case PixelFormat.Format4bppIndexed: case PixelFormat.Format8bppIndexed: case PixelFormat.Format16bppArgb1555: case PixelFormat.Format16bppGrayScale: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: case PixelFormat.Format24bppRgb: case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppRgb: case PixelFormat.Format48bppRgb: case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: return imagePixelFormat; default: //Console.WriteLine("EnsureValidPixelFormat({0}) changed to {1}", imagePixelFormat, PixelFormat.Format32bppArgb); return PixelFormat.Format32bppArgb; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Numerics.Hashing; namespace System.Drawing { [DebuggerDisplay("{NameAndARGBValue}")] [Serializable] public struct Color : IEquatable<Color> { public static readonly Color Empty = new Color(); // ------------------------------------------------------------------- // static list of "web" colors... // public static Color Transparent => new Color(KnownColor.Transparent); public static Color AliceBlue => new Color(KnownColor.AliceBlue); public static Color AntiqueWhite => new Color(KnownColor.AntiqueWhite); public static Color Aqua => new Color(KnownColor.Aqua); public static Color Aquamarine => new Color(KnownColor.Aquamarine); public static Color Azure => new Color(KnownColor.Azure); public static Color Beige => new Color(KnownColor.Beige); public static Color Bisque => new Color(KnownColor.Bisque); public static Color Black => new Color(KnownColor.Black); public static Color BlanchedAlmond => new Color(KnownColor.BlanchedAlmond); public static Color Blue => new Color(KnownColor.Blue); public static Color BlueViolet => new Color(KnownColor.BlueViolet); public static Color Brown => new Color(KnownColor.Brown); public static Color BurlyWood => new Color(KnownColor.BurlyWood); public static Color CadetBlue => new Color(KnownColor.CadetBlue); public static Color Chartreuse => new Color(KnownColor.Chartreuse); public static Color Chocolate => new Color(KnownColor.Chocolate); public static Color Coral => new Color(KnownColor.Coral); public static Color CornflowerBlue => new Color(KnownColor.CornflowerBlue); public static Color Cornsilk => new Color(KnownColor.Cornsilk); public static Color Crimson => new Color(KnownColor.Crimson); public static Color Cyan => new Color(KnownColor.Cyan); public static Color DarkBlue => new Color(KnownColor.DarkBlue); public static Color DarkCyan => new Color(KnownColor.DarkCyan); public static Color DarkGoldenrod => new Color(KnownColor.DarkGoldenrod); public static Color DarkGray => new Color(KnownColor.DarkGray); public static Color DarkGreen => new Color(KnownColor.DarkGreen); public static Color DarkKhaki => new Color(KnownColor.DarkKhaki); public static Color DarkMagenta => new Color(KnownColor.DarkMagenta); public static Color DarkOliveGreen => new Color(KnownColor.DarkOliveGreen); public static Color DarkOrange => new Color(KnownColor.DarkOrange); public static Color DarkOrchid => new Color(KnownColor.DarkOrchid); public static Color DarkRed => new Color(KnownColor.DarkRed); public static Color DarkSalmon => new Color(KnownColor.DarkSalmon); public static Color DarkSeaGreen => new Color(KnownColor.DarkSeaGreen); public static Color DarkSlateBlue => new Color(KnownColor.DarkSlateBlue); public static Color DarkSlateGray => new Color(KnownColor.DarkSlateGray); public static Color DarkTurquoise => new Color(KnownColor.DarkTurquoise); public static Color DarkViolet => new Color(KnownColor.DarkViolet); public static Color DeepPink => new Color(KnownColor.DeepPink); public static Color DeepSkyBlue => new Color(KnownColor.DeepSkyBlue); public static Color DimGray => new Color(KnownColor.DimGray); public static Color DodgerBlue => new Color(KnownColor.DodgerBlue); public static Color Firebrick => new Color(KnownColor.Firebrick); public static Color FloralWhite => new Color(KnownColor.FloralWhite); public static Color ForestGreen => new Color(KnownColor.ForestGreen); public static Color Fuchsia => new Color(KnownColor.Fuchsia); public static Color Gainsboro => new Color(KnownColor.Gainsboro); public static Color GhostWhite => new Color(KnownColor.GhostWhite); public static Color Gold => new Color(KnownColor.Gold); public static Color Goldenrod => new Color(KnownColor.Goldenrod); public static Color Gray => new Color(KnownColor.Gray); public static Color Green => new Color(KnownColor.Green); public static Color GreenYellow => new Color(KnownColor.GreenYellow); public static Color Honeydew => new Color(KnownColor.Honeydew); public static Color HotPink => new Color(KnownColor.HotPink); public static Color IndianRed => new Color(KnownColor.IndianRed); public static Color Indigo => new Color(KnownColor.Indigo); public static Color Ivory => new Color(KnownColor.Ivory); public static Color Khaki => new Color(KnownColor.Khaki); public static Color Lavender => new Color(KnownColor.Lavender); public static Color LavenderBlush => new Color(KnownColor.LavenderBlush); public static Color LawnGreen => new Color(KnownColor.LawnGreen); public static Color LemonChiffon => new Color(KnownColor.LemonChiffon); public static Color LightBlue => new Color(KnownColor.LightBlue); public static Color LightCoral => new Color(KnownColor.LightCoral); public static Color LightCyan => new Color(KnownColor.LightCyan); public static Color LightGoldenrodYellow => new Color(KnownColor.LightGoldenrodYellow); public static Color LightGreen => new Color(KnownColor.LightGreen); public static Color LightGray => new Color(KnownColor.LightGray); public static Color LightPink => new Color(KnownColor.LightPink); public static Color LightSalmon => new Color(KnownColor.LightSalmon); public static Color LightSeaGreen => new Color(KnownColor.LightSeaGreen); public static Color LightSkyBlue => new Color(KnownColor.LightSkyBlue); public static Color LightSlateGray => new Color(KnownColor.LightSlateGray); public static Color LightSteelBlue => new Color(KnownColor.LightSteelBlue); public static Color LightYellow => new Color(KnownColor.LightYellow); public static Color Lime => new Color(KnownColor.Lime); public static Color LimeGreen => new Color(KnownColor.LimeGreen); public static Color Linen => new Color(KnownColor.Linen); public static Color Magenta => new Color(KnownColor.Magenta); public static Color Maroon => new Color(KnownColor.Maroon); public static Color MediumAquamarine => new Color(KnownColor.MediumAquamarine); public static Color MediumBlue => new Color(KnownColor.MediumBlue); public static Color MediumOrchid => new Color(KnownColor.MediumOrchid); public static Color MediumPurple => new Color(KnownColor.MediumPurple); public static Color MediumSeaGreen => new Color(KnownColor.MediumSeaGreen); public static Color MediumSlateBlue => new Color(KnownColor.MediumSlateBlue); public static Color MediumSpringGreen => new Color(KnownColor.MediumSpringGreen); public static Color MediumTurquoise => new Color(KnownColor.MediumTurquoise); public static Color MediumVioletRed => new Color(KnownColor.MediumVioletRed); public static Color MidnightBlue => new Color(KnownColor.MidnightBlue); public static Color MintCream => new Color(KnownColor.MintCream); public static Color MistyRose => new Color(KnownColor.MistyRose); public static Color Moccasin => new Color(KnownColor.Moccasin); public static Color NavajoWhite => new Color(KnownColor.NavajoWhite); public static Color Navy => new Color(KnownColor.Navy); public static Color OldLace => new Color(KnownColor.OldLace); public static Color Olive => new Color(KnownColor.Olive); public static Color OliveDrab => new Color(KnownColor.OliveDrab); public static Color Orange => new Color(KnownColor.Orange); public static Color OrangeRed => new Color(KnownColor.OrangeRed); public static Color Orchid => new Color(KnownColor.Orchid); public static Color PaleGoldenrod => new Color(KnownColor.PaleGoldenrod); public static Color PaleGreen => new Color(KnownColor.PaleGreen); public static Color PaleTurquoise => new Color(KnownColor.PaleTurquoise); public static Color PaleVioletRed => new Color(KnownColor.PaleVioletRed); public static Color PapayaWhip => new Color(KnownColor.PapayaWhip); public static Color PeachPuff => new Color(KnownColor.PeachPuff); public static Color Peru => new Color(KnownColor.Peru); public static Color Pink => new Color(KnownColor.Pink); public static Color Plum => new Color(KnownColor.Plum); public static Color PowderBlue => new Color(KnownColor.PowderBlue); public static Color Purple => new Color(KnownColor.Purple); public static Color Red => new Color(KnownColor.Red); public static Color RosyBrown => new Color(KnownColor.RosyBrown); public static Color RoyalBlue => new Color(KnownColor.RoyalBlue); public static Color SaddleBrown => new Color(KnownColor.SaddleBrown); public static Color Salmon => new Color(KnownColor.Salmon); public static Color SandyBrown => new Color(KnownColor.SandyBrown); public static Color SeaGreen => new Color(KnownColor.SeaGreen); public static Color SeaShell => new Color(KnownColor.SeaShell); public static Color Sienna => new Color(KnownColor.Sienna); public static Color Silver => new Color(KnownColor.Silver); public static Color SkyBlue => new Color(KnownColor.SkyBlue); public static Color SlateBlue => new Color(KnownColor.SlateBlue); public static Color SlateGray => new Color(KnownColor.SlateGray); public static Color Snow => new Color(KnownColor.Snow); public static Color SpringGreen => new Color(KnownColor.SpringGreen); public static Color SteelBlue => new Color(KnownColor.SteelBlue); public static Color Tan => new Color(KnownColor.Tan); public static Color Teal => new Color(KnownColor.Teal); public static Color Thistle => new Color(KnownColor.Thistle); public static Color Tomato => new Color(KnownColor.Tomato); public static Color Turquoise => new Color(KnownColor.Turquoise); public static Color Violet => new Color(KnownColor.Violet); public static Color Wheat => new Color(KnownColor.Wheat); public static Color White => new Color(KnownColor.White); public static Color WhiteSmoke => new Color(KnownColor.WhiteSmoke); public static Color Yellow => new Color(KnownColor.Yellow); public static Color YellowGreen => new Color(KnownColor.YellowGreen); // // end "web" colors // ------------------------------------------------------------------- // NOTE : The "zero" pattern (all members being 0) must represent // : "not set". This allows "Color c;" to be correct. private const short StateKnownColorValid = 0x0001; private const short StateARGBValueValid = 0x0002; private const short StateValueMask = StateARGBValueValid; private const short StateNameValid = 0x0008; private const long NotDefinedValue = 0; /** * Shift count and bit mask for A, R, G, B components in ARGB mode! */ private const int ARGBAlphaShift = 24; private const int ARGBRedShift = 16; private const int ARGBGreenShift = 8; private const int ARGBBlueShift = 0; // user supplied name of color. Will not be filled in if // we map to a "knowncolor" // private readonly string name; // will contain standard 32bit sRGB (ARGB) // private readonly long value; // ignored, unless "state" says it is valid // private readonly short knownColor; // implementation specific information // private readonly short state; internal Color(KnownColor knownColor) { value = 0; state = StateKnownColorValid; name = null; this.knownColor = unchecked((short)knownColor); } private Color(long value, short state, string name, KnownColor knownColor) { this.value = value; this.state = state; this.name = name; this.knownColor = unchecked((short)knownColor); } public byte R => (byte)((Value >> ARGBRedShift) & 0xFF); public byte G => (byte)((Value >> ARGBGreenShift) & 0xFF); public byte B => (byte)((Value >> ARGBBlueShift) & 0xFF); public byte A => (byte)((Value >> ARGBAlphaShift) & 0xFF); private bool IsKnownColor => ((state & StateKnownColorValid) != 0); public bool IsEmpty => state == 0; public bool IsNamedColor => ((state & StateNameValid) != 0) || IsKnownColor; // Not localized because it's only used for the DebuggerDisplayAttribute, and the values are // programmatic items. // Also, don't inline into the attribute for performance reasons. This way means the debugger // does 1 func-eval instead of 5. [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] private string NameAndARGBValue => $"{{Name={Name}, ARGB=({A}, {R}, {G}, {B})}}"; public string Name { get { if ((state & StateNameValid) != 0) { return name; } if (IsKnownColor) { string tablename = KnownColorTable.KnownColorToName((KnownColor)knownColor); Debug.Assert(tablename != null, $"Could not find known color '{(KnownColor)knownColor}' in the KnownColorTable"); return tablename; } // if we reached here, just encode the value // return Convert.ToString(value, 16); } } private long Value { get { if ((state & StateValueMask) != 0) { return value; } if (IsKnownColor) { return KnownColorTable.KnownColorToArgb((KnownColor)knownColor); } return NotDefinedValue; } } private static void CheckByte(int value, string name) { if (value < 0 || value > 255) throw new ArgumentException(SR.Format(SR.InvalidEx2BoundArgument, name, value, 0, 255)); } private static long MakeArgb(byte alpha, byte red, byte green, byte blue) => (long)unchecked((uint)(red << ARGBRedShift | green << ARGBGreenShift | blue << ARGBBlueShift | alpha << ARGBAlphaShift)) & 0xffffffff; public static Color FromArgb(int argb) => new Color(argb & 0xffffffff, StateARGBValueValid, null, 0); public static Color FromArgb(int alpha, int red, int green, int blue) { CheckByte(alpha, nameof(alpha)); CheckByte(red, nameof(red)); CheckByte(green, nameof(green)); CheckByte(blue, nameof(blue)); return new Color(MakeArgb((byte)alpha, (byte)red, (byte)green, (byte)blue), StateARGBValueValid, null, (KnownColor)0); } public static Color FromArgb(int alpha, Color baseColor) { CheckByte(alpha, nameof(alpha)); // unchecked - because we already checked that alpha is a byte in CheckByte above return new Color(MakeArgb(unchecked((byte)alpha), baseColor.R, baseColor.G, baseColor.B), StateARGBValueValid, null, (KnownColor)0); } public static Color FromArgb(int red, int green, int blue) => FromArgb(255, red, green, blue); private static Color FromKnownColor(KnownColor color) { var value = (int)color; if (value < (int)KnownColor.FirstColor || value > (int)KnownColor.LastColor) { return FromName(color.ToString()); } return new Color(color); } public static Color FromName(string name) { // try to get a known color first Color color; if (ColorTable.TryGetNamedColor(name, out color)) { return color; } // otherwise treat it as a named color return new Color(NotDefinedValue, StateNameValid, name, (KnownColor)0); } public float GetBrightness() { float r = R / 255.0f; float g = G / 255.0f; float b = B / 255.0f; float max, min; max = r; min = r; if (g > max) max = g; if (b > max) max = b; if (g < min) min = g; if (b < min) min = b; return (max + min) / 2; } public Single GetHue() { if (R == G && G == B) return 0; // 0 makes as good an UNDEFINED value as any float r = R / 255.0f; float g = G / 255.0f; float b = B / 255.0f; float max, min; float delta; float hue = 0.0f; max = r; min = r; if (g > max) max = g; if (b > max) max = b; if (g < min) min = g; if (b < min) min = b; delta = max - min; if (r == max) { hue = (g - b) / delta; } else if (g == max) { hue = 2 + (b - r) / delta; } else if (b == max) { hue = 4 + (r - g) / delta; } hue *= 60; if (hue < 0.0f) { hue += 360.0f; } return hue; } public float GetSaturation() { float r = R / 255.0f; float g = G / 255.0f; float b = B / 255.0f; float s = 0; float max = r; float min = r; if (g > max) max = g; if (b > max) max = b; if (g < min) min = g; if (b < min) min = b; // if max == min, then there is no color and // the saturation is zero. // if (max != min) { float l = (max + min) / 2; if (l <= .5) { s = (max - min) / (max + min); } else { s = (max - min) / (2 - max - min); } } return s; } public int ToArgb() => unchecked((int)Value); private KnownColor ToKnownColor() => (KnownColor)knownColor; public override string ToString() { if ((state & StateNameValid) != 0 || (state & StateKnownColorValid) != 0) { return nameof(Color) + " [" + Name + "]"; } else if ((state & StateValueMask) != 0) { return nameof(Color) + " [A=" + A.ToString() + ", R=" + R.ToString() + ", G=" + G.ToString() + ", B=" + B.ToString() + "]"; } else { return nameof(Color) + " [Empty]"; } } public static bool operator ==(Color left, Color right) => left.value == right.value && left.state == right.state && left.knownColor == right.knownColor && left.name == right.name; public static bool operator !=(Color left, Color right) => !(left == right); public override bool Equals(object obj) => obj is Color && Equals((Color)obj); public bool Equals(Color other) => this == other; public override int GetHashCode() { // Three cases: // 1. We don't have a name. All relevant data, including this fact, is in the remaining fields. // 2. We have a known name. The name will be the same instance of any other with the same // knownColor value, so we can ignore it for hashing. Note this also hashes different to // an unnamed color with the same ARGB value. // 3. Have an unknown name. Will differ from other unknown-named colors only by name, so we // can usefully use the names hash code alone. if (name != null & !IsKnownColor) return name.GetHashCode(); return HashHelpers.Combine( HashHelpers.Combine(value.GetHashCode(), state.GetHashCode()), knownColor.GetHashCode()); } } }
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.ComponentModel; using System.Text; using System.Drawing.Design; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using AjaxControlToolkit; namespace ACSGhana.Web.Framework { namespace UI { namespace Controls { [ToolboxData("<{0}:ModalForm runat=server></{0}:ModalForm>")]public class ModalForm : Panel { #region Class Level Variables //Control property variables. private string _title = ""; private string _contentCss = ""; private string _headerCss = ""; private string _closeImageUrl = ""; private string _backgroundCss = ""; private bool _dropShadow = false; private string _okControlId = ""; private string _cancelControlId = ""; private string _onOkScript = ""; private string _activateControlId = ""; //ModalPopup extender associated with this panel. private ModalPopupExtender extender = null; private Panel header = null; private const string DragInclude = "Drag"; private const string ModalFormInclude = "ModalForm"; #endregion // Class Level Variables #region Constructor public ModalForm() { } #endregion // Constructor #region Properties [Bindable(true), Category("Header Appearance"), DefaultValue(""), Themeable(false), Description("The title in the header of the form.")]public string Title { get { return _title; } set { _title = value; } } [Bindable(true), Category("Header Appearance"), DefaultValue(""), Editor(typeof(ImageUrlEditor), typeof(UITypeEditor)), Description("The image to use as the close icon in the header.")]public string CloseImageUrl { get { return _closeImageUrl; } set { _closeImageUrl = value; } } [Bindable(true), Category("Appearance"), DefaultValue(""), Description("Stylesheet class to apply to the content area.")]public string ContentCss { get { return _contentCss; } set { _contentCss = value; } } [Bindable(true), Category("Appearance"), DefaultValue(""), Description("Stylesheet class to apply to the header area.")]public string HeaderCss { get { return _headerCss; } set { _headerCss = value; } } [Bindable(true), Category("Appearance"), DefaultValue(""), Description("The stylesheet that describes that background that will fill the screen when the modal form is loaded.")]public string BackgroundCss { get { return _backgroundCss; } set { _backgroundCss = value; } } [Bindable(true), Category("Appearance"), DefaultValue(false), Description("Should a drop shadow appear behind the modal form.")]public bool DropShadow { get { return DropShadow; } set { _dropShadow = value; } } [Bindable(true), Category("Behavior"), DefaultValue(""), Description("The ID of the control that will signal a save of the modal form.")]public string OkControlID { get { return _okControlId; } set { _okControlId = value; } } [Bindable(true), Category("Behavior"), DefaultValue(""), Description("The ID of the control that will cancel out of the modal form.")]public string CancelControlID { get { return _cancelControlId; } set { _cancelControlId = value; } } [Bindable(true), Category("Behavior"), DefaultValue(""), Description("The client side javascript function that should execute when the modal form is saved.")]public string OnOkScript { get { return _onOkScript; } set { _onOkScript = value; } } [Bindable(true), Category("Behavior"), DefaultValue(""), Description("The ID of the control that will activate the modal form.")]public string ActivateControlID { get { return _activateControlId; } set { _activateControlId = value; } } #endregion // Properties #region Methods /// <summary> /// Force the creation of child controls now so that the ModalPopup extender is created on init. /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { EnsureChildControls(); base.OnInit(e); } /// <summary> /// Create the ModalPopup extender and add it as a child of this control. /// </summary> protected override void CreateChildControls() { base.CreateChildControls(); // Create the extender extender = new ModalPopupExtender(); extender.ID = ID + "_ModalPopupExtender"; //Pass on ModalPopup extender properties of this control to the extender. extender.TargetControlID = ActivateControlID; extender.BackgroundCssClass = BackgroundCss; extender.CancelControlID = CancelControlID; extender.OkControlID = OkControlID; extender.DropShadow = DropShadow; extender.OnOkScript = OnOkScript; extender.PopupControlID = ID; if (! this.DesignMode) { Controls.AddAt(0, extender); } } /// <summary> /// Register javascript needed. /// </summary> /// <param name="e"></param> protected override void OnPreRender(EventArgs e) { Page.ClientScript.RegisterClientScriptInclude(DragInclude, Page.ClientScript.GetWebResourceUrl(this.GetType(), "ACSGhana.Web.Framework.Drag.js")); Page.ClientScript.RegisterClientScriptInclude(ModalFormInclude, Page.ClientScript.GetWebResourceUrl(this.GetType(), "ACSGhana.Web.Framework.ModalForm.js")); //Create the header and content panels and add them to the base panel. header = CreateContainerControls(); base.OnPreRender(e); } /// <summary> /// Render HTML for control. /// </summary> /// <param name="output"></param> protected override void Render(HtmlTextWriter output) { base.Render(output); //Include the script to make the modal form draggable. string script = string.Format("<script type=\'text/javascript\' language=\'javascript\'>" + "<!--" + Constants.vbLf + "MakeDraggableHandle(document.getElementById(\"{0}\"), \"{1}\");" + Constants.vbLf + "-->" + Constants.vbLf + "</script>" + Constants.vbLf, header.ClientID, this.ClientID); output.Write(script); } /// <summary> /// Create the header and content panels and place the existing child controls in the content panel. /// </summary> private Panel CreateContainerControls() { Panel header = new Panel(); header.ID = "Header"; header.CssClass = this.HeaderCss; Panel title = new Panel(); //Add title text to title panel. LiteralControl titleText = new LiteralControl(this.Title); title.Controls.Add(titleText); //Place title on left of header panel. title.Style.Add("float", "left"); //Only create a close image panel if a close image and cancel control id have been specified. HtmlImage imageButton = null; if (CloseImageUrl != "" && CancelControlID != "") { Panel closeImage = new Panel(); //Add image to image panel. imageButton = new HtmlImage(); imageButton.ID = "button"; imageButton.Border = 0; imageButton.Src = GetCloseImageUrl(); imageButton.Style.Add("cursor", "pointer"); closeImage.Controls.Add(imageButton); //Place image on right of header panel. closeImage.Style.Add("float", "right"); header.Controls.Add(closeImage); } header.Controls.Add(title); Panel content = new Panel(); content.CssClass = this.ContentCss; //Move all the children of the base panel to the children of the content panel. //Note as a child control is added to content, it is automatically removed from the base panel. int numChildren = this.Controls.Count; int i = 0; while (i < numChildren) { content.Controls.Add(this.Controls[0]); i++; } //Clear all the children of the base panel and add the header and content panels. Controls.Clear(); Controls.Add(header); Controls.Add(content); //Now that all controls are in their proper places, create the cancel javascript for the CancelControlId. if (CloseImageUrl != "" && CancelControlID != "") { imageButton.Attributes.Add("onClick", GetCloseScript()); } //Make sure this panel is hidden to begin. this.Style.Add("display", "none"); return header; } /// <summary> /// Get the javascript to close the modal form. /// </summary> /// <returns> /// The javascript which forces a click on the cancel control. /// </returns> private string GetCloseScript() { System.Web.UI.Control cancelControl = GetControl(this, CancelControlID); if (cancelControl != null) { return string.Format("ModalFormClose(\"{0}\")", cancelControl.ClientID); //strScript } else { return ""; } } /// <summary> /// Perform a recursive search for the indicated control. /// </summary> /// <param name="root"> /// The control whose children should be searched for the indicated control. /// </param> /// <param name="id"> /// The id of the control to get. /// </param> /// <returns> /// The control with the indicated id. /// </returns> private System.Web.UI.Control GetControl(System.Web.UI.Control root, string id) { if (root.ID == id) { return root; } foreach (System.Web.UI.Control c in root.Controls) { System.Web.UI.Control t = GetControl(c, id); if (t != null) { return t; } } return null; } /// <summary> /// Get the url for the close image, taking into account any active theme. /// </summary> /// <returns> /// The url for the close image, taking into account any active theme. /// </returns> private string GetCloseImageUrl() { string image = CloseImageUrl; //Look for image in theme specific Images directory if a theme is in use. if (Page.Theme != "") { //Check to see if this file exists. if (File.Exists(Page.Request.MapPath("~") + "/App_Themes/" + Page.Theme + "/" + image)) { image = "App_Themes/" + Page.Theme + "/" + image; } } return image; } #endregion // Methods } } } }
// ----------------------------------------------------------------------- // <copyright file="WindowTests.cs" company="Steven Kirk"> // Copyright 2015 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { public class WindowTests { [Fact] public void Setting_Title_Should_Set_Impl_Title() { var windowImpl = new Mock<IWindowImpl>(); var windowingPlatform = new MockWindowingPlatform(() => windowImpl.Object); using (UnitTestApplication.Start(new TestServices(windowingPlatform: windowingPlatform))) { var target = new Window(); target.Title = "Hello World"; windowImpl.Verify(x => x.SetTitle("Hello World")); } } [Fact] public void IsVisible_Should_Initially_Be_False() { using (UnitTestApplication.Start(TestServices.MockWindowingPlatform)) { var window = new Window(); Assert.False(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_True_After_Show() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(); window.Show(); Assert.True(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_True_After_ShowDialog() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(); var task = window.ShowDialog(); Assert.True(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_False_Atfer_Hide() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(); window.Show(); window.Hide(); Assert.False(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_False_Atfer_Close() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(); window.Show(); window.Close(); Assert.False(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_False_Atfer_Impl_Signals_Close() { var windowImpl = new Mock<IWindowImpl>(); windowImpl.SetupProperty(x => x.Closed); windowImpl.Setup(x => x.Scaling).Returns(1); var services = TestServices.StyledWindow.With( windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object)); using (UnitTestApplication.Start(services)) { var window = new Window(); window.Show(); windowImpl.Object.Closed(); Assert.False(window.IsVisible); } } [Fact] public void Show_Should_Add_Window_To_OpenWindows() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { ClearOpenWindows(); var window = new Window(); window.Show(); Assert.Equal(new[] { window }, Window.OpenWindows); } } [Fact] public void Window_Should_Be_Added_To_OpenWindows_Only_Once() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { ClearOpenWindows(); var window = new Window(); window.Show(); window.Show(); window.IsVisible = true; Assert.Equal(new[] { window }, Window.OpenWindows); window.Close(); } } [Fact] public void Close_Should_Remove_Window_From_OpenWindows() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { ClearOpenWindows(); var window = new Window(); window.Show(); window.Close(); Assert.Empty(Window.OpenWindows); } } [Fact] public void Impl_Closing_Should_Remove_Window_From_OpenWindows() { var windowImpl = new Mock<IWindowImpl>(); windowImpl.SetupProperty(x => x.Closed); windowImpl.Setup(x => x.Scaling).Returns(1); var services = TestServices.StyledWindow.With( windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object)); using (UnitTestApplication.Start(services)) { ClearOpenWindows(); var window = new Window(); window.Show(); windowImpl.Object.Closed(); Assert.Empty(Window.OpenWindows); } } [Fact] public void Showing_Should_Start_Renderer() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var renderer = new Mock<IRenderer>(); var target = new Window(CreateImpl(renderer)); target.Show(); renderer.Verify(x => x.Start(), Times.Once); } } [Fact] public void ShowDialog_Should_Start_Renderer() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var renderer = new Mock<IRenderer>(); var target = new Window(CreateImpl(renderer)); target.Show(); renderer.Verify(x => x.Start(), Times.Once); } } [Fact] public void Hiding_Should_Stop_Renderer() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var renderer = new Mock<IRenderer>(); var target = new Window(CreateImpl(renderer)); target.Show(); target.Hide(); renderer.Verify(x => x.Stop(), Times.Once); } } private void ClearOpenWindows() { // HACK: We really need a decent way to have "statics" that can be scoped to // AvaloniaLocator scopes. ((IList<Window>)Window.OpenWindows).Clear(); } private IWindowImpl CreateImpl(Mock<IRenderer> renderer) { return Mock.Of<IWindowImpl>(x => x.Scaling == 1 && x.CreateRenderer(It.IsAny<IRenderRoot>()) == renderer.Object); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Timers; using peer; using ServerExperiment; namespace socketSrv { class Client { TcpClient tcpClient = new TcpClient(AddressFamily.InterNetwork); peerInstance myServer = new peerInstance(); NetworkStream clientStream; public Timer clientTimer = new Timer(); //clientTimer.ElapsedEventArgs += timer public List<commandMessage> clientQueue = new List<commandMessage>(); public Client() { this.clientTimer.Elapsed += new ElapsedEventHandler (timer_Elapsed); } public void setServer(peerInstance p) { myServer.peerIP = p.peerIP; myServer.peerPort = p.peerPort; } public bool isClientMessage() { bool returnBool = false; if (clientQueue.Count > 0) returnBool = true; return returnBool; } public List<commandMessage> returnClientQueue() { checkForData(); List<commandMessage> tempQueue = new List<commandMessage>(); tempQueue = clientQueue; //if (clientQueue.Count > 1) //{ // //lock(serverQueue) // //{ // clientQueue.Clear(); // //} //} return tempQueue; } public void checkForData() { commandMessage cmd = new commandMessage(); cmd.command = Int32.MaxValue; int bufSize = 1500; byte[] buffer = new byte[bufSize]; if (clientStream.DataAvailable) { byte [] messageSizeBytes = new byte[4]; byte[] addressBytes = new byte[4]; byte[] portBytes = new byte[4]; byte [] cmdBytes = new byte[4]; byte [] fileSizeBytes = new byte[4]; byte [] fileNameSizeBytes = new byte[4]; byte[] srcIpBytes = new byte[4]; int messageSize, fileSize, fileNameSize, byteCnt; //gotta process the data int bytesRead = clientStream.Read(buffer,0,bufSize); if (bytesRead > 0) { byteCnt = 0; System.Buffer.BlockCopy(buffer, byteCnt, messageSizeBytes, 0, messageSizeBytes.Length); byteCnt += messageSizeBytes.Length; messageSize = BitConverter.ToInt32(messageSizeBytes,0); //messageSize should never be greater than 1500 in this case System.Buffer.BlockCopy(buffer, byteCnt, addressBytes, 0, addressBytes.Length); byteCnt += addressBytes.Length; //cmdIP = IPAddress.Parse( string address = ""; if (addressBytes.Length == 4) { address = addressBytes[0].ToString() + "." + addressBytes[1].ToString() + "." + addressBytes[2].ToString() + "." + addressBytes[3].ToString(); } cmd.peerIP = IPAddress.Parse(address); System.Buffer.BlockCopy(buffer, byteCnt, portBytes, 0, portBytes.Length); byteCnt += portBytes.Length; cmd.port = BitConverter.ToInt32(portBytes,0); System.Buffer.BlockCopy(buffer, byteCnt, cmdBytes, 0, cmdBytes.Length); byteCnt += cmdBytes.Length; cmd.command = BitConverter.ToInt32(cmdBytes,0); System.Buffer.BlockCopy(buffer, byteCnt, fileSizeBytes, 0, fileSizeBytes.Length); byteCnt += fileSizeBytes.Length; fileSize = BitConverter.ToInt32(fileSizeBytes, 0); System.Buffer.BlockCopy(buffer, byteCnt, fileNameSizeBytes, 0, fileNameSizeBytes.Length); byteCnt += fileNameSizeBytes.Length; fileNameSize = BitConverter.ToInt32(fileNameSizeBytes, 0); UTF8Encoding utf8 = new UTF8Encoding(); byte[] fileNameBytes = new byte[fileNameSize]; System.Buffer.BlockCopy(buffer, byteCnt, fileNameBytes, 0, fileNameSize); cmd.fileName = utf8.GetString(fileNameBytes); byteCnt += fileNameSize; System.Buffer.BlockCopy(buffer, byteCnt, srcIpBytes, 0, srcIpBytes.Length); cmd.srcIP = IPAddress.Parse(address); address = ""; if (srcIpBytes.Length == 4) { address = srcIpBytes[0].ToString() + "." + srcIpBytes[1].ToString() + "." + srcIpBytes[2].ToString() + "." + srcIpBytes[3].ToString(); } if (cmd.command == 3) cmd.putIP = IPAddress.Parse(address); //Console.WriteLine("in client process. Command is {0} and srcIP is {1}", cmd.command, cmd.srcIP); clientQueue.Add(cmd); //Program.p2p.clientProcessedQueue.Add(cmd); } } } public void connectToServer() { IPHostEntry serverIP = Dns.GetHostEntry(myServer.peerIP.ToString()); tcpClient = new TcpClient(serverIP.HostName, myServer.peerPort); clientStream = tcpClient.GetStream(); } public void SendCmd (socketSrv.commandMessage cmd) { byte [] buffer = new byte[1500]; byte [] cmdBytes = new byte[4]; byte [] msgLenBytes = new byte[4]; byte [] addressBytes = new byte[4]; byte [] portBytes = new byte[4]; byte[] fileNameBytes = new byte[75]; byte[] fileNameSizeBytes = new byte[4]; byte[] fileSizeBytes = new byte[4]; byte[] srcIpBytes = new byte[4]; //switch( cmd.command) //{ //case 2: //get file //check processedQueue for cmd for (int i = 0; i < Program.p2p.serverProcessedQueue.Count;i++) { if ((Program.p2p.serverProcessedQueue[i].peerIP.Address == cmd.peerIP.Address) && (Program.p2p.serverProcessedQueue[i].fileName == cmd.fileName)) { //Console.WriteLine("Got duplicate cmd. Aborting send."); return; } } Console.WriteLine("\nSent request to server machine"); clientTimer.Interval = 5000; clientTimer.Start (); //int basicCmdLen = 16; int byteCnt = 4; cmdBytes = BitConverter.GetBytes(cmd.command); addressBytes = cmd.peerIP.GetAddressBytes(); portBytes = BitConverter.GetBytes(cmd.port); System.Buffer.BlockCopy(addressBytes, 0, buffer, byteCnt, addressBytes.Length); byteCnt += addressBytes.Length; System.Buffer.BlockCopy(portBytes, 0, buffer, byteCnt, portBytes.Length); byteCnt += portBytes.Length; System.Buffer.BlockCopy(cmdBytes, 0, buffer, byteCnt, cmdBytes.Length); byteCnt += cmdBytes.Length; UTF8Encoding utf8 = new UTF8Encoding(); fileNameBytes = utf8.GetBytes(cmd.fileName); int fileNameLen = utf8.GetByteCount(cmd.fileName); fileSizeBytes = BitConverter.GetBytes(0); fileNameSizeBytes = BitConverter.GetBytes(fileNameLen); System.Buffer.BlockCopy(fileSizeBytes, 0, buffer, byteCnt, fileSizeBytes.Length); byteCnt += fileSizeBytes.Length; System.Buffer.BlockCopy(fileNameSizeBytes, 0, buffer, byteCnt, fileNameSizeBytes.Length); byteCnt += fileNameSizeBytes.Length; System.Buffer.BlockCopy(fileNameBytes, 0, buffer, byteCnt, fileNameLen); byteCnt += fileNameLen; if (cmd.command == 2) { srcIpBytes = Program.p2p.myAddress.GetAddressBytes(); System.Buffer.BlockCopy(srcIpBytes, 0, buffer, byteCnt, srcIpBytes.Length); byteCnt += srcIpBytes.Length; } else if (cmd.command == 3) { srcIpBytes = cmd.putIP.GetAddressBytes(); System.Buffer.BlockCopy(srcIpBytes, 0, buffer, byteCnt, srcIpBytes.Length); byteCnt += srcIpBytes.Length; } int msgLen = byteCnt; msgLenBytes = BitConverter.GetBytes(msgLen); System.Buffer.BlockCopy(msgLenBytes, 0, buffer, 0, msgLenBytes.Length); //if (cmd.srcIP.Address.ToString() == "0.0.0.0") cmd.srcIP = Program.p2p.myAddress; if ((cmd.srcIP.Address != cmd.peerIP.Address) || (Program.p2p.serverProcessedQueue.Count == 0)) { clientStream.Write(buffer, 0, msgLen); //Console.WriteLine("sent a message of {0} bytes asking for file", msgLen); } //add command to serverProcessedQueue Program.p2p.serverProcessedQueue.Add(cmd); //break; //case 3: //put file // Console.WriteLine("got a put"); // break; //} } void timer_Elapsed(object sender, ElapsedEventArgs e) { DateTime now = DateTime.Now; clientTimer.Stop (); //find server messages older than 1 minute for (int i = Program.p2p.serverProcessedQueue.Count-1; i >= 0; i--) { if (Program.p2p.serverProcessedQueue [i].timeStamp.AddMinutes (1) >= now) { //Console.WriteLine("{0} file not received socket timed out.", Program.p2p.serverProcessedQueue[i].fileName); Program.p2p.serverProcessedQueue.RemoveAt (i); } } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Dispatcher { using System; using System.Collections.Generic; using System.ServiceModel.Diagnostics; using System.Runtime; using System.ServiceModel.Channels; using System.Threading; class BufferedReceiveBinder : IChannelBinder { static Action<object> tryReceive = new Action<object>(BufferedReceiveBinder.TryReceive); static AsyncCallback tryReceiveCallback = Fx.ThunkCallback(new AsyncCallback(TryReceiveCallback)); IChannelBinder channelBinder; InputQueue<RequestContextWrapper> inputQueue; [Fx.Tag.SynchronizationObject(Blocking = true, Kind = Fx.Tag.SynchronizationKind.InterlockedNoSpin)] int pendingOperationSemaphore; public BufferedReceiveBinder(IChannelBinder channelBinder) { this.channelBinder = channelBinder; this.inputQueue = new InputQueue<RequestContextWrapper>(); } public IChannel Channel { get { return this.channelBinder.Channel; } } public bool HasSession { get { return this.channelBinder.HasSession; } } public Uri ListenUri { get { return this.channelBinder.ListenUri; } } public EndpointAddress LocalAddress { get { return this.channelBinder.LocalAddress; } } public EndpointAddress RemoteAddress { get { return this.channelBinder.RemoteAddress; } } public void Abort() { this.inputQueue.Close(); this.channelBinder.Abort(); } public void CloseAfterFault(TimeSpan timeout) { this.inputQueue.Close(); this.channelBinder.CloseAfterFault(timeout); } // Locking: // Only 1 channelBinder operation call should be active at any given time. All future calls // will wait on the inputQueue. The semaphore is always released right before the Dispatch on the inputQueue. // This protects a new call racing with an existing operation that is just about to fully complete. public bool TryReceive(TimeSpan timeout, out RequestContext requestContext) { if (Interlocked.CompareExchange(ref this.pendingOperationSemaphore, 1, 0) == 0) { ActionItem.Schedule(tryReceive, this); } RequestContextWrapper wrapper; bool success = this.inputQueue.Dequeue(timeout, out wrapper); if (success && wrapper != null) { requestContext = wrapper.RequestContext; } else { requestContext = null; } return success; } public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state) { if (Interlocked.CompareExchange(ref this.pendingOperationSemaphore, 1, 0) == 0) { IAsyncResult result = this.channelBinder.BeginTryReceive(timeout, tryReceiveCallback, this); if (result.CompletedSynchronously) { HandleEndTryReceive(result); } } return this.inputQueue.BeginDequeue(timeout, callback, state); } public bool EndTryReceive(IAsyncResult result, out RequestContext requestContext) { RequestContextWrapper wrapper; bool success = this.inputQueue.EndDequeue(result, out wrapper); if (success && wrapper != null) { requestContext = wrapper.RequestContext; } else { requestContext = null; } return success; } public RequestContext CreateRequestContext(Message message) { return this.channelBinder.CreateRequestContext(message); } public void Send(Message message, TimeSpan timeout) { this.channelBinder.Send(message, timeout); } public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return this.channelBinder.BeginSend(message, timeout, callback, state); } public void EndSend(IAsyncResult result) { this.channelBinder.EndSend(result); } public Message Request(Message message, TimeSpan timeout) { return this.channelBinder.Request(message, timeout); } public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return this.channelBinder.BeginRequest(message, timeout, callback, state); } public Message EndRequest(IAsyncResult result) { return this.channelBinder.EndRequest(result); } public bool WaitForMessage(TimeSpan timeout) { return this.channelBinder.WaitForMessage(timeout); } public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state) { return this.channelBinder.BeginWaitForMessage(timeout, callback, state); } public bool EndWaitForMessage(IAsyncResult result) { return this.channelBinder.EndWaitForMessage(result); } internal void InjectRequest(RequestContext requestContext) { // Reuse the existing requestContext this.inputQueue.EnqueueAndDispatch(new RequestContextWrapper(requestContext)); } // // TryReceive threads // static void TryReceive(object state) { BufferedReceiveBinder binder = (BufferedReceiveBinder)state; RequestContext requestContext; bool requiresDispatch = false; try { if (binder.channelBinder.TryReceive(TimeSpan.MaxValue, out requestContext)) { requiresDispatch = binder.inputQueue.EnqueueWithoutDispatch(new RequestContextWrapper(requestContext), null); } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } requiresDispatch = binder.inputQueue.EnqueueWithoutDispatch(exception, null); } finally { Interlocked.Exchange(ref binder.pendingOperationSemaphore, 0); if (requiresDispatch) { binder.inputQueue.Dispatch(); } } } static void TryReceiveCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } HandleEndTryReceive(result); } static void HandleEndTryReceive(IAsyncResult result) { BufferedReceiveBinder binder = (BufferedReceiveBinder)result.AsyncState; RequestContext requestContext; bool requiresDispatch = false; try { if (binder.channelBinder.EndTryReceive(result, out requestContext)) { requiresDispatch = binder.inputQueue.EnqueueWithoutDispatch(new RequestContextWrapper(requestContext), null); } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } requiresDispatch = binder.inputQueue.EnqueueWithoutDispatch(exception, null); } finally { Interlocked.Exchange(ref binder.pendingOperationSemaphore, 0); if (requiresDispatch) { binder.inputQueue.Dispatch(); } } } // A RequestContext may be 'null' (some pieces of ChannelHandler depend on this) but the InputQueue // will not allow null items to be enqueued. Wrap the RequestContexts in another object to // facilitate this semantic class RequestContextWrapper { public RequestContextWrapper(RequestContext requestContext) { this.RequestContext = requestContext; } public RequestContext RequestContext { get; private set; } } } }
/* * Qa full api * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: all * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HostMe.Sdk.Model { /// <summary> /// LoyaltySettings /// </summary> [DataContract] public partial class LoyaltySettings : IEquatable<LoyaltySettings>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="LoyaltySettings" /> class. /// </summary> /// <param name="CheckinPoints">CheckinPoints.</param> /// <param name="IsEnabled">IsEnabled.</param> /// <param name="MembershipLevelRules">MembershipLevelRules.</param> /// <param name="PurchasePointsRules">PurchasePointsRules.</param> /// <param name="SignupPoints">SignupPoints.</param> /// <param name="WaitingPointsRules">WaitingPointsRules.</param> public LoyaltySettings(int? CheckinPoints = null, bool? IsEnabled = null, List<MembershipLevel> MembershipLevelRules = null, List<PurchaseToPoints> PurchasePointsRules = null, int? SignupPoints = null, List<MinutesToPoints> WaitingPointsRules = null) { this.CheckinPoints = CheckinPoints; this.IsEnabled = IsEnabled; this.MembershipLevelRules = MembershipLevelRules; this.PurchasePointsRules = PurchasePointsRules; this.SignupPoints = SignupPoints; this.WaitingPointsRules = WaitingPointsRules; } /// <summary> /// Gets or Sets CheckinPoints /// </summary> [DataMember(Name="checkinPoints", EmitDefaultValue=true)] public int? CheckinPoints { get; set; } /// <summary> /// Gets or Sets IsEnabled /// </summary> [DataMember(Name="isEnabled", EmitDefaultValue=true)] public bool? IsEnabled { get; set; } /// <summary> /// Gets or Sets MembershipLevelRules /// </summary> [DataMember(Name="membershipLevelRules", EmitDefaultValue=true)] public List<MembershipLevel> MembershipLevelRules { get; set; } /// <summary> /// Gets or Sets PurchasePointsRules /// </summary> [DataMember(Name="purchasePointsRules", EmitDefaultValue=true)] public List<PurchaseToPoints> PurchasePointsRules { get; set; } /// <summary> /// Gets or Sets SignupPoints /// </summary> [DataMember(Name="signupPoints", EmitDefaultValue=true)] public int? SignupPoints { get; set; } /// <summary> /// Gets or Sets WaitingPointsRules /// </summary> [DataMember(Name="waitingPointsRules", EmitDefaultValue=true)] public List<MinutesToPoints> WaitingPointsRules { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LoyaltySettings {\n"); sb.Append(" CheckinPoints: ").Append(CheckinPoints).Append("\n"); sb.Append(" IsEnabled: ").Append(IsEnabled).Append("\n"); sb.Append(" MembershipLevelRules: ").Append(MembershipLevelRules).Append("\n"); sb.Append(" PurchasePointsRules: ").Append(PurchasePointsRules).Append("\n"); sb.Append(" SignupPoints: ").Append(SignupPoints).Append("\n"); sb.Append(" WaitingPointsRules: ").Append(WaitingPointsRules).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LoyaltySettings); } /// <summary> /// Returns true if LoyaltySettings instances are equal /// </summary> /// <param name="other">Instance of LoyaltySettings to be compared</param> /// <returns>Boolean</returns> public bool Equals(LoyaltySettings other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.CheckinPoints == other.CheckinPoints || this.CheckinPoints != null && this.CheckinPoints.Equals(other.CheckinPoints) ) && ( this.IsEnabled == other.IsEnabled || this.IsEnabled != null && this.IsEnabled.Equals(other.IsEnabled) ) && ( this.MembershipLevelRules == other.MembershipLevelRules || this.MembershipLevelRules != null && this.MembershipLevelRules.SequenceEqual(other.MembershipLevelRules) ) && ( this.PurchasePointsRules == other.PurchasePointsRules || this.PurchasePointsRules != null && this.PurchasePointsRules.SequenceEqual(other.PurchasePointsRules) ) && ( this.SignupPoints == other.SignupPoints || this.SignupPoints != null && this.SignupPoints.Equals(other.SignupPoints) ) && ( this.WaitingPointsRules == other.WaitingPointsRules || this.WaitingPointsRules != null && this.WaitingPointsRules.SequenceEqual(other.WaitingPointsRules) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.CheckinPoints != null) hash = hash * 59 + this.CheckinPoints.GetHashCode(); if (this.IsEnabled != null) hash = hash * 59 + this.IsEnabled.GetHashCode(); if (this.MembershipLevelRules != null) hash = hash * 59 + this.MembershipLevelRules.GetHashCode(); if (this.PurchasePointsRules != null) hash = hash * 59 + this.PurchasePointsRules.GetHashCode(); if (this.SignupPoints != null) hash = hash * 59 + this.SignupPoints.GetHashCode(); if (this.WaitingPointsRules != null) hash = hash * 59 + this.WaitingPointsRules.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Diagnostics; using System.Collections.Generic; using Axiom.MathLib; using Axiom.Graphics; namespace Axiom.Core { /// <summary> /// A viewpoint from which the scene will be rendered. /// </summary> ///<remarks> /// The engine renders scenes from a camera viewpoint into a buffer of /// some sort, normally a window or a texture (a subclass of /// RenderTarget). the engine cameras support both perspective projection (the default, /// meaning objects get smaller the further away they are) and /// orthographic projection (blueprint-style, no decrease in size /// with distance). Each camera carries with it a style of rendering, /// e.g. full textured, flat shaded, wireframe), field of view, /// rendering distances etc, allowing you to use the engine to create /// complex multi-window views if required. In addition, more than /// one camera can point at a single render target if required, /// each rendering to a subset of the target, allowing split screen /// and picture-in-picture views. /// <p/> /// Cameras maintain their own aspect ratios, field of view, and frustrum, /// and project co-ordinates into a space measured from -1 to 1 in x and y, /// and 0 to 1 in z. At render time, the camera will be rendering to a /// Viewport which will translate these parametric co-ordinates into real screen /// co-ordinates. Obviously it is advisable that the viewport has the same /// aspect ratio as the camera to avoid distortion (unless you want it!). /// <p/> /// Note that a Camera can be attached to a SceneNode, using the method /// SceneNode.AttachObject. If this is done the Camera will combine it's own /// position/orientation settings with it's parent SceneNode. /// This is useful for implementing more complex Camera / object /// relationships i.e. having a camera attached to a world object. /// </remarks> public class Camera : Frustum { #region Fields /// <summary> /// Parent scene manager. /// </summary> protected SceneManager sceneManager; /// <summary> /// Camera orientation. /// </summary> protected Quaternion orientation; /// <summary> /// Camera position. /// </summary> protected Vector3 position; /// <summary> /// Orientation dervied from parent. /// </summary> protected Quaternion derivedOrientation; /// <summary> /// Position dervied from parent. /// </summary> protected Vector3 derivedPosition; /// <summary> /// Real world orientation of the camera /// </summary> protected Quaternion realOrientation; /// <summary> /// Real world position of the camera /// </summary> protected Vector3 realPosition; /// <summary> /// Whether to yaw around a fixed axis. /// </summary> protected bool isYawFixed; /// <summary> /// Fixed axis to yaw around. /// </summary> protected Vector3 yawFixedAxis; /// <summary> /// Rendering type (wireframe, solid, point). /// </summary> protected SceneDetailLevel sceneDetail; /// <summary> /// Stored number of visible faces in the last render. /// </summary> protected int numFacesRenderedLastFrame; /// <summary> /// SceneNode which this Camera will automatically track. /// </summary> protected SceneNode autoTrackTarget; /// <summary> /// Tracking offset for fine tuning. /// </summary> protected Vector3 autoTrackOffset; /// <summary> /// Scene LOD factor used to adjust overall LOD. /// </summary> protected float sceneLodFactor; /// <summary> /// Inverted scene LOD factor, can be used by Renderables to adjust their LOD. /// </summary> protected float invSceneLodFactor; /// <summary> /// Left window edge (window clip planes). /// </summary> protected float windowLeft; /// <summary> /// Right window edge (window clip planes). /// </summary> protected float windowRight; /// <summary> /// Top window edge (window clip planes). /// </summary> protected float windowTop; /// <summary> /// Bottom window edge (window clip planes). /// </summary> protected float windowBottom; /// <summary> /// Is viewing window used. /// </summary> protected bool isWindowSet; /// <summary> /// Windowed viewport clip planes. /// </summary> protected List<Plane> windowClipPlanes = new List<Plane>(); /// <summary> /// Was viewing window changed? /// </summary> protected bool recalculateWindow; /// <summary> /// The last viewport to be added using this camera. /// </summary> protected Viewport lastViewport; /// <summary> /// Whether aspect ratio will automaticaally be recalculated when a vieport changes its size. /// </summary> protected bool autoAspectRatio; /// <summary> /// Custom culling frustum /// </summary> Frustum cullingFrustum; /// <summary> /// Whether or not the rendering distance of objects should take effect for this camera /// </summary> bool useRenderingDistance; #endregion Fields #region Constructors public Camera(string name, SceneManager sceneManager) { // Record name & SceneManager this.name = name; this.sceneManager = sceneManager; // Init camera location & direction // Locate at (0,0,0) orientation = Quaternion.Identity; position = Vector3.Zero; derivedOrientation = Quaternion.Identity; derivedPosition = Vector3.Zero; // Reasonable defaults to camera params sceneDetail = SceneDetailLevel.Solid; // Init no tracking autoTrackTarget = null; autoTrackOffset = Vector3.Zero; // default these to 1 so Lod default to normal sceneLodFactor = this.invSceneLodFactor = 1.0f; lastViewport = null; autoAspectRatio = false; cullingFrustum = null; // default to using the rendering distance useRenderingDistance = true; fieldOfView = MathUtil.RadiansToDegrees(MathUtil.PI / 4.0f); nearDistance = 100.0f; farDistance = 100000.0f; aspectRatio = 1.33333333333333f; projectionType = Projection.Perspective; // Default to fixed yaw (freelook) this.FixedYawAxis = Vector3.UnitY; InvalidateFrustum(); InvalidateView(); viewMatrix = Matrix4.Zero; projectionMatrix = Matrix4.Zero; parentNode = null; // no reflection isReflected = false; isVisible = false; } #endregion #region Frustum Members /// <summary> /// Get the derived orientation of this frustum. /// </summary> /// <returns></returns> protected override Quaternion GetOrientationForViewUpdate() { return realOrientation; } /// <summary> /// Get the derived position of this frustum. /// </summary> /// <returns></returns> protected override Vector3 GetPositionForViewUpdate() { return realPosition; } /// <summary> /// Signal to update view information. /// </summary> protected override void InvalidateView() { recalculateWindow = true; base.InvalidateView(); } /// <summary> /// Signal to update frustum information. /// </summary> protected override void InvalidateFrustum() { recalculateWindow = true; base.InvalidateFrustum(); } /// <summary> /// Evaluates whether or not the view matrix is out of date. /// </summary> /// <returns></returns> protected override bool IsViewOutOfDate { get { // Overridden from Frustum to use local orientation / position offsets // are we attached to another node? if(parentNode != null) { if(recalculateView || parentNode.DerivedOrientation != lastParentOrientation || parentNode.DerivedPosition != lastParentPosition) { // we are out of date with the parent scene node lastParentOrientation = parentNode.DerivedOrientation; lastParentPosition = parentNode.DerivedPosition; realOrientation = lastParentOrientation * orientation; realPosition = (lastParentOrientation * position) + lastParentPosition; recalculateView = true; recalculateWindow = true; } } else { // rely on own updates realOrientation = orientation; realPosition = position; } if(isReflected && linkedReflectionPlane != null && !(lastLinkedReflectionPlane == linkedReflectionPlane.DerivedPlane)) { reflectionPlane = linkedReflectionPlane.DerivedPlane; reflectionMatrix = MathUtil.BuildReflectionMatrix(reflectionPlane); lastLinkedReflectionPlane = linkedReflectionPlane.DerivedPlane; recalculateView = true; recalculateWindow = true; } // Deriving reflected orientation / position if (recalculateView) { if (isReflected) { // Calculate reflected orientation, use up-vector as fallback axis. Vector3 dir = realOrientation * Vector3.NegativeUnitZ; Vector3 rdir = dir.Reflect(reflectionPlane.Normal); Vector3 up = realOrientation * Vector3.UnitY; derivedOrientation = dir.GetRotationTo(rdir, up) * realOrientation; // Calculate reflected position. derivedPosition = reflectionMatrix.TransformAffine(realPosition); } else { derivedOrientation = realOrientation; derivedPosition = realPosition; } } return recalculateView; } } #endregion Frustum Members #region SceneObject Implementation public override void UpdateRenderQueue(RenderQueue queue) { // Do nothing } public override AxisAlignedBox BoundingBox { get { // a camera is not visible in the scene return AxisAlignedBox.Null; } } /// <summary> /// Overridden to return a proper bounding radius for the camera. /// </summary> public override float BoundingRadius { get { // return a little bigger than the near distance // just to keep things just outside return nearDistance * 1.5f; } } public override void NotifyCurrentCamera(Axiom.Core.Camera camera) { // Do nothing } /// <summary> /// Called by the scene manager to let this camera know how many faces were renderer within /// view of this camera every frame. /// </summary> /// <param name="renderedFaceCount"></param> internal void NotifyRenderedFaces(int renderedFaceCount) { numFacesRenderedLastFrame = renderedFaceCount; } #endregion #region Public Properties public override string Name { get { return name; } } public SceneNode AutoTrackingTarget { get { return autoTrackTarget; } set { autoTrackTarget = value; } } public Vector3 AutoTrackingOffset { get { return autoTrackOffset; } set { autoTrackOffset = value; } } /// <summary> /// If set to true a viewport that owns this frustum will be able to /// recalculate the aspect ratio whenever the frustum is resized. /// </summary> /// <remarks> /// You should set this to true only if the frustum / camera is used by /// one viewport at the same time. Otherwise the aspect ratio for other /// viewports may be wrong. /// </remarks> public bool AutoAspectRatio { get { return autoAspectRatio; } set { autoAspectRatio = value; //FIXED: From true to value } } /// <summary> /// Whether or not the rendering distance of objects should take effect for this camera /// </summary> public bool UseRenderingDistance { get { return useRenderingDistance; } set { useRenderingDistance = value; } } /// <summary> /// Returns the current SceneManager that this camera is using. /// </summary> public SceneManager SceneManager { get { return sceneManager; } } /// <summary> /// Sets the level of rendering detail required from this camera. /// </summary> /// <remarks> /// Each camera is set to render at full detail by default, that is /// with full texturing, lighting etc. This method lets you change /// that behavior, allowing you to make the camera just render a /// wireframe view, for example. /// </remarks> public SceneDetailLevel SceneDetail { get { return sceneDetail; } set { sceneDetail = value; } } /// <summary> /// Gets/Sets the camera's orientation. /// </summary> public Quaternion Orientation { get { return orientation; } set { orientation = value; InvalidateView(); } } /// <summary> /// Gets/Sets the camera's position. /// </summary> public Vector3 Position { get { return position; } set { position = value; InvalidateView(); } } /// <summary> /// Gets/Sets the camera's direction vector. /// </summary> public Vector3 Direction { // Direction points down the negatize Z axis by default. get { return orientation * Vector3.NegativeUnitZ; } set { Vector3 direction = value; // Do nothing if given a zero vector // (Replaced assert since this could happen with auto tracking camera and // camera passes through the lookAt point) if (direction == Vector3.Zero) return; // Remember, camera points down -Z of local axes! // Therefore reverse direction of direction vector before determining local Z Vector3 zAdjustVector = -direction; zAdjustVector.Normalize(); if( isYawFixed ) { Vector3 xVector = yawFixedAxis.Cross( zAdjustVector ); xVector.Normalize(); Vector3 yVector = zAdjustVector.Cross( xVector ); yVector.Normalize(); orientation.FromAxes( xVector, yVector, zAdjustVector ); } else { // update the view of the camera UpdateView(); // Get axes from current quaternion Vector3 xAxis, yAxis, zAxis; // get the vector components of the derived orientation vector realOrientation.ToAxes(out xAxis, out yAxis, out zAxis); Quaternion rotationQuat; if ((zAdjustVector + zAxis).LengthSquared < 0.00005f) { // Oops, a 180 degree turn (infinite possible rotation axes) // Default to yaw i.e. use current UP rotationQuat = Quaternion.FromAngleAxis(MathUtil.PI, yAxis); } else // Derive shortest arc to new direction rotationQuat = zAxis.GetRotationTo(zAdjustVector); orientation = rotationQuat * orientation; } // transform to parent space if (parentNode != null) orientation = parentNode.DerivedOrientation.Inverse() * orientation; // TODO: If we have a fixed yaw axis, we musn't break it by using the // shortest arc because this will sometimes cause a relative yaw // which will tip the camera InvalidateView(); } } /// <summary> /// Gets camera's 'right' vector. /// </summary> public Vector3 Right { get { return Orientation * Vector3.UnitX; } } public Vector3 DerivedRight { get { UpdateView(); return DerivedOrientation * Vector3.UnitX; } } /// <summary> /// Gets camera's 'up' vector. /// </summary> public Vector3 Up { get { return Orientation * Vector3.UnitY; } } public Vector3 DerivedUp { get { UpdateView(); return DerivedOrientation * Vector3.UnitY; } } /// <summary> /// Gets the real world orientation of the camera, including any /// rotation inherited from a node attachment */ /// </summary> public Quaternion RealOrientation { get { UpdateView(); return realOrientation; } } /// <summary> /// Gets the real world position of the camera, including any /// rotation inherited from a node attachment /// </summary> public Vector3 RealPosition { get { UpdateView(); return realPosition; } } /// <summary> /// Gets the real world direction vector of the camera, including any /// rotation inherited from a node attachment. /// </summary> public Vector3 RealDirection { get { UpdateView(); return realOrientation * Vector3.NegativeUnitZ; } } /// <summary> /// Gets the real world up vector of the camera, including any /// rotation inherited from a node attachment. /// </summary> public Vector3 RealUp { get { UpdateView(); return realOrientation * Vector3.UnitY; } } /// <summary> /// Gets the real world right vector of the camera, including any /// rotation inherited from a node attachment. /// </summary> public Vector3 RealRight { get { UpdateView(); return realOrientation * Vector3.UnitX; } } /// <summary> /// Get the last viewport which was attached to this camera. /// </summary> /// <remarks> /// This is not guaranteed to be the only viewport which is /// using this camera, just the last once which was created referring /// to it. /// </remarks> public Viewport Viewport { get { return lastViewport; } } /// <summary> /// Tells the camera whether to yaw around it's own local Y axis or a /// fixed axis of choice. /// </summary> /// <remarks> /// This method allows you to change the yaw behaviour of the camera /// - by default, the camera yaws around a fixed Y axis. This is /// often what you want - for example if you're making a first-person /// shooter, you really don't want the yaw axis to reflect the local /// camera Y, because this would mean a different yaw axis if the /// player is looking upwards rather than when they are looking /// straight ahead. You can change this behaviour by calling this /// method, which you will want to do if you are making a completely /// free camera like the kind used in a flight simulator. /// </remarks> /// <param name="useFixed" /// If true, the axis passed in the second parameter will /// always be the yaw axis no matter what the camera /// orientation. /// If false, the camera yaws around the local Y. /// </param> /// <param name="fixedAxis" /// The axis to use if the first parameter is true. /// </param> public void SetFixedYawAxis(bool useFixed, Vector3 fixedAxis) { isYawFixed = useFixed; yawFixedAxis = fixedAxis; } /// <summary> /// /// </summary> public Vector3 FixedYawAxis { get { return yawFixedAxis; } set { yawFixedAxis = value; if(yawFixedAxis != Vector3.Zero) { isYawFixed = true; } else { isYawFixed = false; } } } /// <summary> /// Sets the level-of-detail factor for this Camera. /// </summary> /// <remarks> /// This method can be used to influence the overall level of detail of the scenes /// rendered using this camera. Various elements of the scene have level-of-detail /// reductions to improve rendering speed at distance; this method allows you /// to hint to those elements that you would like to adjust the level of detail that /// they would normally use (up or down). /// <p/> /// The most common use for this method is to reduce the overall level of detail used /// for a secondary camera used for sub viewports like rear-view mirrors etc. /// Note that scene elements are at liberty to ignore this setting if they choose, /// this is merely a hint. /// <p/> /// Higher values increase the detail, so 2.0 doubles the normal detail and 0.5 halves it. /// </remarks> public float LodBias { get { return sceneLodFactor; } set { Debug.Assert(value > 0.0f, "Lod bias must be greater than 0"); sceneLodFactor = value; invSceneLodFactor = 1.0f / sceneLodFactor; } } /// <summary> /// Used for internal Lod calculations. /// </summary> public float InverseLodBias { get { return invSceneLodFactor; } } /// <summary> /// Gets the last count of triangles visible in the view of this camera. /// </summary> public int RenderedFaceCount { get { return numFacesRenderedLastFrame; } } /// <summary> /// Gets the derived orientation of the camera. /// </summary> public Quaternion DerivedOrientation { get { UpdateView(); return derivedOrientation; } } /// <summary> /// Gets the derived position of the camera. /// </summary> public Vector3 DerivedPosition { get { UpdateView(); return derivedPosition; } } /// <summary> /// Gets the derived direction of the camera. /// </summary> public Vector3 DerivedDirection { get { UpdateView(); // RH coords, direction points down -Z by default return derivedOrientation * Vector3.NegativeUnitZ; } } /// <summary> /// Gets the flag specifying if a viewport window is being used. /// </summary> public virtual bool IsWindowSet { get { return isWindowSet; } } /// <summary> /// Gets the number of window clip planes for this camera. /// </summary> /// <remarks>Only applicable if IsWindowSet == true. /// </remarks> public int WindowPlaneCount { get { return windowClipPlanes.Count; } } public override Matrix4 ViewMatrix { get { if (cullingFrustum != null) return cullingFrustum.ViewMatrix; else return base.ViewMatrix; } } public override Vector3[] WorldSpaceCorners { get { if (cullingFrustum != null) return cullingFrustum.WorldSpaceCorners; else return base.WorldSpaceCorners; } } public override float Near { get { if (cullingFrustum != null) return cullingFrustum.Near; else return base.Near; } set // overriding because iron python fails to find the base implementation automatically { base.Near = value; } } public override float Far { get { if (cullingFrustum != null) return cullingFrustum.Far; else return base.Far; } set // overriding because iron python fails to find the base implementation automatically { base.Far = value; } } #endregion #region Public methods public override bool IsObjectVisible(AxisAlignedBox bound, out FrustumPlane culledBy) { if (cullingFrustum != null) return cullingFrustum.IsObjectVisible(bound, out culledBy); else return base.IsObjectVisible(bound, out culledBy); } public override bool IsObjectVisible(Sphere bound, out FrustumPlane culledBy) { if (cullingFrustum != null) return cullingFrustum.IsObjectVisible(bound, out culledBy); else return base.IsObjectVisible(bound, out culledBy); } public override bool IsObjectVisible(Vector3 vert, out FrustumPlane culledBy) { if (cullingFrustum != null) return cullingFrustum.IsObjectVisible(vert, out culledBy); else return base.IsObjectVisible(vert, out culledBy); } public override Plane GetFrustumPlane(FrustumPlane plane) { if (cullingFrustum != null) return cullingFrustum.GetFrustumPlane(plane); else return base.GetFrustumPlane(plane); } public override bool ProjectSphere(Sphere sphere, out float left, out float top, out float right, out float bottom) { if (cullingFrustum != null) return cullingFrustum.ProjectSphere(sphere, out left, out top, out right, out bottom); else return base.ProjectSphere(sphere, out left, out top, out right, out bottom); } /// <summary> /// Moves the camera's position by the vector offset provided along world axes. /// </summary> /// <param name="offset"></param> public void Move(Vector3 offset) { position = position + offset; InvalidateView(); } /// <summary> /// Moves the camera's position by the vector offset provided along it's own axes (relative to orientation). /// </summary> /// <param name="offset"></param> public void MoveRelative(Vector3 offset) { // Transform the axes of the relative vector by camera's local axes Vector3 transform = orientation * offset; position = position + transform; InvalidateView(); } /// <summary> /// Specifies a target that the camera should look at. /// </summary> /// <param name="target"></param> public void LookAt(Vector3 target) { UpdateView(); this.Direction = (target - realPosition); } /// <summary> /// Pitches the camera up/down counter-clockwise around it's local x axis. /// </summary> /// <param name="degrees"></param> public void Pitch(float degrees) { Vector3 xAxis = orientation * Vector3.UnitX; Rotate(xAxis, degrees); InvalidateView(); } /// <summary> /// Rolls the camera counter-clockwise, in degrees, around its local y axis. /// </summary> /// <param name="degrees"></param> public void Yaw(float degrees) { Vector3 yAxis; if(isYawFixed) { // Rotate around fixed yaw axis yAxis = yawFixedAxis; } else { // Rotate around local Y axis yAxis = orientation * Vector3.UnitY; } Rotate(yAxis, degrees); InvalidateView(); } /// <summary> /// Rolls the camera counter-clockwise, in degrees, around its local z axis. /// </summary> /// <param name="degrees"></param> public void Roll(float degrees) { // Rotate around local Z axis Vector3 zAxis = orientation * Vector3.UnitZ; Rotate(zAxis, degrees); InvalidateView(); } /// <summary> /// Rotates the camera about an arbitrary axis. /// </summary> /// <param name="quat"></param> public void Rotate(Quaternion quat) { // Note the order of the multiplication orientation = quat * orientation; orientation.Normalize(); InvalidateView(); } /// <summary> /// Rotates the camera about an arbitrary axis. /// </summary> /// <param name="axis"></param> /// <param name="degrees"></param> public void Rotate(Vector3 axis, float degrees) { Quaternion q = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(degrees), axis); Rotate(q); } /// <summary> /// Enables / disables automatic tracking of a SceneObject. /// </summary> /// <remarks> /// If you enable auto-tracking, this Camera will automatically rotate to /// look at the target SceneNode every frame, no matter how /// it or SceneNode move. This is handy if you want a Camera to be focused on a /// single object or group of objects. Note that by default the Camera looks at the /// origin of the SceneNode, if you want to tweak this, e.g. if the object which is /// attached to this target node is quite big and you want to point the camera at /// a specific point on it, provide a vector in the 'offset' parameter and the /// camera's target point will be adjusted. /// </remarks> /// <param name="enabled">If true, the Camera will track the SceneNode supplied as the next /// parameter (cannot be null). If false the camera will cease tracking and will /// remain in it's current orientation. /// </param> /// <param name="target">The SceneObject which this Camera will track.</param> public void SetAutoTracking(bool enabled, MovableObject target) { SetAutoTracking(enabled, (SceneNode)target.ParentNode, Vector3.Zero); } /// <summary> /// Enables / disables automatic tracking of a SceneNode. /// </summary> /// <remarks> /// If you enable auto-tracking, this Camera will automatically rotate to /// look at the target SceneNode every frame, no matter how /// it or SceneNode move. This is handy if you want a Camera to be focused on a /// single object or group of objects. Note that by default the Camera looks at the /// origin of the SceneNode, if you want to tweak this, e.g. if the object which is /// attached to this target node is quite big and you want to point the camera at /// a specific point on it, provide a vector in the 'offset' parameter and the /// camera's target point will be adjusted. /// </remarks> /// <param name="enabled">If true, the Camera will track the SceneNode supplied as the next /// parameter (cannot be null). If false the camera will cease tracking and will /// remain in it's current orientation. /// </param> /// <param name="target">The SceneNode which this Camera will track. Make sure you don't /// delete this SceneNode before turning off tracking (e.g. SceneManager.ClearScene will /// delete it so be careful of this). Can be null if and only if the enabled param is false. /// </param> public void SetAutoTracking(bool enabled, SceneNode target) { SetAutoTracking(enabled, target, Vector3.Zero); } /// <summary> /// Enables / disables automatic tracking of a SceneNode. /// </summary> /// <remarks> /// If you enable auto-tracking, this Camera will automatically rotate to /// look at the target SceneNode every frame, no matter how /// it or SceneNode move. This is handy if you want a Camera to be focused on a /// single object or group of objects. Note that by default the Camera looks at the /// origin of the SceneNode, if you want to tweak this, e.g. if the object which is /// attached to this target node is quite big and you want to point the camera at /// a specific point on it, provide a vector in the 'offset' parameter and the /// camera's target point will be adjusted. /// </remarks> /// <param name="enabled">If true, the Camera will track the SceneNode supplied as the next /// parameter (cannot be null). If false the camera will cease tracking and will /// remain in it's current orientation. /// </param> /// <param name="target">The SceneNode which this Camera will track. Make sure you don't /// delete this SceneNode before turning off tracking (e.g. SceneManager.ClearScene will /// delete it so be careful of this). Can be null if and only if the enabled param is false. /// </param> /// <param name="offset">If supplied, the camera targets this point in local space of the target node /// instead of the origin of the target node. Good for fine tuning the look at point. /// </param> public void SetAutoTracking(bool enabled, SceneNode target, Vector3 offset) { if(enabled) { Debug.Assert(target != null, "A camera's auto track target cannot be null."); autoTrackTarget = target; autoTrackOffset = offset; } else { autoTrackTarget = null; } } /// <summary> /// Sets the viewing window inside of viewport. /// </summary> /// <remarks> /// This method can be used to set a subset of the viewport as the rendering target. /// </remarks> /// <param name="left">Relative to Viewport - 0 corresponds to left edge, 1 - to right edge (default - 0).</param> /// <param name="top">Relative to Viewport - 0 corresponds to top edge, 1 - to bottom edge (default - 0).</param> /// <param name="right">Relative to Viewport - 0 corresponds to left edge, 1 - to right edge (default - 1).</param> /// <param name="bottom">Relative to Viewport - 0 corresponds to top edge, 1 - to bottom edge (default - 1).</param> public virtual void SetWindow(float left, float top, float right, float bottom) { windowLeft = left; windowTop = top; windowRight = right; windowBottom = bottom; isWindowSet = true; recalculateWindow = true; InvalidateView(); } /// <summary> /// Do actual window setting, using parameters set in <see cref="SetWindow"/> call. /// </summary> /// <remarks>The method is called after projection matrix each change.</remarks> protected void SetWindowImpl() { if(!isWindowSet || !recalculateWindow) { return; } float thetaY = MathUtil.DegreesToRadians(fieldOfView * 0.5f); float tanThetaY = MathUtil.Tan(thetaY); float tanThetaX = tanThetaY * aspectRatio; float vpTop = tanThetaY * nearDistance; float vpLeft = -tanThetaX * nearDistance; float vpWidth = -2 * vpLeft; float vpHeight = -2 * vpTop; float wvpLeft = vpLeft + windowLeft * vpWidth; float wvpRight = vpLeft + windowRight * vpWidth; float wvpTop = vpTop - windowTop * vpHeight; float wvpBottom = vpTop - windowBottom * vpHeight; Vector3 vpUpLeft = new Vector3(wvpLeft, wvpTop, -nearDistance); Vector3 vpUpRight = new Vector3(wvpRight, wvpTop, -nearDistance); Vector3 vpBottomLeft = new Vector3(wvpLeft, wvpBottom, -nearDistance); Vector3 vpBottomRight = new Vector3(wvpRight, wvpBottom, -nearDistance); Matrix4 inv = viewMatrix.Inverse(); Vector3 vwUpLeft = inv * vpUpLeft; Vector3 vwUpRight = inv * vpUpRight; Vector3 vwBottomLeft = inv * vpBottomLeft; Vector3 vwBottomRight = inv * vpBottomRight; Vector3 pos = Position; windowClipPlanes.Clear(); windowClipPlanes.Add(new Plane(pos, vwBottomLeft, vwUpLeft)); windowClipPlanes.Add(new Plane(pos, vwUpLeft, vwUpRight)); windowClipPlanes.Add(new Plane(pos, vwUpRight, vwBottomRight)); windowClipPlanes.Add(new Plane(pos, vwBottomRight, vwBottomLeft)); recalculateWindow = false; } /// <summary> /// Cancel view window. /// </summary> public virtual void ResetWindow() { isWindowSet = false; } /// <summary> /// Gets the window plane at the specified index. /// </summary> /// <param name="index">Index of the plane to get.</param> /// <returns>The window plane at the specified index.</returns> public Plane GetWindowPlane(int index) { Debug.Assert(index < windowClipPlanes.Count, "Window clip plane index out of bounds."); // ensure the window is recalced SetWindowImpl(); return (Plane)windowClipPlanes[index]; } /// <summary> /// Gets a world space ray as cast from the camera through a viewport position. /// </summary> /// <param name="screenX"> /// The x position at which the ray should intersect the viewport, /// in normalised screen coordinates [0,1]. /// </param> /// <param name="screenY"> /// The y position at which the ray should intersect the viewport, /// in normalised screen coordinates [0,1]. /// </param> /// <returns></returns> public Ray GetCameraToViewportRay(float screenX, float screenY) { float centeredScreenX = (screenX - 0.5f); float centeredScreenY = (0.5f - screenY); float normalizedSlope = MathUtil.Tan(MathUtil.DegreesToRadians(fieldOfView * 0.5f)); float viewportYToWorldY = normalizedSlope * nearDistance * 2; float viewportXToWorldX = viewportYToWorldY * aspectRatio; Vector3 rayDirection = new Vector3( centeredScreenX * viewportXToWorldX, centeredScreenY * viewportYToWorldY, -nearDistance); rayDirection = this.DerivedOrientation * rayDirection; rayDirection.Normalize(); return new Ray(this.DerivedPosition, rayDirection); } public Matrix4 GetViewMatrix(bool ownFrustumOnly) { if (ownFrustumOnly) return base.ViewMatrix; else return ViewMatrix; } /// <summary> /// Notifies this camera that a viewport is using it. /// </summary> /// <param name="viewport">Viewport that is using this camera.</param> public void NotifyViewport(Viewport viewport) { lastViewport = viewport; } #endregion #region Internal engine methods /// <summary> /// Called to ask a camera to render the scene into the given viewport. /// </summary> /// <param name="viewport"></param> /// <param name="showOverlays"></param> internal void RenderScene(Viewport viewport, bool showOverlays) { sceneManager.RenderScene(this, viewport, showOverlays); } /// <summary> /// Updates an auto-tracking camera. /// </summary> internal void AutoTrack() { // assumes all scene nodes have been updated if(autoTrackTarget != null) { LookAt(autoTrackTarget.DerivedPosition + autoTrackOffset); } } #endregion } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Perception\AISense_Blueprint.h:18 namespace UnrealEngine { [ManageType("ManageAISense_Blueprint")] public partial class ManageAISense_Blueprint : UAISense_Blueprint, IManageWrapper { public ManageAISense_Blueprint(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_CleanseInvalidSources(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Blueprint_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods public override void CleanseInvalidSources() => E__Supper__UAISense_Blueprint_CleanseInvalidSources(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__UAISense_Blueprint_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__UAISense_Blueprint_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__UAISense_Blueprint_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__UAISense_Blueprint_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__UAISense_Blueprint_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__UAISense_Blueprint_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__UAISense_Blueprint_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UAISense_Blueprint_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UAISense_Blueprint_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__UAISense_Blueprint_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UAISense_Blueprint_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UAISense_Blueprint_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__UAISense_Blueprint_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UAISense_Blueprint_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__UAISense_Blueprint_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageAISense_Blueprint self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageAISense_Blueprint(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageAISense_Blueprint>(PtrDesc); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace ParquetSharp.Schema { using System; using System.Text; using ParquetSharp.External; /** * Parses a schema from a textual format similar to that described in the Dremel paper. * * @author Julien Le Dem */ public static class MessageTypeParser { private static readonly Log LOG = Log.getLog(typeof(MessageTypeParser)); private class Tokenizer { private StringTokenizer st; private int line = 0; private StringBuilder currentLine = new StringBuilder(); public Tokenizer(string schemaString, string @string) { st = new StringTokenizer(schemaString, " ,;{}()\n\t=", true); } public string nextToken() { while (st.hasMoreTokens()) { string t = st.nextToken(); if (t.Equals("\n")) { ++line; currentLine.Clear(); } else { currentLine.Append(t); } if (!isWhitespace(t)) { return t; } } throw new ArgumentException("unexpected end of schema"); } private bool isWhitespace(string t) { return t.Equals(" ") || t.Equals("\t") || t.Equals("\n"); } public string getLocationString() { return "line " + line + ": " + currentLine.ToString(); } } /** * * @param input the text representation of the schema to parse * @return the corresponding object representation */ public static MessageType parseMessageType(string input) { return parse(input); } private static MessageType parse(string schemaString) { Tokenizer st = new Tokenizer(schemaString, " ;{}()\n\t"); Types.MessageTypeBuilder builder = Types.buildMessage(); string t = st.nextToken(); check(t, "message", "start with 'message'", st); string name = st.nextToken(); addGroupTypeFields(st.nextToken(), st, builder); return builder.named(name); } private static void addGroupTypeFields<T>(string t, Tokenizer st, Types.GroupBuilder<T> builder) { check(t, "{", "start of message", st); while (!(t = st.nextToken()).Equals("}")) { addType(t, st, builder); } } private static void addType<T>(string t, Tokenizer st, Types.GroupBuilder<T> builder) { Type.Repetition repetition = asRepetition(t, st); // Read type. string type = st.nextToken(); if (string.Equals(type, "group", StringComparison.OrdinalIgnoreCase)) { addGroupType(t, st, repetition, builder); } else { addPrimitiveType(t, st, asPrimitive(type, st), repetition, builder); } } private static void addGroupType<T>(string t, Tokenizer st, Type.Repetition r, Types.GroupBuilder<T> builder) { Types.GroupBuilder<Types.GroupBuilder<T>> childBuilder = builder.group(r); string name = st.nextToken(); // Read annotation, if any. t = st.nextToken(); OriginalType? originalType = null; if (string.Equals(t, "(", StringComparison.OrdinalIgnoreCase)) { originalType = (OriginalType)Enum.Parse(typeof(OriginalType), st.nextToken(), true); childBuilder.@as(originalType.Value); check(st.nextToken(), ")", "original type ended by )", st); t = st.nextToken(); } if (t.Equals("=")) { childBuilder.id(int.Parse(st.nextToken())); t = st.nextToken(); } try { addGroupTypeFields(t, st, childBuilder); } catch (ArgumentException e) { throw new ArgumentException("problem reading type: type = group, name = " + name + ", original type = " + originalType, e); } childBuilder.named(name); } private static void addPrimitiveType<T>( string t, Tokenizer st, PrimitiveType.PrimitiveTypeName type, Type.Repetition r, Types.GroupBuilder<T> builder) { Types.PrimitiveBuilder<Types.GroupBuilder<T>> childBuilder = builder.primitive(type, r); if (type == PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY) { t = st.nextToken(); // Read type length if the type is fixed_len_byte_array. if (!string.Equals(t, "(", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("expecting (length) for field of type fixed_len_byte_array"); } childBuilder.length(int.Parse(st.nextToken())); check(st.nextToken(), ")", "type length ended by )", st); } string name = st.nextToken(); // Read annotation, if any. t = st.nextToken(); OriginalType? originalType = null; if (string.Equals(t, "(", StringComparison.OrdinalIgnoreCase)) { originalType = (OriginalType)Enum.Parse(typeof(OriginalType), st.nextToken(), true); childBuilder.@as(originalType.Value); if (OriginalType.DECIMAL == originalType) { t = st.nextToken(); // parse precision and scale if (string.Equals(t, "(", StringComparison.OrdinalIgnoreCase)) { childBuilder.precision(int.Parse(st.nextToken())); t = st.nextToken(); if (string.Equals(t, ",", StringComparison.OrdinalIgnoreCase)) { childBuilder.scale(int.Parse(st.nextToken())); t = st.nextToken(); } check(t, ")", "decimal type ended by )", st); t = st.nextToken(); } } else { t = st.nextToken(); } check(t, ")", "original type ended by )", st); t = st.nextToken(); } if (t.Equals("=")) { childBuilder.id(int.Parse(st.nextToken())); t = st.nextToken(); } check(t, ";", "field ended by ';'", st); try { childBuilder.named(name); } catch (ArgumentException e) { throw new ArgumentException("problem reading type: type = " + type + ", name = " + name + ", original type = " + originalType, e); } } private static PrimitiveType.PrimitiveTypeName asPrimitive(string t, Tokenizer st) { try { return PrimitiveType.PrimitiveTypeName.valueOf(t.ToUpperInvariant()); } catch (ArgumentException e) { throw new ArgumentException("expected one of " + Arrays.toString(PrimitiveType.PrimitiveTypeName.values()) + " got " + t + " at " + st.getLocationString(), e); } } private static Type.Repetition asRepetition(string t, Tokenizer st) { try { return (Type.Repetition)Enum.Parse(typeof(Type.Repetition), t, true); } catch (ArgumentException e) { throw new ArgumentException("expected one of " + Arrays.toString((Type.Repetition[])Enum.GetValues(typeof(Type.Repetition))) + " got " + t + " at " + st.getLocationString(), e); } } private static void check(string t, string expected, string message, Tokenizer tokenizer) { if (!string.Equals(t, expected, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(message + ": expected '" + expected + "' but got '" + t + "' at " + tokenizer.getLocationString()); } } } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace pb.locationIntelligence.Model { /// <summary> /// Poi /// </summary> [DataContract] public partial class Poi : IEquatable<Poi> { /// <summary> /// Initializes a new instance of the <see cref="Poi" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="Name">Name.</param> /// <param name="BrandName">BrandName.</param> /// <param name="TradeName">TradeName.</param> /// <param name="FranchiseName">FranchiseName.</param> /// <param name="Open24Hours">Open24Hours.</param> /// <param name="ContactDetails">ContactDetails.</param> /// <param name="PoiClassification">PoiClassification.</param> /// <param name="EmployeeCount">EmployeeCount.</param> /// <param name="OrganizationStatusCode">OrganizationStatusCode.</param> /// <param name="OrganizationStatusCodeDescription">OrganizationStatusCodeDescription.</param> /// <param name="ParentBusiness">ParentBusiness.</param> /// <param name="TickerSymbol">TickerSymbol.</param> /// <param name="ExchangeName">ExchangeName.</param> public Poi(string Id = null, string Name = null, string BrandName = null, string TradeName = null, string FranchiseName = null, string Open24Hours = null, ContactDetails ContactDetails = null, PoiClassification PoiClassification = null, EmployeeCount EmployeeCount = null, string OrganizationStatusCode = null, string OrganizationStatusCodeDescription = null, ParentBusiness ParentBusiness = null, string TickerSymbol = null, string ExchangeName = null) { this.Id = Id; this.Name = Name; this.BrandName = BrandName; this.TradeName = TradeName; this.FranchiseName = FranchiseName; this.Open24Hours = Open24Hours; this.ContactDetails = ContactDetails; this.PoiClassification = PoiClassification; this.EmployeeCount = EmployeeCount; this.OrganizationStatusCode = OrganizationStatusCode; this.OrganizationStatusCodeDescription = OrganizationStatusCodeDescription; this.ParentBusiness = ParentBusiness; this.TickerSymbol = TickerSymbol; this.ExchangeName = ExchangeName; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets BrandName /// </summary> [DataMember(Name="brandName", EmitDefaultValue=false)] public string BrandName { get; set; } /// <summary> /// Gets or Sets TradeName /// </summary> [DataMember(Name="tradeName", EmitDefaultValue=false)] public string TradeName { get; set; } /// <summary> /// Gets or Sets FranchiseName /// </summary> [DataMember(Name="franchiseName", EmitDefaultValue=false)] public string FranchiseName { get; set; } /// <summary> /// Gets or Sets Open24Hours /// </summary> [DataMember(Name="open24Hours", EmitDefaultValue=false)] public string Open24Hours { get; set; } /// <summary> /// Gets or Sets ContactDetails /// </summary> [DataMember(Name="contactDetails", EmitDefaultValue=false)] public ContactDetails ContactDetails { get; set; } /// <summary> /// Gets or Sets PoiClassification /// </summary> [DataMember(Name="poiClassification", EmitDefaultValue=false)] public PoiClassification PoiClassification { get; set; } /// <summary> /// Gets or Sets EmployeeCount /// </summary> [DataMember(Name="employeeCount", EmitDefaultValue=false)] public EmployeeCount EmployeeCount { get; set; } /// <summary> /// Gets or Sets OrganizationStatusCode /// </summary> [DataMember(Name="organizationStatusCode", EmitDefaultValue=false)] public string OrganizationStatusCode { get; set; } /// <summary> /// Gets or Sets OrganizationStatusCodeDescription /// </summary> [DataMember(Name="organizationStatusCodeDescription", EmitDefaultValue=false)] public string OrganizationStatusCodeDescription { get; set; } /// <summary> /// Gets or Sets ParentBusiness /// </summary> [DataMember(Name="parentBusiness", EmitDefaultValue=false)] public ParentBusiness ParentBusiness { get; set; } /// <summary> /// Gets or Sets TickerSymbol /// </summary> [DataMember(Name="tickerSymbol", EmitDefaultValue=false)] public string TickerSymbol { get; set; } /// <summary> /// Gets or Sets ExchangeName /// </summary> [DataMember(Name="exchangeName", EmitDefaultValue=false)] public string ExchangeName { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Poi {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" BrandName: ").Append(BrandName).Append("\n"); sb.Append(" TradeName: ").Append(TradeName).Append("\n"); sb.Append(" FranchiseName: ").Append(FranchiseName).Append("\n"); sb.Append(" Open24Hours: ").Append(Open24Hours).Append("\n"); sb.Append(" ContactDetails: ").Append(ContactDetails).Append("\n"); sb.Append(" PoiClassification: ").Append(PoiClassification).Append("\n"); sb.Append(" EmployeeCount: ").Append(EmployeeCount).Append("\n"); sb.Append(" OrganizationStatusCode: ").Append(OrganizationStatusCode).Append("\n"); sb.Append(" OrganizationStatusCodeDescription: ").Append(OrganizationStatusCodeDescription).Append("\n"); sb.Append(" ParentBusiness: ").Append(ParentBusiness).Append("\n"); sb.Append(" TickerSymbol: ").Append(TickerSymbol).Append("\n"); sb.Append(" ExchangeName: ").Append(ExchangeName).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Poi); } /// <summary> /// Returns true if Poi instances are equal /// </summary> /// <param name="other">Instance of Poi to be compared</param> /// <returns>Boolean</returns> public bool Equals(Poi other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.BrandName == other.BrandName || this.BrandName != null && this.BrandName.Equals(other.BrandName) ) && ( this.TradeName == other.TradeName || this.TradeName != null && this.TradeName.Equals(other.TradeName) ) && ( this.FranchiseName == other.FranchiseName || this.FranchiseName != null && this.FranchiseName.Equals(other.FranchiseName) ) && ( this.Open24Hours == other.Open24Hours || this.Open24Hours != null && this.Open24Hours.Equals(other.Open24Hours) ) && ( this.ContactDetails == other.ContactDetails || this.ContactDetails != null && this.ContactDetails.Equals(other.ContactDetails) ) && ( this.PoiClassification == other.PoiClassification || this.PoiClassification != null && this.PoiClassification.Equals(other.PoiClassification) ) && ( this.EmployeeCount == other.EmployeeCount || this.EmployeeCount != null && this.EmployeeCount.Equals(other.EmployeeCount) ) && ( this.OrganizationStatusCode == other.OrganizationStatusCode || this.OrganizationStatusCode != null && this.OrganizationStatusCode.Equals(other.OrganizationStatusCode) ) && ( this.OrganizationStatusCodeDescription == other.OrganizationStatusCodeDescription || this.OrganizationStatusCodeDescription != null && this.OrganizationStatusCodeDescription.Equals(other.OrganizationStatusCodeDescription) ) && ( this.ParentBusiness == other.ParentBusiness || this.ParentBusiness != null && this.ParentBusiness.Equals(other.ParentBusiness) ) && ( this.TickerSymbol == other.TickerSymbol || this.TickerSymbol != null && this.TickerSymbol.Equals(other.TickerSymbol) ) && ( this.ExchangeName == other.ExchangeName || this.ExchangeName != null && this.ExchangeName.Equals(other.ExchangeName) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.BrandName != null) hash = hash * 59 + this.BrandName.GetHashCode(); if (this.TradeName != null) hash = hash * 59 + this.TradeName.GetHashCode(); if (this.FranchiseName != null) hash = hash * 59 + this.FranchiseName.GetHashCode(); if (this.Open24Hours != null) hash = hash * 59 + this.Open24Hours.GetHashCode(); if (this.ContactDetails != null) hash = hash * 59 + this.ContactDetails.GetHashCode(); if (this.PoiClassification != null) hash = hash * 59 + this.PoiClassification.GetHashCode(); if (this.EmployeeCount != null) hash = hash * 59 + this.EmployeeCount.GetHashCode(); if (this.OrganizationStatusCode != null) hash = hash * 59 + this.OrganizationStatusCode.GetHashCode(); if (this.OrganizationStatusCodeDescription != null) hash = hash * 59 + this.OrganizationStatusCodeDescription.GetHashCode(); if (this.ParentBusiness != null) hash = hash * 59 + this.ParentBusiness.GetHashCode(); if (this.TickerSymbol != null) hash = hash * 59 + this.TickerSymbol.GetHashCode(); if (this.ExchangeName != null) hash = hash * 59 + this.ExchangeName.GetHashCode(); return hash; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DbSession.cs" company=""> // // </copyright> // <summary> // The db session. // </summary> // -------------------------------------------------------------------------------------------------------------------- #region using directives using System; using System.Linq.Expressions; using RabbitDB.Contracts.Reader; using RabbitDB.Contracts.Session; using RabbitDB.Query; using RabbitDB.Query.Generic; using RabbitDB.Storage; #endregion namespace RabbitDB.Session { /// <summary> /// The db session. /// </summary> public sealed class DbSession : ReadOnlySession, IDbSession { #region Fields /// <summary> /// The _db entity persister. /// </summary> private DbEntityPersister _dbEntityPersister; #endregion #region Construction /// <summary> /// Initializes a new instance of the <see cref="DbSession" /> class. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="dbEngine"> /// The db engine. /// </param> public DbSession(string connectionString, DbEngine dbEngine) : base(connectionString, dbEngine) { } /// <summary> /// Initializes a new instance of the <see cref="DbSession" /> class. /// </summary> /// <param name="assemblyType"> /// The assembly type. /// </param> public DbSession(Type assemblyType) : base(assemblyType) { } /// <summary> /// Initializes a new instance of the <see cref="DbSession" /> class. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> public DbSession(string connectionString) : this(connectionString, DbEngine.SqlServer) { } /// <summary> /// Finalizes an instance of the <see cref="DbSession" /> class. /// </summary> ~DbSession() { if (Disposed == false) { Dispose(); } } #endregion #region Properties /// <summary> /// Gets the configuration. /// </summary> public static Configuration Configuration => Configuration.Instance; /// <summary> /// Gets the db entity persister. /// </summary> /// <exception cref="InvalidOperationException"> /// </exception> internal DbEntityPersister DbEntityPersister { get { if (SqlDialect == null) { throw new InvalidOperationException("SqlDialect is not initialized"); } return _dbEntityPersister ?? (_dbEntityPersister = new DbEntityPersister(DbPersister)); } } #endregion #region Public Methods /// <summary> /// The delete. /// </summary> /// <param name="entity"> /// The entity. /// </param> /// <typeparam name="TEntity"> /// </typeparam> public void Delete<TEntity>(TEntity entity) { DbPersister.Delete(entity); } /// <summary> /// The execute command. /// </summary> /// <param name="sql"> /// The sql. /// </param> /// <param name="arguments"> /// The arguments. /// </param> public void ExecuteCommand(string sql, params object[] arguments) { SqlDialect.ExecuteCommand(new SqlQuery(sql, QueryParameterCollection.Create(arguments))); } /// <summary> /// The insert. /// </summary> /// <param name="entity"> /// The entity. /// </param> /// <typeparam name="TEntity"> /// </typeparam> public void Insert<TEntity>(TEntity entity) { DbPersister.Insert(entity); } /// <summary> /// The update. /// </summary> /// <param name="criteria"> /// The criteria. /// </param> /// <param name="setArguments"> /// The set arguments. /// </param> /// <typeparam name="TEntity"> /// </typeparam> public void Update<TEntity>(Expression<Func<TEntity, bool>> criteria, params object[] setArguments) { DbPersister.Update<TEntity>(new UpdateExpressionQuery<TEntity>(criteria, setArguments)); } /// <summary> /// The update. /// </summary> /// <param name="entity"> /// The entity. /// </param> /// <typeparam name="TEntity"> /// </typeparam> public void Update<TEntity>(TEntity entity) { DbPersister.Update<TEntity>(new UpdateQuery<TEntity>(entity)); } #endregion #region Private Methods /// <summary> /// The load. /// </summary> /// <param name="entity"> /// The entity. /// </param> /// <typeparam name="TEntity"> /// </typeparam> /// <exception cref="Exception"> /// </exception> void IDbSession.Load<TEntity>(TEntity entity) { IEntityReader<TEntity> objectReader = SqlDialect.ExecuteReader<TEntity>(new EntityQuery<TEntity>(entity)); if (objectReader.Load(entity) == false) { throw new Exception("Loading data was not successfull!"); } } /// <summary> /// The persist changes. /// </summary> /// <param name="entity"> /// The entity. /// </param> /// <typeparam name="TEntity"> /// </typeparam> /// <returns> /// The <see cref="bool" />. /// </returns> bool IDbSession.PersistChanges<TEntity>(TEntity entity) { return DbEntityPersister.PersistChanges(entity); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Configuration; using osu.Framework.Localisation; namespace osu.Framework.Tests.Localisation { [TestFixture] public class LocalisationTest { private FrameworkConfigManager config; private LocalisationManager manager; [SetUp] public void Setup() { config = new FakeFrameworkConfigManager(); manager = new LocalisationManager(config); manager.AddLanguage("en", new FakeStorage("en")); } [Test] public void TestNoLanguagesAdded() { // reinitialise without the default language manager = new LocalisationManager(config); var localisedText = manager.GetLocalisedString(new TranslatableString(FakeStorage.LOCALISABLE_STRING_EN, FakeStorage.LOCALISABLE_STRING_EN)); Assert.AreEqual(FakeStorage.LOCALISABLE_STRING_EN, localisedText.Value); } [Test] public void TestNotLocalised() { manager.AddLanguage("ja-JP", new FakeStorage("ja-JP")); config.SetValue(FrameworkSetting.Locale, "ja-JP"); var localisedText = manager.GetLocalisedString(FakeStorage.LOCALISABLE_STRING_EN); Assert.AreEqual(FakeStorage.LOCALISABLE_STRING_EN, localisedText.Value); localisedText.Text = FakeStorage.LOCALISABLE_STRING_JA; Assert.AreEqual(FakeStorage.LOCALISABLE_STRING_JA, localisedText.Value); } [Test] public void TestLocalised() { manager.AddLanguage("ja-JP", new FakeStorage("ja-JP")); var localisedText = manager.GetLocalisedString(new TranslatableString(FakeStorage.LOCALISABLE_STRING_EN, FakeStorage.LOCALISABLE_STRING_EN)); Assert.AreEqual(FakeStorage.LOCALISABLE_STRING_EN, localisedText.Value); config.SetValue(FrameworkSetting.Locale, "ja-JP"); Assert.AreEqual(FakeStorage.LOCALISABLE_STRING_JA_JP, localisedText.Value); } [Test] public void TestLocalisationFallback() { manager.AddLanguage("ja", new FakeStorage("ja")); config.SetValue(FrameworkSetting.Locale, "ja-JP"); var localisedText = manager.GetLocalisedString(new TranslatableString(FakeStorage.LOCALISABLE_STRING_EN, FakeStorage.LOCALISABLE_STRING_EN)); Assert.AreEqual(FakeStorage.LOCALISABLE_STRING_JA, localisedText.Value); } [Test] public void TestFormatted() { const string to_format = "this {0} {1} formatted"; const string arg_0 = "has"; const string arg_1 = "been"; string expectedResult = string.Format(to_format, arg_0, arg_1); var formattedText = manager.GetLocalisedString(string.Format(to_format, arg_0, arg_1)); Assert.AreEqual(expectedResult, formattedText.Value); } [Test] public void TestFormattedInterpolation() { const string arg_0 = "formatted"; manager.AddLanguage("ja-JP", new FakeStorage("ja")); config.SetValue(FrameworkSetting.Locale, "ja-JP"); string expectedResult = string.Format(FakeStorage.LOCALISABLE_FORMAT_STRING_JA, arg_0); var formattedText = manager.GetLocalisedString(new TranslatableString(FakeStorage.LOCALISABLE_FORMAT_STRING_EN, interpolation: $"The {arg_0} fallback should only matches argument count")); Assert.AreEqual(expectedResult, formattedText.Value); } [Test] public void TestFormattedAndLocalised() { const string arg_0 = "formatted"; string expectedResult = string.Format(FakeStorage.LOCALISABLE_FORMAT_STRING_JA, arg_0); manager.AddLanguage("ja", new FakeStorage("ja")); config.SetValue(FrameworkSetting.Locale, "ja"); var formattedText = manager.GetLocalisedString(new TranslatableString(FakeStorage.LOCALISABLE_FORMAT_STRING_EN, FakeStorage.LOCALISABLE_FORMAT_STRING_EN, arg_0)); Assert.AreEqual(expectedResult, formattedText.Value); } [Test] public void TestNumberCultureAware() { const double value = 1.23; manager.AddLanguage("fr", new FakeStorage("fr")); config.SetValue(FrameworkSetting.Locale, "fr"); var expectedResult = string.Format(new CultureInfo("fr"), FakeStorage.LOCALISABLE_NUMBER_FORMAT_STRING_FR, value); Assert.AreEqual("number 1,23 FR", expectedResult); // FR uses comma for decimal point. var formattedText = manager.GetLocalisedString(new TranslatableString(FakeStorage.LOCALISABLE_NUMBER_FORMAT_STRING_EN, null, value)); Assert.AreEqual(expectedResult, formattedText.Value); } [Test] public void TestStorageNotFound() { manager.AddLanguage("ja", new FakeStorage("ja")); config.SetValue(FrameworkSetting.Locale, "ja"); const string expected_fallback = "fallback string"; var formattedText = manager.GetLocalisedString(new TranslatableString("no such key", expected_fallback)); Assert.AreEqual(expected_fallback, formattedText.Value); } [Test] public void TestUnicodePreference() { const string non_unicode = "non unicode"; const string unicode = "unicode"; var text = manager.GetLocalisedString(new RomanisableString(unicode, non_unicode)); config.SetValue(FrameworkSetting.ShowUnicode, true); Assert.AreEqual(unicode, text.Value); config.SetValue(FrameworkSetting.ShowUnicode, false); Assert.AreEqual(non_unicode, text.Value); } [Test] public void TestUnicodeStringChanging() { const string non_unicode_1 = "non unicode 1"; const string non_unicode_2 = "non unicode 2"; const string unicode_1 = "unicode 1"; const string unicode_2 = "unicode 2"; var text = manager.GetLocalisedString(new RomanisableString(unicode_1, non_unicode_1)); config.SetValue(FrameworkSetting.ShowUnicode, false); Assert.AreEqual(non_unicode_1, text.Value); text.Text = new RomanisableString(unicode_1, non_unicode_2); Assert.AreEqual(non_unicode_2, text.Value); config.SetValue(FrameworkSetting.ShowUnicode, true); Assert.AreEqual(unicode_1, text.Value); text.Text = new RomanisableString(unicode_2, non_unicode_2); Assert.AreEqual(unicode_2, text.Value); } [Test] public void TestEmptyStringFallback([Values("", null)] string emptyValue) { const string non_unicode_fallback = "non unicode"; const string unicode_fallback = "unicode"; var text = manager.GetLocalisedString(new RomanisableString(unicode_fallback, emptyValue)); config.SetValue(FrameworkSetting.ShowUnicode, false); Assert.AreEqual(unicode_fallback, text.Value); text = manager.GetLocalisedString(new RomanisableString(emptyValue, non_unicode_fallback)); config.SetValue(FrameworkSetting.ShowUnicode, true); Assert.AreEqual(non_unicode_fallback, text.Value); } private class FakeFrameworkConfigManager : FrameworkConfigManager { protected override string Filename => null; public FakeFrameworkConfigManager() : base(null) { } protected override void InitialiseDefaults() { SetDefault(FrameworkSetting.Locale, ""); SetDefault(FrameworkSetting.ShowUnicode, true); } } private class FakeStorage : ILocalisationStore { public const string LOCALISABLE_STRING_EN = "localised EN"; public const string LOCALISABLE_STRING_JA = "localised JA"; public const string LOCALISABLE_STRING_JA_JP = "localised JA-JP"; public const string LOCALISABLE_FORMAT_STRING_EN = "{0} localised EN"; public const string LOCALISABLE_FORMAT_STRING_JA = "{0} localised JA"; public const string LOCALISABLE_NUMBER_FORMAT_STRING_EN = "number {0} EN"; public const string LOCALISABLE_NUMBER_FORMAT_STRING_FR = "number {0} FR"; public CultureInfo EffectiveCulture { get; } private readonly string locale; public FakeStorage(string locale) { this.locale = locale; EffectiveCulture = new CultureInfo(locale); } public async Task<string> GetAsync(string name) => await Task.Run(() => Get(name)).ConfigureAwait(false); public string Get(string name) { switch (name) { case LOCALISABLE_STRING_EN: switch (locale) { default: return LOCALISABLE_STRING_EN; case "ja": return LOCALISABLE_STRING_JA; case "ja-JP": return LOCALISABLE_STRING_JA_JP; } case LOCALISABLE_FORMAT_STRING_EN: switch (locale) { default: return LOCALISABLE_FORMAT_STRING_EN; case "ja": return LOCALISABLE_FORMAT_STRING_JA; } case LOCALISABLE_NUMBER_FORMAT_STRING_EN: switch (locale) { default: return LOCALISABLE_NUMBER_FORMAT_STRING_EN; case "fr": return LOCALISABLE_NUMBER_FORMAT_STRING_FR; } default: return null; } } public Stream GetStream(string name) => throw new NotSupportedException(); public void Dispose() { } public IEnumerable<string> GetAvailableResources() => Enumerable.Empty<string>(); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Reflection; using System.Threading; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications.Capabilities; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Communications.Capabilities.Caps; using OSDArray=OpenMetaverse.StructuredData.OSDArray; using OSDMap=OpenMetaverse.StructuredData.OSDMap; using Amib.Threading; namespace OpenSim.Region.CoreModules.World.WorldMap { public class WorldMapModule : INonSharedRegionModule, IWorldMapModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string DEFAULT_WORLD_MAP_EXPORT_PATH = "exportmap.jpg"; private static readonly string m_mapLayerPath = "0001/"; //private IConfig m_config; protected Scene m_scene; private List<MapBlockData> cachedMapBlocks = new List<MapBlockData>(); private int cachedTime = 0; private byte[] myMapImageJPEG; protected volatile bool m_Enabled = false; private Dictionary<UUID, MapRequestState> m_openRequests = new Dictionary<UUID, MapRequestState>(); private Dictionary<string, int> m_blacklistedurls = new Dictionary<string, int>(); private Dictionary<ulong, int> m_blacklistedregions = new Dictionary<ulong, int>(); private Dictionary<ulong, string> m_cachedRegionMapItemsAddress = new Dictionary<ulong, string>(); private List<UUID> m_rootAgents = new List<UUID>(); private SmartThreadPool _blockRequestPool; private SmartThreadPool _infoRequestPool; private Dictionary<UUID, IWorkItemResult> _currentRequests = new Dictionary<UUID, IWorkItemResult>(); //private int CacheRegionsDistance = 256; #region INonSharedRegionModule Members public virtual void Initialize(IConfigSource config) { IConfig startupConfig = config.Configs["Startup"]; if (startupConfig.GetString("WorldMapModule", "WorldMap") == "WorldMap") m_Enabled = true; STPStartInfo reqPoolStartInfo = new STPStartInfo(); reqPoolStartInfo.MaxWorkerThreads = 2; reqPoolStartInfo.IdleTimeout = 5 * 60 * 1000; reqPoolStartInfo.ThreadPriority = ThreadPriority.Lowest; STPStartInfo infoReqPoolStartInfo = new STPStartInfo(); reqPoolStartInfo.MaxWorkerThreads = 4; reqPoolStartInfo.IdleTimeout = 5 * 60 * 1000; reqPoolStartInfo.ThreadPriority = ThreadPriority.Lowest; _blockRequestPool = new SmartThreadPool(reqPoolStartInfo); _blockRequestPool.Name = "Map Block Requests"; _infoRequestPool = new SmartThreadPool(infoReqPoolStartInfo); _infoRequestPool.Name = "Map Info Requests"; } public virtual void AddRegion (Scene scene) { if (!m_Enabled) return; lock (scene) { m_scene = scene; m_scene.RegisterModuleInterface<IWorldMapModule>(this); m_scene.AddCommand( this, "export-map", "export-map [<path>]", "Save an image of the world map", HandleExportWorldMapConsoleCommand); AddHandlers(); } } public virtual void RemoveRegion (Scene scene) { if (!m_Enabled) return; lock (m_scene) { m_Enabled = false; RemoveHandlers(); m_scene = null; } } public virtual void RegionLoaded (Scene scene) { } public virtual void Close() { } public virtual string Name { get { return "WorldMapModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion // this has to be called with a lock on m_scene protected virtual void AddHandlers() { myMapImageJPEG = new byte[0]; string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString(); regionimage = regionimage.Replace("-", String.Empty); m_log.Info("[WORLD MAP]: JPEG Map location: http://" + m_scene.RegionInfo.ExternalHostName + ":" + m_scene.RegionInfo.HttpPort.ToString() + "/index.php?method=" + regionimage); m_scene.CommsManager.HttpServer.AddHTTPHandler(regionimage, OnHTTPGetMapImage); m_scene.CommsManager.HttpServer.AddLLSDHandler( "/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest); m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnNewClient += OnNewClient; m_scene.EventManager.OnClientClosed += ClientLoggedOut; m_scene.EventManager.OnMakeChildAgent += MakeChildAgent; m_scene.EventManager.OnMakeRootAgent += MakeRootAgent; } // this has to be called with a lock on m_scene protected virtual void RemoveHandlers() { m_scene.EventManager.OnMakeRootAgent -= MakeRootAgent; m_scene.EventManager.OnMakeChildAgent -= MakeChildAgent; m_scene.EventManager.OnClientClosed -= ClientLoggedOut; m_scene.EventManager.OnNewClient -= OnNewClient; m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString(); regionimage = regionimage.Replace("-", String.Empty); m_scene.CommsManager.HttpServer.RemoveLLSDHandler("/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest); m_scene.CommsManager.HttpServer.RemoveHTTPHandler(String.Empty, regionimage); } public void OnRegisterCaps(UUID agentID, Caps caps) { //m_log.DebugFormat("[WORLD MAP]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps); string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("MapLayer", new RestStreamHandler("POST", capsBase + m_mapLayerPath, delegate(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return MapLayerRequest(request, path, param, agentID, caps); })); } /// <summary> /// Callback for a map layer request /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string MapLayerRequest(string request, string path, string param, UUID agentID, Caps caps) { //try //{ //m_log.DebugFormat("[MAPLAYER]: request: {0}, path: {1}, param: {2}, agent:{3}", //request, path, param,agentID.ToString()); // this is here because CAPS map requests work even beyond the 10,000 limit. ScenePresence avatarPresence = null; m_scene.TryGetAvatar(agentID, out avatarPresence); if (avatarPresence != null) { bool lookup = false; lock (cachedMapBlocks) { if (cachedMapBlocks.Count > 0 && ((cachedTime + 1800) > Util.UnixTimeSinceEpoch())) { List<MapBlockData> mapBlocks; mapBlocks = cachedMapBlocks; avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0); } else { lookup = true; } } if (lookup) { List<MapBlockData> mapBlocks; mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks((int)m_scene.RegionInfo.RegionLocX - 8, (int)m_scene.RegionInfo.RegionLocY - 8, (int)m_scene.RegionInfo.RegionLocX + 8, (int)m_scene.RegionInfo.RegionLocY + 8); avatarPresence.ControllingClient.SendMapBlock(mapBlocks,0); lock (cachedMapBlocks) cachedMapBlocks = mapBlocks; cachedTime = Util.UnixTimeSinceEpoch(); } } LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse()); return mapResponse.ToString(); } /// <summary> /// /// </summary> /// <param name="mapReq"></param> /// <returns></returns> public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq) { m_log.Debug("[WORLD MAP]: MapLayer Request in region: " + m_scene.RegionInfo.RegionName); LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse()); return mapResponse; } /// <summary> /// /// </summary> /// <returns></returns> protected static OSDMapLayer GetOSDMapLayerResponse() { OSDMapLayer mapLayer = new OSDMapLayer(); mapLayer.Right = 5000; mapLayer.Top = 5000; mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006"); return mapLayer; } #region EventHandlers /// <summary> /// Registered for event /// </summary> /// <param name="client"></param> private void OnNewClient(IClientAPI client) { client.OnRequestMapBlocks += RequestMapBlocks; client.OnMapItemRequest += HandleMapItemRequest; } /// <summary> /// Client logged out, check to see if there are any more root agents in the simulator /// If not, stop the mapItemRequest Thread /// Event handler /// </summary> /// <param name="AgentId">AgentID that logged out</param> private void ClientLoggedOut(UUID AgentId, Scene scene) { lock (m_rootAgents) { if (m_rootAgents.Contains(AgentId)) { m_rootAgents.Remove(AgentId); } } } #endregion public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { lock (m_rootAgents) { if (!m_rootAgents.Contains(remoteClient.AgentId)) return; } uint xstart = 0; uint ystart = 0; Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out xstart, out ystart); if (itemtype == 6) // we only sevice 6 right now (avatar green dots) { if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle) { // Local Map Item Request List<ScenePresence> avatars = m_scene.GetAvatars(); int tc = Environment.TickCount; List<mapItemReply> mapitems = new List<mapItemReply>(); mapItemReply mapitem = new mapItemReply(); if (avatars.Count == 0 || avatars.Count == 1) { mapitem = new mapItemReply(); mapitem.x = (uint)(xstart + 1); mapitem.y = (uint)(ystart + 1); mapitem.id = UUID.Zero; mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()); mapitem.Extra = 0; mapitem.Extra2 = 0; mapitems.Add(mapitem); } else { foreach (ScenePresence avatar in avatars) { // Don't send a green dot for yourself Vector3 avpos; if ((avatar.UUID != remoteClient.AgentId) && avatar.HasSafePosition(out avpos)) { mapitem = new mapItemReply(); mapitem.x = (uint)(xstart + avpos.X); mapitem.y = (uint)(ystart + avpos.Y); mapitem.id = UUID.Zero; mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()); mapitem.Extra = 1; mapitem.Extra2 = 0; mapitems.Add(mapitem); } } } remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); } else { RequestMapItems(String.Empty,remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle); } } } /// <summary> /// Sends the mapitem response to the IClientAPI /// </summary> /// <param name="response">The OSDMap Response for the mapitem</param> private void RequestMapItemsCompleted(OSDMap response) { UUID requestID = response["requestID"].AsUUID(); if (requestID != UUID.Zero) { MapRequestState mrs = new MapRequestState(); mrs.agentID = UUID.Zero; lock (m_openRequests) { if (m_openRequests.ContainsKey(requestID)) { mrs = m_openRequests[requestID]; m_openRequests.Remove(requestID); } } if (mrs.agentID != UUID.Zero) { ScenePresence av = null; m_scene.TryGetAvatar(mrs.agentID, out av); if (av != null) { if (response.ContainsKey(mrs.itemtype.ToString())) { List<mapItemReply> returnitems = new List<mapItemReply>(); OSDArray itemarray = (OSDArray)response[mrs.itemtype.ToString()]; for (int i = 0; i < itemarray.Count; i++) { OSDMap mapitem = (OSDMap)itemarray[i]; mapItemReply mi = new mapItemReply(); mi.x = (uint)mapitem["X"].AsInteger(); mi.y = (uint)mapitem["Y"].AsInteger(); mi.id = mapitem["ID"].AsUUID(); mi.Extra = mapitem["Extra"].AsInteger(); mi.Extra2 = mapitem["Extra2"].AsInteger(); mi.name = mapitem["Name"].AsString(); returnitems.Add(mi); } av.ControllingClient.SendMapItemReply(returnitems.ToArray(), mrs.itemtype, mrs.flags); } } } } } /// <summary> /// Enqueue the MapItem request for remote processing /// </summary> /// <param name="httpserver">blank string, we discover this in the process</param> /// <param name="id">Agent ID that we are making this request on behalf</param> /// <param name="flags">passed in from packet</param> /// <param name="EstateID">passed in from packet</param> /// <param name="godlike">passed in from packet</param> /// <param name="itemtype">passed in from packet</param> /// <param name="regionhandle">Region we're looking up</param> public void RequestMapItems(string httpserver, UUID id, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { bool dorequest = true; lock (m_rootAgents) { if (!m_rootAgents.Contains(id)) dorequest = false; } if (dorequest) { _infoRequestPool.QueueWorkItem( delegate() { OSDMap response = RequestMapItemsAsync(httpserver, id, flags, EstateID, godlike, itemtype, regionhandle); RequestMapItemsCompleted(response); } ); } } /// <summary> /// Does the actual remote mapitem request /// This should be called from an asynchronous thread /// Request failures get blacklisted until region restart so we don't /// continue to spend resources trying to contact regions that are down. /// </summary> /// <param name="httpserver">blank string, we discover this in the process</param> /// <param name="id">Agent ID that we are making this request on behalf</param> /// <param name="flags">passed in from packet</param> /// <param name="EstateID">passed in from packet</param> /// <param name="godlike">passed in from packet</param> /// <param name="itemtype">passed in from packet</param> /// <param name="regionhandle">Region we're looking up</param> /// <returns></returns> private OSDMap RequestMapItemsAsync(string httpserver, UUID id, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { bool blacklisted = false; lock (m_blacklistedregions) { if (m_blacklistedregions.ContainsKey(regionhandle)) blacklisted = true; } if (blacklisted) return new OSDMap(); UUID requestID = UUID.Random(); lock (m_cachedRegionMapItemsAddress) { if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) httpserver = m_cachedRegionMapItemsAddress[regionhandle]; } if (String.IsNullOrEmpty(httpserver)) { RegionInfo mreg = m_scene.SceneGridService.RequestNeighbouringRegionInfo(regionhandle); if (mreg != null) { httpserver = "http://" + mreg.ExternalHostName + ":" + mreg.HttpPort + "/MAP/MapItems/" + regionhandle.ToString(); lock (m_cachedRegionMapItemsAddress) { if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver); } } else { lock (m_blacklistedregions) { if (!m_blacklistedregions.ContainsKey(regionhandle)) m_blacklistedregions.Add(regionhandle, Environment.TickCount); } m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString()); } } blacklisted = false; lock (m_blacklistedurls) { if (m_blacklistedurls.ContainsKey(httpserver)) blacklisted = true; } // Can't find the http server if (String.IsNullOrEmpty(httpserver) || blacklisted) return new OSDMap(); MapRequestState mrs = new MapRequestState(); mrs.agentID = id; mrs.EstateID = EstateID; mrs.flags = flags; mrs.godlike = godlike; mrs.itemtype=itemtype; mrs.regionhandle = regionhandle; lock (m_openRequests) m_openRequests.Add(requestID, mrs); WebRequest mapitemsrequest = WebRequest.Create(httpserver); mapitemsrequest.Method = "POST"; mapitemsrequest.ContentType = "application/xml+llsd"; OSDMap RAMap = new OSDMap(); // string RAMapString = RAMap.ToString(); OSD LLSDofRAMap = RAMap; // RENAME if this works byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap); OSDMap responseMap = new OSDMap(); responseMap["requestID"] = OSD.FromUUID(requestID); Stream os = null; try { // send the Post mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send os = mapitemsrequest.GetRequestStream(); os.Write(buffer, 0, buffer.Length); //Send it os.Close(); //m_log.DebugFormat("[WORLD MAP]: Getting MapItems from Sim {0}", httpserver); } catch (WebException ex) { m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); lock (m_blacklistedurls) { if (!m_blacklistedurls.ContainsKey(httpserver)) m_blacklistedurls.Add(httpserver, Environment.TickCount); } m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver); return responseMap; } string response_mapItems_reply = null; { // get the response try { WebResponse webResponse = mapitemsrequest.GetResponse(); if (webResponse != null) { StreamReader sr = new StreamReader(webResponse.GetResponseStream()); response_mapItems_reply = sr.ReadToEnd().Trim(); } else { return new OSDMap(); } } catch (WebException) { responseMap["connect"] = OSD.FromBoolean(false); lock (m_blacklistedurls) { if (!m_blacklistedurls.ContainsKey(httpserver)) m_blacklistedurls.Add(httpserver, Environment.TickCount); } m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver); return responseMap; } OSD rezResponse = null; try { rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply); responseMap = (OSDMap)rezResponse; responseMap["requestID"] = OSD.FromUUID(requestID); } catch (Exception) { //m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } } return responseMap; } private void RequestCompleted(IWorkItemResult workItem) { lock (_currentRequests) { UUID userId = (UUID)workItem.State; IWorkItemResult currentRequest; if (_currentRequests.TryGetValue(userId, out currentRequest)) { if (currentRequest == workItem) { _currentRequests.Remove(userId); } } } } /// <summary> /// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates /// </summary> /// <param name="minX"></param> /// <param name="minY"></param> /// <param name="maxX"></param> /// <param name="maxY"></param> public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag) { IWorkItemResult newItem = null; if ((flag & 0x10000) != 0) // user clicked on the map a tile that isn't visible { lock (_currentRequests) { CancelCurrentRequestForUser(remoteClient); newItem = _blockRequestPool.QueueWorkItem( delegate(object state) { RequestNonVisibleMapTile(remoteClient, minX, minY, maxX, maxY, flag); return null; }, remoteClient.AgentId, this.RequestCompleted ); _currentRequests[remoteClient.AgentId] = newItem; } } else { lock (_currentRequests) { // normal mapblock request. Use the provided values CancelCurrentRequestForUser(remoteClient); newItem = _blockRequestPool.QueueWorkItem( delegate(object state) { GetAndSendBlocks(remoteClient, minX, minY, maxX, maxY, flag); return null; }, remoteClient.AgentId, this.RequestCompleted ); _currentRequests[remoteClient.AgentId] = newItem; } } } private void CancelCurrentRequestForUser(IClientAPI remoteClient) { IWorkItemResult foundResult; if (_currentRequests.TryGetValue(remoteClient.AgentId, out foundResult)) { foundResult.Cancel(); } } private void RequestNonVisibleMapTile(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag) { List<MapBlockData> response = new List<MapBlockData>(); // this should return one mapblock at most. But make sure: Look whether the one we requested is in there List<MapBlockData> mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks(minX, minY, maxX, maxY); if (mapBlocks != null) { foreach (MapBlockData block in mapBlocks) { if (block.X == minX && block.Y == minY) { // found it => add it to response response.Add(block); break; } } } if (response.Count == 0) { // response still empty => couldn't find the map-tile the user clicked on => tell the client MapBlockData block = new MapBlockData(); block.X = (ushort)minX; block.Y = (ushort)minY; block.Name = "(NONE)"; // The viewer insists that the region name never be empty. block.Access = 255; // == not there (254 is "region down", 255 is "region non-existent") response.Add(block); } //(flag & 0x10000) != 0 is sent by v2 viewers, and it expects flag 2 back remoteClient.SendMapBlock(response, flag & 0xffff); } protected virtual void GetAndSendBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag) { List<MapBlockData> mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks(minX - 4, minY - 4, maxX + 4, maxY + 4); remoteClient.SendMapBlock(mapBlocks, flag); } /// <summary> /// The last time a mapimage was cached /// </summary> private DateTime _lastImageGenerationTime = DateTime.Now; /// <summary> /// Number of days to cache a mapimage /// </summary> private const int MAPIMAGE_CACHE_TIME = 2; public Hashtable OnHTTPGetMapImage(Hashtable keysvals) { bool forceRefresh = false; if (keysvals.ContainsKey("requestvars")) { Hashtable rvars = (Hashtable)keysvals["requestvars"]; if (rvars.ContainsKey("forcerefresh")) forceRefresh = true; } if (forceRefresh) { m_log.Debug("[WORLD MAP]: Forcing refresh of map tile"); //regenerate terrain m_scene.CreateTerrainTexture(false); } m_log.Debug("[WORLD MAP]: Sending map image jpeg"); Hashtable reply = new Hashtable(); int statuscode = 200; byte[] jpeg = new byte[0]; if (myMapImageJPEG.Length == 0 || (DateTime.Now - _lastImageGenerationTime).TotalDays > MAPIMAGE_CACHE_TIME || forceRefresh) { MemoryStream imgstream = new MemoryStream(); Bitmap mapTexture = new Bitmap(1,1); ManagedImage managedImage; Image image = (Image)mapTexture; try { // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data imgstream = new MemoryStream(); // non-async because we know we have the asset immediately. AssetBase mapasset = m_scene.CommsManager.AssetCache.GetAsset(m_scene.RegionInfo.lastMapUUID, AssetRequestInfo.InternalRequest()); // Decode image to System.Drawing.Image if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image)) { // Save to bitmap mapTexture = new Bitmap(image); EncoderParameters myEncoderParameters = new EncoderParameters(); myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); // Save bitmap to stream mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters); // Write the stream to a byte array for output jpeg = imgstream.ToArray(); myMapImageJPEG = jpeg; _lastImageGenerationTime = DateTime.Now; } } catch (Exception) { // Dummy! m_log.Warn("[WORLD MAP]: Unable to generate Map image"); } finally { // Reclaim memory, these are unmanaged resources mapTexture.Dispose(); image.Dispose(); imgstream.Close(); imgstream.Dispose(); } } else { // Use cached version so we don't have to loose our mind jpeg = myMapImageJPEG; } reply["str_response_string"] = Convert.ToBase64String(jpeg); reply["int_response_code"] = statuscode; reply["content_type"] = "image/jpeg"; return reply; } // From msdn private static ImageCodecInfo GetEncoderInfo(String mimeType) { ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } /// <summary> /// Export the world map /// </summary> /// <param name="fileName"></param> public void HandleExportWorldMapConsoleCommand(string module, string[] cmdparams) { if (m_scene.ConsoleScene() == null) { // FIXME: If console region is root then this will be printed by every module. Currently, there is no // way to prevent this, short of making the entire module shared (which is complete overkill). // One possibility is to return a bool to signal whether the module has completely handled the command m_log.InfoFormat("[WORLD MAP]: Please change to a specific region in order to export its world map"); return; } if (m_scene.ConsoleScene() != m_scene) return; string exportPath; if (cmdparams.Length > 1) exportPath = cmdparams[1]; else exportPath = DEFAULT_WORLD_MAP_EXPORT_PATH; m_log.InfoFormat( "[WORLD MAP]: Exporting world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath); List<MapBlockData> mapBlocks = m_scene.CommsManager.GridService.RequestNeighbourMapBlocks( (int)(m_scene.RegionInfo.RegionLocX - 9), (int)(m_scene.RegionInfo.RegionLocY - 9), (int)(m_scene.RegionInfo.RegionLocX + 9), (int)(m_scene.RegionInfo.RegionLocY + 9)); List<AssetBase> textures = new List<AssetBase>(); List<Image> bitImages = new List<Image>(); foreach (MapBlockData mapBlock in mapBlocks) { AssetBase texAsset = m_scene.CommsManager.AssetCache.GetAsset(mapBlock.MapImageId, AssetRequestInfo.InternalRequest()); if (texAsset != null) { textures.Add(texAsset); } else { texAsset = m_scene.CommsManager.AssetCache.GetAsset(mapBlock.MapImageId, AssetRequestInfo.InternalRequest()); if (texAsset != null) { textures.Add(texAsset); } } } foreach (AssetBase asset in textures) { ManagedImage managedImage; Image image; if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image)) bitImages.Add(image); } Bitmap mapTexture = new Bitmap(2560, 2560); Graphics g = Graphics.FromImage(mapTexture); SolidBrush sea = new SolidBrush(Color.DarkBlue); g.FillRectangle(sea, 0, 0, 2560, 2560); for (int i = 0; i < mapBlocks.Count; i++) { ushort x = (ushort)((mapBlocks[i].X - m_scene.RegionInfo.RegionLocX) + 10); ushort y = (ushort)((mapBlocks[i].Y - m_scene.RegionInfo.RegionLocY) + 10); g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128); } mapTexture.Save(exportPath, ImageFormat.Jpeg); m_log.InfoFormat( "[WORLD MAP]: Successfully exported world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath); } public OSD HandleRemoteMapItemRequest(string path, OSD request, IPEndPoint endpoint) { uint xstart = 0; uint ystart = 0; Utils.LongToUInts(m_scene.RegionInfo.RegionHandle,out xstart,out ystart); OSDMap responsemap = new OSDMap(); OSDMap responsemapdata = new OSDMap(); int tc = Environment.TickCount; List<ScenePresence> avatars = m_scene.GetAvatars(); OSDArray responsearr = new OSDArray(avatars.Count); if (avatars.Count == 0) { responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1)); responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); responsemapdata["Extra"] = OSD.FromInteger(0); responsemapdata["Extra2"] = OSD.FromInteger(0); responsearr.Add(responsemapdata); responsemap["6"] = responsearr; } else { responsearr = new OSDArray(avatars.Count); foreach (ScenePresence av in avatars) { Vector3 avpos; if (av.HasSafePosition(out avpos)) { responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + avpos.X)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + avpos.Y)); responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); responsemapdata["Extra"] = OSD.FromInteger(1); responsemapdata["Extra2"] = OSD.FromInteger(0); responsearr.Add(responsemapdata); } } responsemap["6"] = responsearr; } return responsemap; } public void LazySaveGeneratedMaptile(byte[] data, bool temporary) { // Overwrites the local Asset cache with new maptile data // Assets are single write, this causes the asset server to ignore this update, // but the local asset cache does not // this is on purpose! The net result of this is the region always has the most up to date // map tile while protecting the (grid) asset database from bloat caused by a new asset each // time a mapimage is generated! UUID lastMapRegionUUID = m_scene.RegionInfo.lastMapUUID; int lastMapRefresh = 0; int twoDays = 172800; int RefreshSeconds = twoDays; try { lastMapRefresh = Convert.ToInt32(m_scene.RegionInfo.lastMapRefresh); } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } UUID TerrainImageUUID = UUID.Random(); if (lastMapRegionUUID == UUID.Zero || (lastMapRefresh + RefreshSeconds) < Util.UnixTimeSinceEpoch()) { m_scene.RegionInfo.SaveLastMapUUID(TerrainImageUUID); m_log.Debug("[MAPTILE]: STORING MAPTILE IMAGE"); } else { TerrainImageUUID = lastMapRegionUUID; m_log.Debug("[MAPTILE]: REUSING OLD MAPTILE IMAGE ID"); } m_scene.RegionInfo.RegionSettings.TerrainImageID = TerrainImageUUID; AssetBase asset = new AssetBase(); asset.FullID = m_scene.RegionInfo.RegionSettings.TerrainImageID; asset.Data = data; asset.Name = "terrainImage_" + m_scene.RegionInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString(); asset.Description = m_scene.RegionInfo.RegionName; asset.Type = 0; asset.Temporary = temporary; try { m_scene.CommsManager.AssetCache.AddAsset(asset, AssetRequestInfo.InternalRequest()); } catch (AssetServerException) { } } private void MakeRootAgent(ScenePresence avatar) { lock (m_rootAgents) { if (!m_rootAgents.Contains(avatar.UUID)) { m_rootAgents.Add(avatar.UUID); } } } private void MakeChildAgent(ScenePresence avatar) { lock (m_rootAgents) { if (m_rootAgents.Contains(avatar.UUID)) { m_rootAgents.Remove(avatar.UUID); } } } } public struct MapRequestState { public UUID agentID; public uint flags; public uint EstateID; public bool godlike; public uint itemtype; public ulong regionhandle; } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 3/8/2010 11:54:49 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.IO; namespace DotSpatial.Data { /// <summary> /// Stream extensions /// </summary> public static class StreamExt { /// <summary> /// Attempts to read count of bytes from stream. /// </summary> /// <param name="stream">Input stream.</param> /// <param name="count">Count of bytes.</param> /// <returns>Bytes array.</returns> public static byte[] ReadBytes(this Stream stream, int count) { var bytes = new byte[count]; stream.Read(bytes, 0, bytes.Length); return bytes; } /// <summary> /// Attempts to read the specified T. If this system is /// doesn't match the specified endian, then this will reverse the array of bytes, /// so that it corresponds with the big-endian format. /// </summary> /// <param name="stream">The stream to read the value from</param> /// <param name="endian">Specifies what endian property should be used.</param> /// <returns>The integer value</returns> public static int ReadInt32(this Stream stream, Endian endian = Endian.LittleEndian) { var val = new byte[4]; stream.Read(val, 0, 4); if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian) { Array.Reverse(val); } return BitConverter.ToInt32(val, 0); } /// <summary> /// Reads the specified number of integers. If a value other than the /// systems endian format is specified the values will be reversed. /// </summary> /// <param name="stream">The stream to read from</param> /// <param name="count">The integer count of integers to read</param> /// <param name="endian">The endian order of the bytes.</param> /// <returns>The array of integers that will have count integers.</returns> public static int[] ReadInt32(this Stream stream, int count, Endian endian = Endian.LittleEndian) { var result = new int[count]; var val = new byte[4 * count]; stream.Read(val, 0, val.Length); if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian) { for (var i = 0; i < count; i++) { var temp = new byte[4]; Array.Copy(val, i * 4, temp, 0, 4); Array.Reverse(temp); Array.Copy(temp, 0, val, i * 4, 4); } } Buffer.BlockCopy(val, 0, result, 0, count * 4); return result; } /// <summary> /// Reads a double precision value from the stream. If this system /// is not little endian, it will reverse the individual memebrs. /// </summary> /// <param name="stream">The stream to read the values from.</param> /// <returns>A double precision value</returns> public static double ReadDouble(this Stream stream) { return ReadDouble(stream, 1)[0]; } /// <summary> /// Reads the specified number of double precision values. If this system /// does not match the specified endian, the bytes will be reversed. /// </summary> /// <param name="stream">The stream to read the values from.</param> /// <param name="count">The integer count of doubles to read.</param> /// <param name="endian">The endian to use.</param> /// <returns>An array with the double values that were read.</returns> public static double[] ReadDouble(this Stream stream, int count, Endian endian = Endian.LittleEndian) { var val = new byte[count * 8]; stream.Read(val, 0, count * 8); if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian) { for (var i = 0; i < count; i++) { var temp = new byte[8]; Array.Copy(val, i * 8, temp, 0, 8); Array.Reverse(temp); Array.Copy(temp, 0, val, i * 8, 8); } } var result = new double[count]; Buffer.BlockCopy(val, 0, result, 0, count * 8); return result; } /// <summary> /// Writes the specified integer value to the stream as big endian. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="value">The integer value to write in big endian form.</param> public static void WriteBe(this Stream stream, int value) { var val = BitConverter.GetBytes(value); if (BitConverter.IsLittleEndian) Array.Reverse(val); stream.Write(val, 0, 4); } /// <summary> /// Writes the specified integer value to the stream as little endian. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="value">The integer value to write in little endian form.</param> public static void WriteLe(this Stream stream, int value) { var val = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) Array.Reverse(val); stream.Write(val, 0, 4); } /// <summary> /// Checks that the endian order is ok for integers and then writes the number of array items /// that are defined by startIndex and count to the stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="values">The integer values to write in little endian form.</param> /// <param name="startIndex">The integer start index in the integer array to begin writing.</param> /// <param name="count">The integer count of integer to write.</param> public static void WriteLe(this Stream stream, int[] values, int startIndex, int count) { var bytes = new byte[count * 4]; Buffer.BlockCopy(values, startIndex * 4, bytes, 0, bytes.Length); if (!BitConverter.IsLittleEndian) { // Reverse to little endian if this is a big endian machine var temp = bytes; bytes = new byte[temp.Length]; Array.Reverse(temp); for (var i = 0; i < count; i++) { Array.Copy(temp, i * 4, bytes, (count - i - 1) * 4, 4); } } stream.Write(bytes, 0, bytes.Length); } /// <summary> /// Writes the specified double value to the stream as little endian. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="value">The double value to write in little endian form.</param> public static void WriteLe(this Stream stream, double value) { var val = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) Array.Reverse(val); stream.Write(val, 0, 8); } /// <summary> /// Checks that the endian order is ok for doubles and then writes the entire array to the stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="values">The double values to write in little endian form.</param> public static void WriteLe(this Stream stream, double[] values) { WriteLe(stream, values, 0, values.Length); } /// <summary> /// Checks that the endian order is ok for doubles and then writes the number of array items /// that are defined by startIndex and count to the stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="values">The double values to write in little endian form.</param> /// <param name="startIndex">The integer start index in the double array to begin writing.</param> /// <param name="count">The integer count of doubles to write.</param> public static void WriteLe(this Stream stream, double[] values, int startIndex, int count) { var bytes = new byte[count * 8]; Buffer.BlockCopy(values, startIndex * 8, bytes, 0, bytes.Length); if (!BitConverter.IsLittleEndian) { // Reverse to little endian if this is a big endian machine var temp = bytes; bytes = new byte[temp.Length]; Array.Reverse(temp); for (var i = 0; i < count; i++) { Array.Copy(temp, i * 8, bytes, (count - i - 1) * 8, 8); } } stream.Write(bytes, 0, bytes.Length); } } }
// // PlaylistSource.cs // // Authors: // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Data.Sqlite; using Hyena.Collections; using Banshee.Base; using Banshee.ServiceStack; using Banshee.Database; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; namespace Banshee.Playlist { public class PlaylistSource : AbstractPlaylistSource, IUnmapableSource { private static HyenaSqliteCommand add_track_range_command; private static HyenaSqliteCommand add_track_command; private static HyenaSqliteCommand remove_track_range_command; private static string add_track_range_from_joined_model_sql; private static string generic_name = Catalog.GetString ("Playlist"); protected override string SourceTable { get { return "CorePlaylists"; } } protected override string SourcePrimaryKey { get { return "PlaylistID"; } } protected override string TrackJoinTable { get { return "CorePlaylistEntries"; } } protected long MaxViewOrder { get { return ServiceManager.DbConnection.Query<long> ( "SELECT MAX(ViewOrder) + 1 FROM CorePlaylistEntries WHERE PlaylistID = ?", DbId); } } static PlaylistSource () { add_track_range_command = new HyenaSqliteCommand (@" INSERT INTO CorePlaylistEntries (EntryID, PlaylistID, TrackID, ViewOrder) SELECT null, ?, ItemID, OrderId + ? FROM CoreCache WHERE ModelID = ? LIMIT ?, ?" ); add_track_command = new HyenaSqliteCommand (@" INSERT INTO CorePlaylistEntries (EntryID, PlaylistID, TrackID, ViewOrder) VALUES (null, ?, ?, ?)" ); add_track_range_from_joined_model_sql = @" INSERT INTO CorePlaylistEntries (EntryID, PlaylistID, TrackID, ViewOrder) SELECT null, ?, TrackID, OrderId + ? FROM CoreCache c INNER JOIN {0} e ON c.ItemID = e.{1} WHERE ModelID = ? LIMIT ?, ?"; remove_track_range_command = new HyenaSqliteCommand (@" DELETE FROM CorePlaylistEntries WHERE PlaylistID = ? AND EntryID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ? ORDER BY OrderID LIMIT ?, ?)" ); } #region Constructors public PlaylistSource (string name, PrimarySource parent) : base (generic_name, name, parent) { SetProperties (); } protected PlaylistSource (string name, long dbid, PrimarySource parent) : this (name, dbid, -1, 0, parent, 0, false) { } protected PlaylistSource (string name, long dbid, int sortColumn, int sortType, PrimarySource parent, int count, bool is_temp) : base (generic_name, name, dbid, sortColumn, sortType, parent, is_temp) { SetProperties (); SavedCount = count; } #endregion private void SetProperties () { Properties.SetString ("Icon.Name", "source-playlist"); Properties.SetString ("RemoveSelectedTracksActionLabel", Catalog.GetString ("Remove From Playlist")); Properties.SetString ("RemovePlayingTrackActionLabel", Catalog.GetString ("Remove From Library")); Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Delete Playlist")); } #region Source Overrides public override bool AcceptsInputFromSource (Source source) { return base.AcceptsInputFromSource (source) && ( source == Parent || (source.Parent == Parent || Parent == null) // This is commented out because we don't support (yet?) DnD from Play Queue to a playlist //(source.Parent == Parent || Parent == null || (source.Parent == null && !(source is PrimarySource))) ); } public override SourceMergeType SupportedMergeTypes { get { return SourceMergeType.All; } } #endregion #region AbstractPlaylist overrides protected override void AfterInitialized () { base.AfterInitialized (); if (PrimarySource != null) { PrimarySource.TracksChanged += HandleTracksChanged; PrimarySource.TracksDeleted += HandleTracksDeleted; } TrackModel.CanReorder = true; } protected override void Update () { ServiceManager.DbConnection.Execute (new HyenaSqliteCommand ( String.Format ( @"UPDATE {0} SET Name = ?, SortColumn = ?, SortType = ?, CachedCount = ?, IsTemporary = ? WHERE PlaylistID = ?", SourceTable ), Name, -1, 0, Count, IsTemporary, dbid )); } protected override void Create () { DbId = ServiceManager.DbConnection.Execute (new HyenaSqliteCommand ( @"INSERT INTO CorePlaylists (PlaylistID, Name, SortColumn, SortType, PrimarySourceID, IsTemporary) VALUES (NULL, ?, ?, ?, ?, ?)", Name, -1, 1, PrimarySourceId, IsTemporary //SortColumn, SortType )); } #endregion #region DatabaseSource overrides // We can add tracks only if our parent can public override bool CanAddTracks { get { DatabaseSource ds = Parent as DatabaseSource; return ds != null ? ds.CanAddTracks : base.CanAddTracks; } } // We can remove tracks only if our parent can public override bool CanRemoveTracks { get { return (Parent is PrimarySource) ? !(Parent as PrimarySource).PlaylistsReadOnly : true; } } #endregion #region IUnmapableSource Implementation public virtual bool Unmap () { if (DbId != null) { ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@" BEGIN TRANSACTION; DELETE FROM CorePlaylists WHERE PlaylistID = ?; DELETE FROM CorePlaylistEntries WHERE PlaylistID = ?; COMMIT TRANSACTION", DbId, DbId )); } ThreadAssist.ProxyToMain (Remove); return true; } #endregion protected void AddTrack (long track_id) { ServiceManager.DbConnection.Execute (add_track_command, DbId, track_id, MaxViewOrder); OnTracksAdded (); } public override void AddTrack (DatabaseTrackInfo track) { AddTrack (track.TrackId); } public override bool AddSelectedTracks (Source source, Selection selection) { if (Parent == null || source == Parent || source.Parent == Parent) { return base.AddSelectedTracks (source, selection); } else { // Adding from a different primary source, so add to our primary source first //PrimarySource primary = Parent as PrimarySource; //primary.AddSelectedTracks (model); // then add to us //Log.Information ("Note: Feature Not Implemented", String.Format ("In this alpha release, you can only add tracks to {0} from {1} or its playlists.", Name, Parent.Name), true); } return false; } public virtual void ReorderSelectedTracks (int drop_row) { if (TrackModel.Selection.Count == 0 || TrackModel.Selection.AllSelected) { return; } TrackInfo track = TrackModel[drop_row]; long order = track == null ? ServiceManager.DbConnection.Query<long> ("SELECT MAX(ViewOrder) + 1 FROM CorePlaylistEntries WHERE PlaylistID = ?", DbId) : ServiceManager.DbConnection.Query<long> ("SELECT ViewOrder FROM CorePlaylistEntries WHERE PlaylistID = ? AND EntryID = ?", DbId, Convert.ToInt64 (track.CacheEntryId)); // Make room for our new items if (track != null) { ServiceManager.DbConnection.Execute ("UPDATE CorePlaylistEntries SET ViewOrder = ViewOrder + ? WHERE PlaylistID = ? AND ViewOrder >= ?", TrackModel.Selection.Count, DbId, order ); } HyenaSqliteCommand update_command = new HyenaSqliteCommand (String.Format ("UPDATE CorePlaylistEntries SET ViewOrder = ? WHERE PlaylistID = {0} AND EntryID = ?", DbId)); HyenaSqliteCommand select_command = new HyenaSqliteCommand (String.Format ("SELECT ItemID FROM CoreCache WHERE ModelID = {0} LIMIT ?, ?", DatabaseTrackModel.CacheId)); // Reorder the selected items ServiceManager.DbConnection.BeginTransaction (); foreach (RangeCollection.Range range in TrackModel.Selection.Ranges) { foreach (long entry_id in ServiceManager.DbConnection.QueryEnumerable<long> (select_command, range.Start, range.Count)) { ServiceManager.DbConnection.Execute (update_command, order++, entry_id); } } ServiceManager.DbConnection.CommitTransaction (); Reload (); } DatabaseTrackListModel last_add_range_from_model; HyenaSqliteCommand last_add_range_command = null; protected override void AddTrackRange (DatabaseTrackListModel from, RangeCollection.Range range) { last_add_range_command = (!from.CachesJoinTableEntries) ? add_track_range_command : from == last_add_range_from_model ? last_add_range_command : new HyenaSqliteCommand (String.Format (add_track_range_from_joined_model_sql, from.JoinTable, from.JoinPrimaryKey)); long first_order_id = ServiceManager.DbConnection.Query<long> ("SELECT OrderID FROM CoreCache WHERE ModelID = ? LIMIT 1 OFFSET ?", from.CacheId, range.Start); ServiceManager.DbConnection.Execute (last_add_range_command, DbId, MaxViewOrder - first_order_id, from.CacheId, range.Start, range.Count); last_add_range_from_model = from; } protected override void RemoveTrackRange (DatabaseTrackListModel from, RangeCollection.Range range) { ServiceManager.DbConnection.Execute (remove_track_range_command, DbId, from.CacheId, range.Start, range.Count); } protected override void HandleTracksChanged (Source sender, TrackEventArgs args) { if (args.When > last_updated) { last_updated = args.When; // Playlists do not need to reload if only certain columns are changed if (NeedsReloadWhenFieldsChanged (args.ChangedFields)) { // TODO Optimization: playlists only need to reload if one of their tracks was updated //if (ServiceManager.DbConnection.Query<int> (count_updated_command, last_updated) > 0) { Reload (); //} } else { InvalidateCaches (); } } } protected override void HandleTracksDeleted (Source sender, TrackEventArgs args) { if (args.When > last_removed) { last_removed = args.When; Reload (); /*if (ServiceManager.DbConnection.Query<int> (count_removed_command, last_removed) > 0) { //ServiceManager.DbConnection.Execute ("DELETE FROM CoreCache WHERE ModelID = ? AND ItemID IN (SELECT EntryID FROM CorePlaylistEntries WHERE PlaylistID = ? AND TrackID IN (TrackID FROM CoreRemovedTracks))"); ServiceManager.DbConnection.Execute ("DELETE FROM CorePlaylistEntries WHERE TrackID IN (SELECT TrackID FROM CoreRemovedTracks)"); //track_model.UpdateAggregates (); //OnUpdated (); }*/ } } public static IEnumerable<PlaylistSource> LoadAll (PrimarySource parent) { ClearTemporary (); using (HyenaDataReader reader = new HyenaDataReader (ServiceManager.DbConnection.Query ( @"SELECT PlaylistID, Name, SortColumn, SortType, PrimarySourceID, CachedCount, IsTemporary FROM CorePlaylists WHERE Special = 0 AND PrimarySourceID = ?", parent.DbId))) { while (reader.Read ()) { yield return new PlaylistSource ( reader.Get<string> (1), reader.Get<long> (0), reader.Get<int> (2), reader.Get<int> (3), parent, reader.Get<int> (5), reader.Get<bool> (6) ); } } } private static void ClearTemporary () { ServiceManager.DbConnection.BeginTransaction (); ServiceManager.DbConnection.Execute (@" DELETE FROM CorePlaylistEntries WHERE PlaylistID IN (SELECT PlaylistID FROM CorePlaylists WHERE IsTemporary = 1); DELETE FROM CorePlaylists WHERE IsTemporary = 1;" ); ServiceManager.DbConnection.CommitTransaction (); } public static void ClearTemporary (PrimarySource parent) { if (parent != null) { ServiceManager.DbConnection.BeginTransaction (); ServiceManager.DbConnection.Execute (@" DELETE FROM CorePlaylistEntries WHERE PlaylistID IN (SELECT PlaylistID FROM CorePlaylists WHERE PrimarySourceID = ? AND IsTemporary = 1); DELETE FROM CorePlaylists WHERE PrimarySourceID = ? AND IsTemporary = 1;", parent.DbId, parent.DbId ); ServiceManager.DbConnection.CommitTransaction (); } } private static long GetPlaylistId (string name) { return ServiceManager.DbConnection.Query<long> ( "SELECT PlaylistID FROM Playlists WHERE Name = ? LIMIT 1", name ); } private static bool PlaylistExists (string name) { return GetPlaylistId (name) > 0; } public static string CreateUniqueName () { return NamingUtil.PostfixDuplicate (Catalog.GetString ("New Playlist"), PlaylistExists); } public static string CreateUniqueName (IEnumerable tracks) { return NamingUtil.PostfixDuplicate (NamingUtil.GenerateTrackCollectionName ( tracks, Catalog.GetString ("New Playlist")), PlaylistExists); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ImplicitInstance] [ForceDevirtualization] public abstract class TypeSystemManager { class EmptyManager : TypeSystemManager { [NoInline] public override Object AllocateObject(TS.VTable vTable) { return null; } [NoInline] public override Object AllocateReferenceCountingObject(TS.VTable vTable) { return null; } [NoInline] public override Object AllocateObjectWithExtensions(TS.VTable vTable) { return null; } [NoInline] public override Array AllocateArray(TS.VTable vTable, uint length) { return null; } [NoInline] public override Array AllocateReferenceCountingArray(TS.VTable vTable, uint length) { return null; } [NoInline] public override Array AllocateArrayNoClear(TS.VTable vTable, uint length) { return null; } [NoInline] public override String AllocateString(TS.VTable vTable, int length) { return null; } [NoInline] public override String AllocateReferenceCountingString(TS.VTable vTable, int length) { return null; } } // // Helper Methods // public virtual void InitializeTypeSystemManager() { InvokeStaticConstructors(); } [Inline] [TS.DisableAutomaticReferenceCounting] public object InitializeObject(UIntPtr memory, TS.VTable vTable, bool referenceCounting) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader(memory); oh.VirtualTable = vTable; if (referenceCounting) { oh.MultiUseWord = (int)((1 << ObjectHeader.ReferenceCountShift) | (int)ObjectHeader.GarbageCollectorFlags.NormalObject | (int)ObjectHeader.GarbageCollectorFlags.Unmarked); #if REFCOUNT_STAT ObjectHeader.s_RefCountedObjectsAllocated++; #endif #if DEBUG_REFCOUNT BugCheck.Log( "InitRC (0x%x), new count = 1 +", (int)oh.ToPointer( ) ); #endif } else { oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked); } return oh.Pack(); } [Inline] [TS.DisableAutomaticReferenceCounting] public object InitializeObjectWithExtensions(UIntPtr memory, TS.VTable vTable) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader(memory); oh.VirtualTable = vTable; oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked); return oh.Pack(); } [Inline] [TS.DisableAutomaticReferenceCounting] public Array InitializeArray(UIntPtr memory, TS.VTable vTable, uint length, bool referenceCounting) { object obj = InitializeObject(memory, vTable, referenceCounting); ArrayImpl array = ArrayImpl.CastAsArray(obj); array.m_numElements = length; return array.CastThisAsArray(); } [Inline] [TS.DisableAutomaticReferenceCounting] public String InitializeString(UIntPtr memory, TS.VTable vTable, int length, bool referenceCounting) { object obj = InitializeObject(memory, vTable, referenceCounting); StringImpl str = StringImpl.CastAsString(obj); str.m_arrayLength = length; return str.CastThisAsString(); } [TS.WellKnownMethod("TypeSystemManager_AllocateObject")] [TS.DisableAutomaticReferenceCounting] public abstract Object AllocateObject(TS.VTable vTable); [TS.WellKnownMethod("TypeSystemManager_AllocateReferenceCountingObject")] [TS.DisableAutomaticReferenceCounting] public abstract Object AllocateReferenceCountingObject(TS.VTable vTable); [TS.WellKnownMethod("TypeSystemManager_AllocateObjectWithExtensions")] [TS.DisableAutomaticReferenceCounting] public abstract Object AllocateObjectWithExtensions(TS.VTable vTable); [TS.WellKnownMethod("TypeSystemManager_AllocateArray")] [TS.DisableAutomaticReferenceCounting] public abstract Array AllocateArray(TS.VTable vTable, uint length); [TS.WellKnownMethod("TypeSystemManager_AllocateReferenceCountingArray")] [TS.DisableAutomaticReferenceCounting] public abstract Array AllocateReferenceCountingArray(TS.VTable vTable, uint length); [TS.WellKnownMethod("TypeSystemManager_AllocateArrayNoClear")] [TS.DisableAutomaticReferenceCounting] public abstract Array AllocateArrayNoClear(TS.VTable vTable, uint length); [TS.WellKnownMethod("TypeSystemManager_AllocateString")] [TS.DisableAutomaticReferenceCounting] public abstract String AllocateString(TS.VTable vTable, int length); [TS.DisableAutomaticReferenceCounting] public abstract String AllocateReferenceCountingString(TS.VTable vTable, int length); //--// [Inline] public static T AtomicAllocator<T>(ref T obj) where T : class, new() { if (obj == null) { return AtomicAllocatorSlow(ref obj); } return obj; } [NoInline] private static T AtomicAllocatorSlow<T>(ref T obj) where T : class, new() { T newObj = new T(); System.Threading.Interlocked.CompareExchange(ref obj, newObj, default(T)); return obj; } //--// public static System.Reflection.MethodInfo CodePointerToMethodInfo(TS.CodePointer ptr) { throw new NotImplementedException(); } //--// [NoInline] [TS.WellKnownMethod("TypeSystemManager_InvokeStaticConstructors")] private void InvokeStaticConstructors() { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to inject calls to the static constructors that are reachable. // This is the empty vessel for those calls. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } [TS.WellKnownMethod("TypeSystemManager_CastToType")] public static object CastToType(object obj, TS.VTable expected) { if (obj != null) { obj = CastToTypeNoThrow(obj, expected); if (obj == null) { throw new InvalidCastException(); } } return obj; } [TS.WellKnownMethod("TypeSystemManager_CastToTypeNoThrow")] public static object CastToTypeNoThrow(object obj, TS.VTable expected) { if (obj != null) { TS.VTable got = TS.VTable.Get(obj); if (expected.CanBeAssignedFrom(got) == false) { return null; } } return obj; } //--// [TS.WellKnownMethod("TypeSystemManager_CastToSealedType")] public static object CastToSealedType(object obj, TS.VTable expected) { if (obj != null) { obj = CastToSealedTypeNoThrow(obj, expected); if (obj == null) { throw new InvalidCastException(); } } return obj; } [TS.WellKnownMethod("TypeSystemManager_CastToSealedTypeNoThrow")] public static object CastToSealedTypeNoThrow(object obj, TS.VTable expected) { if (obj != null) { TS.VTable got = TS.VTable.Get(obj); if (got != expected) { return null; } } return obj; } //--// [TS.WellKnownMethod("TypeSystemManager_CastToInterface")] public static object CastToInterface(object obj, TS.VTable expected) { if (obj != null) { obj = CastToInterfaceNoThrow(obj, expected); if (obj == null) { throw new InvalidCastException(); } } return obj; } [TS.WellKnownMethod("TypeSystemManager_CastToInterfaceNoThrow")] public static object CastToInterfaceNoThrow(object obj, TS.VTable expected) { if (obj != null) { TS.VTable got = TS.VTable.Get(obj); if (got.ImplementsInterface(expected)) { return obj; } } return null; } //--// [NoReturn] [NoInline] [TS.WellKnownMethod("TypeSystemManager_Throw")] public virtual void Throw(Exception obj) { ThreadImpl.CurrentThread.CurrentException = obj; UIntPtr exception = Unwind.LLOS_AllocateException(obj, Unwind.ExceptionClass); Unwind.LLOS_Unwind_RaiseException(exception); } [NoReturn] [NoInline] [TS.WellKnownMethod("TypeSystemManager_Rethrow")] public virtual void Rethrow() { Throw(ThreadImpl.CurrentThread.CurrentException); } // // Access Methods // public static extern TypeSystemManager Instance { [TS.WellKnownMethod("TypeSystemManager_get_Instance")] [SingletonFactory(Fallback = typeof(EmptyManager))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } }
using UnityEngine; using System.Collections; [System.Serializable] public class CutsceneTrackItem { #region Constants public enum DragLocation { None, Left_Handle, Center, Right_Handle, } const float NonVerboseLength = 10; public static Color SelectedColor = Color.yellow;//new Color(236f / 255f, 219f / 255f, 50f / 255f); public static Color NotSelectedColor = Color.red;//new Color(215f / 255f, 47f / 255f, 100f / 255f); public static Color LockedColor = new Color(169f / 255f, 187f / 255f, 196f / 255f); #endregion #region Variables public string Name = ""; public string EventType; public float StartTime; public float Length = 1; [HideInInspector] public bool FireAndForget = true; [HideInInspector] public bool LengthRepresented = false; [HideInInspector] public Rect GuiPosition = new Rect(); [HideInInspector] public Rect LeftHandle = new Rect(); [HideInInspector] public Rect RightHandle = new Rect(); [HideInInspector] public Color GuiColor = Color.white; [HideInInspector] public bool Hidden; [HideInInspector] public bool Enabled = true; [HideInInspector] public string m_UniqueId = ""; [HideInInspector] public bool Locked; [HideInInspector] public bool Selected; [HideInInspector] public bool ReadOnly; // allows developers to comment and document events. This text is displayed in the MM window under the notes section [HideInInspector] public string Notes = ""; #endregion #region Properties public string UniqueId { get { return m_UniqueId; } } public float EndTime { get { return StartTime + Length; } } #endregion #region Functions public CutsceneTrackItem() { } public CutsceneTrackItem(string uniqueId) { m_UniqueId = uniqueId; } public CutsceneTrackItem(Rect guiPosition, string uniqueId) { m_UniqueId = uniqueId; GuiPosition = guiPosition; } public CutsceneTrackItem(string uniqueId, string name, float startTime, float length, float yPos, float height, bool lengthRepresented, Color color) { m_UniqueId = uniqueId; Name = name; StartTime = startTime; Length = length; GuiPosition.y = yPos; GuiPosition.height = height; LengthRepresented = lengthRepresented; GuiColor = color; } /// <summary> /// Maintains the same relative handle positions when TrackItems are moved around /// </summary> /// <param name="distanceFromBorder"></param> public void UpdateHandlePositions(float distanceFromBorder) { LeftHandle.Set(GuiPosition.x + distanceFromBorder, GuiPosition.y, 10, GuiPosition.height); RightHandle.Set(GuiPosition.x + GuiPosition.width - distanceFromBorder - 10, GuiPosition.y, 10, GuiPosition.height); } /// <summary> /// Locks or unlocks the TrackItem. Locked items can't be moved /// </summary> /// <param name="locked"></param> public void SetLocked(bool locked) { Locked = locked; if (!Selected) { SetColor(Locked ? LockedColor : NotSelectedColor); } } /// <summary> /// Enables or disables the TrackItem. Disables items aren't invoked when asked to be fired /// </summary> /// <param name="enabled"></param> public void SetEnabled(bool enabled) { Enabled = enabled; GuiColor.a = Enabled ? 1 : 0.5f; } public void SetReadOnly(bool readOnly) { ReadOnly = readOnly; SetLocked(true); } public void SetSelected(bool selected) { Selected = selected; if (selected) { SetColor(SelectedColor); } else { SetColor(Locked ? LockedColor : NotSelectedColor); } } protected void SetColor(Color col) { GuiColor = col; GuiColor.a = Enabled ? 1 : 0.5f; } /// <summary> /// Returns the DragLocation type based on what area of the TrackItem rect /// contains the provided position /// </summary> /// <param name="position"></param> /// <returns></returns> public DragLocation GetDragStateFromPosition(Vector2 position) { DragLocation retVal = DragLocation.None; if (LeftHandle.Contains(position)) { retVal = DragLocation.Left_Handle; } else if (RightHandle.Contains(position)) { retVal = DragLocation.Right_Handle; } else if (retVal == DragLocation.None && GuiPosition.Contains(position)) { retVal = DragLocation.Center; } return retVal; } /// <summary> /// Returns the length in pixels of the given text. This function can only be called /// in onGUI /// </summary> /// <param name="content"></param> /// <param name="text"></param> /// <returns></returns> public static float CalculateTextLength(GUIContent content, string text) { content.text = text; return GUI.skin.label.CalcSize(content).x + 8; } public bool Draw(bool verboseText, GUIContent content) { if (Hidden) { return false; } bool buttonPressed = false; GUI.color = GuiColor; if (FireAndForget) { content.tooltip = string.Format("{0} {1}", Name, StartTime.ToString("f2")); if (!LengthRepresented) { content.text = verboseText ? Name : ""; GuiPosition.width = verboseText ? CalculateTextLength(content, Name) : NonVerboseLength; } else { content.text = Name; } buttonPressed = GUI.Button(GuiPosition, content); } else { // timed event content.text = Name; content.tooltip = string.Format("{0} {1}", Name, StartTime.ToString("f2")); UpdateHandlePositions(0); buttonPressed = GUI.Button(GuiPosition, content); GUI.color = Color.cyan; GUI.Button(LeftHandle, ""); GUI.Button(RightHandle, ""); } return buttonPressed; } #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine { public class DiagnosticAnalyzerDriverTests { [Fact] public async Task DiagnosticAnalyzerDriverAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers or named types with primary constructors. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType); var syntaxKindsMissing = new HashSet<SyntaxKind>(); // AllInOneCSharpCode has no deconstruction or declaration expression syntaxKindsMissing.Add(SyntaxKind.VariableDeconstructionDeclarator); syntaxKindsMissing.Add(SyntaxKind.DeclarationExpression); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); AccessSupportedDiagnostics(analyzer); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length)); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(syntaxKindsMissing); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true); } } [Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")] public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() { var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" }; var source = @" [System.Obsolete] class C { int P { get; set; } delegate void A(); delegate string F(); } "; var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineAnalyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); foreach (var method in methodNames) { Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer }); foreach (var method in methodNames) { Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } } [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var source = TestResource.AllInOneCSharpCode; using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer => await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length), logAnalyzerExceptionAsDiagnostics: true)); } } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1() { var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); AccessSupportedDiagnostics(analyzer); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2() { var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); var exceptions = new List<Exception>(); try { AccessSupportedDiagnostics(analyzer); } catch (Exception e) { exceptions.Add(e); } Assert.True(exceptions.Count == 0); } [Fact] public async Task AnalyzerOptionsArePassedToAllAnalyzers() { using (var workspace = await TestWorkspace.CreateCSharpAsync(TestResource.AllInOneCSharpCode, TestOptions.Regular)) { var currentProject = workspace.CurrentSolution.Projects.Single(); var additionalDocId = DocumentId.CreateNewId(currentProject.Id); var newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text")); currentProject = newSln.Projects.Single(); var additionalDocument = currentProject.GetAdditionalDocument(additionalDocId); AdditionalText additionalStream = new AdditionalTextDocument(additionalDocument.State); AnalyzerOptions options = new AnalyzerOptions(ImmutableArray.Create(additionalStream)); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options); var sourceDocument = currentProject.Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, sourceDocument, new Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length)); analyzer.VerifyAnalyzerOptions(); } } private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer) { var diagnosticService = new TestDiagnosticAnalyzerService(LanguageNames.CSharp, analyzer); diagnosticService.GetDiagnosticDescriptors(projectOpt: null); } private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct { public bool RunInProcess => true; public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SyntaxAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis; } } [Fact] public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer() { var source = @"x"; var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic"); Assert.Equal(1, diagnosticsFromAnalyzer.Count()); } } private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer { private const string ID = "SyntaxDiagnostic"; private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor = new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_syntaxDiagnosticDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree); } private class SyntaxTreeAnalyzer { public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation())); } } } [Fact] public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode() { var source = @" using System; class C { void F(int x = 0) { Console.WriteLine(0); } } "; var analyzer = new CodeBlockAnalyzerFactory(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(2, diagnosticsFromAnalyzer.Count()); } source = @" using System; class C { void F(int x = 0, int y = 1, int z = 2) { Console.WriteLine(0); } } "; using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(4, diagnosticsFromAnalyzer.Count()); } } private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock); } public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context) { var blockAnalyzer = new CodeBlockAnalyzer(); context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock); context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray()); } private class CodeBlockAnalyzer { public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause); } } public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { } public void AnalyzeNode(SyntaxNodeAnalysisContext context) { // Ensure only executable nodes are analyzed. Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind()); context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation())); } } } } }
// // Copyright (C) Microsoft. All rights reserved. // namespace Microsoft.PowerShell.Commands { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands.Internal.Format; using System.IO; internal class TableView { private MshExpressionFactory _expressionFactory; private TypeInfoDataBase _typeInfoDatabase; private FormatErrorManager _errorManager; internal void Initialize(MshExpressionFactory expressionFactory, TypeInfoDataBase db) { _expressionFactory = expressionFactory; _typeInfoDatabase = db; // Initialize Format Error Manager. FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); formatErrorPolicy.ShowErrorsAsMessages = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; formatErrorPolicy.ShowErrorsInFormattedOutput = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; _errorManager = new FormatErrorManager(formatErrorPolicy); } internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet) { HeaderInfo headerInfo = new HeaderInfo(); // This verification is needed because the database returns "LastWriteTime" value for file system objects // as strings and it is used to detect this situation and use the actual field value. bool fileSystemObject = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject); if (tableBody != null) // If the tableBody is null, the TableControlBody info was not put into the database. { // Generate HeaderInfo from the type information database. List<TableRowItemDefinition> activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, input); int col = 0; foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList) { ColumnInfo columnInfo = null; string displayName = null; TableColumnHeaderDefinition colHeader = null; // Retrieve a matching TableColumnHeaderDefinition if (col < tableBody.header.columnHeaderDefinitionList.Count) colHeader = tableBody.header.columnHeaderDefinitionList[col]; if (colHeader != null && colHeader.label != null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label); } FormatToken token = null; if (rowItem.formatTokenList.Count > 0) { token = rowItem.formatTokenList[0]; } if (token != null) { FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { if (displayName == null) { // Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName = fpt.expression.expressionValue; } if (fpt.expression.isScriptBlock) { MshExpression ex = _expressionFactory.CreateFromExpressionToken(fpt.expression); // Using the displayName as a propertyName for a stale PSObject. const string LastWriteTimePropertyName = "LastWriteTime"; // For FileSystem objects "LastWriteTime" property value should be used although the database indicates that a script should be executed to get the value. if (fileSystemObject && displayName.Equals(LastWriteTimePropertyName, StringComparison.OrdinalIgnoreCase)) { columnInfo = new OriginalColumnInfo(displayName, displayName, LastWriteTimePropertyName, parentCmdlet); } else { columnInfo = new ExpressionColumnInfo(displayName, displayName, ex); } } else { columnInfo = new OriginalColumnInfo(fpt.expression.expressionValue, displayName, fpt.expression.expressionValue, parentCmdlet); } } else { TextToken tt = token as TextToken; if (tt != null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); } } } if (columnInfo != null) { headerInfo.AddColumn(columnInfo); } col++; } } return headerInfo; } internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parentCmdlet) { HeaderInfo headerInfo = new HeaderInfo(); List<MshResolvedExpressionParameterAssociation> activeAssociationList; // Get properties from the default property set of the object activeAssociationList = AssociationManager.ExpandDefaultPropertySet(input, _expressionFactory); if (activeAssociationList.Count > 0) { // we got a valid set of properties from the default property set..add computername for // remoteobjects (if available) if (PSObjectHelper.ShouldShowComputerNameProperty(input)) { activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, new MshExpression(RemotingConstants.ComputerNameNoteProperty))); } } else { // We failed to get anything from the default property set activeAssociationList = AssociationManager.ExpandAll(input); if (activeAssociationList.Count > 0) { // Remove PSComputerName and PSShowComputerName from the display as needed. AssociationManager.HandleComputerNameProperties(input, activeAssociationList); FilterActiveAssociationList(activeAssociationList); } else { // We were unable to retrieve any properties, so we leave an empty list activeAssociationList = new List<MshResolvedExpressionParameterAssociation>(); } } for (int k = 0; k < activeAssociationList.Count; k++) { string propertyName = null; MshResolvedExpressionParameterAssociation association = activeAssociationList[k]; // set the label of the column if (association.OriginatingParameter != null) { object key = association.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (key != AutomationNull.Value) propertyName = (string)key; } if (propertyName == null) { propertyName = association.ResolvedExpression.ToString(); } ColumnInfo columnInfo = new OriginalColumnInfo(propertyName, propertyName, propertyName, parentCmdlet); headerInfo.AddColumn(columnInfo); } return headerInfo; } /// <summary> /// Method to filter resolved expressions as per table view needs. /// For v1.0, table view supports only 10 properties. /// /// This method filters and updates "activeAssociationList" instance property. /// </summary> /// <returns>None.</returns> /// <remarks>This method updates "activeAssociationList" instance property.</remarks> private void FilterActiveAssociationList(List<MshResolvedExpressionParameterAssociation> activeAssociationList) { // we got a valid set of properties from the default property set // make sure we do not have too many properties // NOTE: this is an arbitrary number, chosen to be a sensitive default int nMax = 256; if (activeAssociationList.Count > nMax) { List<MshResolvedExpressionParameterAssociation> tmp = new List<MshResolvedExpressionParameterAssociation>(activeAssociationList); activeAssociationList.Clear(); for (int k = 0; k < nMax; k++) activeAssociationList.Add(tmp[k]); } return; } private List<TableRowItemDefinition> GetActiveTableRowDefinition(TableControlBody tableBody, PSObject so) { if (tableBody.optionalDefinitionList.Count == 0) { // we do not have any override, use default return tableBody.defaultDefinition.rowItemDefinitionList; } // see if we have an override that matches TableRowDefinition matchingRowDefinition = null; var typeNames = so.InternalTypeNames; TypeMatch match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typeNames); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { matchingRowDefinition = x; break; } } if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } if (matchingRowDefinition == null) { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typesWithoutPrefix); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { matchingRowDefinition = x; break; } } if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } } } if (matchingRowDefinition == null) { // no matching override, use default return tableBody.defaultDefinition.rowItemDefinitionList; } // we have an override, we need to compute the merge of the active cells List<TableRowItemDefinition> activeRowItemDefinitionList = new List<TableRowItemDefinition>(); int col = 0; foreach (TableRowItemDefinition rowItem in matchingRowDefinition.rowItemDefinitionList) { // Check if the row is an override or not if (rowItem.formatTokenList.Count == 0) { // It's a place holder, use the default activeRowItemDefinitionList.Add(tableBody.defaultDefinition.rowItemDefinitionList[col]); } else { // Use the override activeRowItemDefinitionList.Add(rowItem); } col++; } return activeRowItemDefinitionList; } } }
///<summary> ///HTTP Method: POST ///Access: Private public string VerifyAge( ) { RestRequest request = new RestRequest($"/Tokens/VerifyAge/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string EquipItem( ) { RestRequest request = new RestRequest($"/Destiny/EquipItem/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string EquipItems( ) { RestRequest request = new RestRequest($"/Destiny/EquipItems/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetAccount( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetAccountSummary( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Summary/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetActivityBlob( ) { RestRequest request = new RestRequest($"/Destiny/Stats/ActivityBlob/{e}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="mode">Game mode to return. Required.</param> ///<param name="count">The number of results to return.</param> ///<param name="page">The current page to return. Starts at 1.</param> ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetActivityHistory( object mode, object count, object page, object definitions ) { RestRequest request = new RestRequest($"/Destiny/Stats/ActivityHistory/{membershipType}/{destinyMembershipId}/{characterId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("mode, mode");request.AddParameter("count, count");request.AddParameter("page, page");request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetAdvisorsForAccount( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Advisors/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetAdvisorsForCharacter( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/Advisors/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetAdvisorsForCharacterV2( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/Advisors/V2/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetAdvisorsForCurrentCharacter( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Character/{characterId}/Advisors/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetAllItemsSummary( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Items/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetAllVendorsForCurrentCharacter( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Character/{characterId}/Vendors/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetBondAdvisors( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Advisors/Bonds/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetCharacter( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/Complete/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetCharacterActivities( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/Activities/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetCharacterInventory( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/Inventory/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetCharacterInventorySummary( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/Inventory/Summary/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetCharacterProgression( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/Progression/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetCharacterSummary( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="modes"></param> ///<param name="statid"></param> ///<param name="maxtop"></param> ///</summary> public string GetClanLeaderboards( object modes, object statid, object maxtop ) { RestRequest request = new RestRequest($"/Destiny/Stats/ClanLeaderboards/{param1}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("modes, modes");request.AddParameter("statid, statid");request.AddParameter("maxtop, maxtop"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetDestinyAggregateActivityStats( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Stats/AggregateActivityStats/{membershipType}/{destinyMembershipId}/{characterId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="tpage"></param> ///<param name="count">The number of results to return. Default is 10.</param> ///<param name="name">Filter by name.</param> ///<param name="order">Order results.</param> ///<param name="orderstathash"></param> ///<param name="direction"></param> ///<param name="rarity">Filter by item rarity.</param> ///<param name="step"></param> ///<param name="categories"></param> ///<param name="weaponPerformance"></param> ///<param name="impactEffects"></param> ///<param name="guardianAttributes"></param> ///<param name="lightAbilities"></param> ///<param name="damageTypes">Filter by damage type.</param> ///<param name="matchrandomsteps"></param> ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///<param name="sourcecat"></param> ///<param name="sourcehash"></param> ///</summary> public string GetDestinyExplorerItems( object tpage, object count, object name, object order, object orderstathash, object direction, object rarity, object step, object categories, object weaponPerformance, object impactEffects, object guardianAttributes, object lightAbilities, object damageTypes, object matchrandomsteps, object definitions, object sourcecat, object sourcehash ) { RestRequest request = new RestRequest($"/Destiny/Explorer/Items/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("tpage, tpage");request.AddParameter("count, count");request.AddParameter("name, name");request.AddParameter("order, order");request.AddParameter("orderstathash, orderstathash");request.AddParameter("direction, direction");request.AddParameter("rarity, rarity");request.AddParameter("step, step");request.AddParameter("categories, categories");request.AddParameter("weaponPerformance, weaponPerformance");request.AddParameter("impactEffects, impactEffects");request.AddParameter("guardianAttributes, guardianAttributes");request.AddParameter("lightAbilities, lightAbilities");request.AddParameter("damageTypes, damageTypes");request.AddParameter("matchrandomsteps, matchrandomsteps");request.AddParameter("definitions, definitions");request.AddParameter("sourcecat, sourcecat");request.AddParameter("sourcehash, sourcehash"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="page">The current page to return. Starts at 1.</param> ///<param name="count">The number of results per page. Default is 10.</param> ///<param name="name">Filter by name.</param> ///<param name="direction"></param> ///<param name="weaponPerformance"></param> ///<param name="impactEffects"></param> ///<param name="guardianAttributes"></param> ///<param name="lightAbilities"></param> ///<param name="damageTypes">Filter by damage type.</param> ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetDestinyExplorerTalentNodeSteps( object page, object count, object name, object direction, object weaponPerformance, object impactEffects, object guardianAttributes, object lightAbilities, object damageTypes, object definitions ) { RestRequest request = new RestRequest($"/Destiny/Explorer/TalentNodeSteps/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("page, page");request.AddParameter("count, count");request.AddParameter("name, name");request.AddParameter("direction, direction");request.AddParameter("weaponPerformance, weaponPerformance");request.AddParameter("impactEffects, impactEffects");request.AddParameter("guardianAttributes, guardianAttributes");request.AddParameter("lightAbilities, lightAbilities");request.AddParameter("damageTypes, damageTypes");request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public public string GetDestinyLiveTileContentItems( ) { RestRequest request = new RestRequest($"/Destiny/LiveTiles/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public public string GetDestinyManifest( ) { RestRequest request = new RestRequest($"/Destiny/Manifest/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///<param name="version"></param> ///</summary> public string GetDestinySingleDefinition( object definitions, object version ) { RestRequest request = new RestRequest($"/Destiny/Manifest/{definitionType}/{definitionId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions");request.AddParameter("version, version"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetExcellenceBadges( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Stats/GetExcellenceBadges/{membershipType}/{destinyMembershipId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///<param name="flavour">Indicates flavour stats should be included with player card data. More testing needed.</param> ///<param name="single">Return data for a single cardId.</param> ///</summary> public string GetGrimoireByMembership( object definitions, object flavour, object single ) { RestRequest request = new RestRequest($"/Destiny/Vanguard/Grimoire/{membershipType}/{destinyMembershipId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions");request.AddParameter("flavour, flavour");request.AddParameter("single, single"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public public string GetGrimoireDefinition( ) { RestRequest request = new RestRequest($"/Destiny/Vanguard/Grimoire/Definition/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="periodType">Indicates a specific period type to return.</param> ///<param name="modes">Game modes to return. Comma separated.</param> ///<param name="groups">Group of stats to include, otherwise only general stats are returned. Comma separated.</param> ///<param name="monthstart">First month to return when monthly stats are requested. Use the format YYYY-MM.</param> ///<param name="monthend">Last month to return when monthly stats are requested. Use the format YYYY-MM.</param> ///<param name="daystart">First day to return when daily stats are requested. Use the format YYYY-MM-DD.</param> ///<param name="dayend">Last day to return when daily stats are requested. Use the format YYYY-MM-DD.</param> ///</summary> public string GetHistoricalStats( object periodType, object modes, object groups, object monthstart, object monthend, object daystart, object dayend ) { RestRequest request = new RestRequest($"/Destiny/Stats/{membershipType}/{destinyMembershipId}/{characterId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("periodType, periodType");request.AddParameter("modes, modes");request.AddParameter("groups, groups");request.AddParameter("monthstart, monthstart");request.AddParameter("monthend, monthend");request.AddParameter("daystart, daystart");request.AddParameter("dayend, dayend"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public public string GetHistoricalStatsDefinition( ) { RestRequest request = new RestRequest($"/Destiny/Stats/Definition/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="groups">Groups of stats to include, otherwise only general stats are returned. Comma separated.</param> ///</summary> public string GetHistoricalStatsForAccount( object groups ) { RestRequest request = new RestRequest($"/Destiny/Stats/Account/{membershipType}/{destinyMembershipId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("groups, groups"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetItemDetail( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Character/{characterId}/Inventory/{itemInstanceId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetItemReferenceDetail( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{param1}/Account/{param2}/Character/{param3}/ItemReference/{param4}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="modes">Game modes to return. Comma separated.</param> ///<param name="statid"></param> ///<param name="maxtop"></param> ///</summary> public string GetLeaderboards( object modes, object statid, object maxtop ) { RestRequest request = new RestRequest($"/Destiny/Stats/Leaderboards/{membershipType}/{destinyMembershipId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("modes, modes");request.AddParameter("statid, statid");request.AddParameter("maxtop, maxtop"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="modes">Game modes to return. Comma separated.</param> ///<param name="statid"></param> ///<param name="maxtop"></param> ///</summary> public string GetLeaderboardsForCharacter( object modes, object statid, object maxtop ) { RestRequest request = new RestRequest($"/Destiny/Stats/Leaderboards/{membershipType}/{destinyMembershipId}/{characterId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("modes, modes");request.AddParameter("statid, statid");request.AddParameter("maxtop, maxtop"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="modes">Game modes to return. Comma separated.</param> ///<param name="code">Unknown, further testing needed.</param> ///</summary> public string GetLeaderboardsForPsn( object modes, object code ) { RestRequest request = new RestRequest($"/Destiny/Stats/LeaderboardsForPsn/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("modes, modes");request.AddParameter("code, code"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="ignorecase">Default is false when not specified. True to cause a caseless search to be used.</param> ///</summary> public string GetMembershipIdByDisplayName( object ignorecase ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Stats/GetMembershipIdByDisplayName/{displayName}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("ignorecase, ignorecase"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///<param name="flavour">Indicates flavour stats should be included with player card data. More testing needed.</param> ///<param name="single">Return data for a single cardId.</param> ///</summary> public string GetMyGrimoire( object definitions, object flavour, object single ) { RestRequest request = new RestRequest($"/Destiny/Vanguard/Grimoire/{membershipType}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions");request.AddParameter("flavour, flavour");request.AddParameter("single, single"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetPostGameCarnageReport( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Stats/PostGameCarnageReport/{activityInstanceId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetPublicAdvisors( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Advisors/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetPublicAdvisorsV2( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Advisors/V2/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetPublicVendor( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Vendors/{vendorId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetPublicVendorWithMetadata( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Vendors/{vendorId}/Metadata/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetPublicXurVendor( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Advisors/Xur/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetRecordBookCompletionStatus( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/RecordBooks/{recordBookHash}/Completion/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetSpecialEventAdvisors( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Events/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetTriumphs( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/Account/{destinyMembershipId}/Triumphs/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetUniqueWeaponHistory( object definitions ) { RestRequest request = new RestRequest($"/Destiny/Stats/UniqueWeapons/{membershipType}/{destinyMembershipId}/{characterId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///<param name="accountId">A valid destinyMembershipId.</param> ///</summary> public string GetVault( object definitions, object accountId ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Vault/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions");request.AddParameter("accountId, accountId"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///<param name="accountId">A valid destinyMembershipId.</param> ///</summary> public string GetVaultSummary( object definitions, object accountId ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Vault/Summary/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions");request.AddParameter("accountId, accountId"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetVendorForCurrentCharacter( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Character/{characterId}/Vendor/{vendorId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetVendorForCurrentCharacterWithMetadata( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Character/{characterId}/Vendor/{vendorId}/Metadata/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetVendorItemDetailForCurrentCharacter( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Character/{characterId}/Vendor/{vendorId}/Item/{itemId}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetVendorItemDetailForCurrentCharacterWithMetadata( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Character/{characterId}/Vendor/{vendorId}/Item/{itemId}/Metadata/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Private ///<param name="definitions">Include definitions in the response. Use while testing.</param> ///</summary> public string GetVendorSummariesForCurrentCharacter( object definitions ) { RestRequest request = new RestRequest($"/Destiny/{membershipType}/MyAccount/Character/{characterId}/Vendors/Summaries/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("definitions, definitions"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: Public public string SearchDestinyPlayer( ) { RestRequest request = new RestRequest($"/Destiny/SearchDestinyPlayer/{membershipType}/{displayName}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string SetItemLockState( ) { RestRequest request = new RestRequest($"/Destiny/SetLockState/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string SetQuestTrackedState( ) { RestRequest request = new RestRequest($"/Destiny/SetQuestTrackedState/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; }
#region License /* * Logger.cs * * The MIT License * * Copyright (c) 2013-2015 sta.blockhead * * 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.Diagnostics; using System.IO; namespace WebSocketSharp { /// <summary> /// Provides a set of methods and properties for logging. /// </summary> /// <remarks> /// <para> /// If you output a log with lower than the value of the <see cref="Logger.Level"/> property, /// it cannot be outputted. /// </para> /// <para> /// The default output action writes a log to the standard output stream and the log file /// if the <see cref="Logger.File"/> property has a valid path to it. /// </para> /// <para> /// If you would like to use the custom output action, you should set /// the <see cref="Logger.Output"/> property to any <c>Action&lt;LogData, string&gt;</c> /// delegate. /// </para> /// </remarks> public class Logger { #region Private Fields private volatile string _file; private volatile LogLevel _level; private Action<LogData, string> _output; private object _sync; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class. /// </summary> /// <remarks> /// This constructor initializes the current logging level with <see cref="LogLevel.Error"/>. /// </remarks> public Logger () : this (LogLevel.Error, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class with /// the specified logging <paramref name="level"/>. /// </summary> /// <param name="level"> /// One of the <see cref="LogLevel"/> enum values. /// </param> public Logger (LogLevel level) : this (level, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class with /// the specified logging <paramref name="level"/>, path to the log <paramref name="file"/>, /// and <paramref name="output"/> action. /// </summary> /// <param name="level"> /// One of the <see cref="LogLevel"/> enum values. /// </param> /// <param name="file"> /// A <see cref="string"/> that represents the path to the log file. /// </param> /// <param name="output"> /// An <c>Action&lt;LogData, string&gt;</c> delegate that references the method(s) used to /// output a log. A <see cref="string"/> parameter passed to this delegate is /// <paramref name="file"/>. /// </param> public Logger (LogLevel level, string file, Action<LogData, string> output) { _level = level; _file = file; _output = output ?? defaultOutput; _sync = new object (); } #endregion #region Public Properties /// <summary> /// Gets or sets the current path to the log file. /// </summary> /// <value> /// A <see cref="string"/> that represents the current path to the log file if any. /// </value> public string File { get { return _file; } set { lock (_sync) { _file = value; Warn ( String.Format ("The current path to the log file has been changed to {0}.", _file)); } } } /// <summary> /// Gets or sets the current logging level. /// </summary> /// <remarks> /// A log with lower than the value of this property cannot be outputted. /// </remarks> /// <value> /// One of the <see cref="LogLevel"/> enum values, specifies the current logging level. /// </value> public LogLevel Level { get { return _level; } set { lock (_sync) { _level = value; Warn (String.Format ("The current logging level has been changed to {0}.", _level)); } } } /// <summary> /// Gets or sets the current output action used to output a log. /// </summary> /// <value> /// <para> /// An <c>Action&lt;LogData, string&gt;</c> delegate that references the method(s) used to /// output a log. A <see cref="string"/> parameter passed to this delegate is the value of /// the <see cref="Logger.File"/> property. /// </para> /// <para> /// If the value to set is <see langword="null"/>, the current output action is changed to /// the default output action. /// </para> /// </value> public Action<LogData, string> Output { get { return _output; } set { lock (_sync) { _output = value ?? defaultOutput; Warn ("The current output action has been changed."); } } } #endregion #region Private Methods private static void defaultOutput (LogData data, string path) { var log = data.ToString (); Console.WriteLine (log); if (path != null && path.Length > 0) writeToFile (log, path); } private void output (string message, LogLevel level) { lock (_sync) { if (_level > level) return; LogData data = null; try { data = new LogData (level, new StackFrame (2, true), message); _output (data, _file); } catch (Exception ex) { data = new LogData (LogLevel.Fatal, new StackFrame (0, true), ex.Message); Console.WriteLine (data.ToString ()); } } } private static void writeToFile (string value, string path) { using (var writer = new StreamWriter (path, true)) using (var syncWriter = TextWriter.Synchronized (writer)) syncWriter.WriteLine (value); } #endregion #region Public Methods /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Debug"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Debug"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Debug (string message) { if (_level > LogLevel.Debug) return; output (message, LogLevel.Debug); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Error"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Error"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Error (string message) { if (_level > LogLevel.Error) return; output (message, LogLevel.Error); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Fatal"/>. /// </summary> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Fatal (string message) { output (message, LogLevel.Fatal); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Info"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Info"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Info (string message) { if (_level > LogLevel.Info) return; output (message, LogLevel.Info); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Trace"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Trace"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Trace (string message) { if (_level > LogLevel.Trace) return; output (message, LogLevel.Trace); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Warn"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Warn"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Warn (string message) { if (_level > LogLevel.Warn) return; output (message, LogLevel.Warn); } #endregion } }
// // Copyright (C) Microsoft. All rights reserved. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Management.Automation; using System.Management.Automation.Remoting; using System.Threading; namespace Microsoft.PowerShell.Commands { /// <summary> /// This cmdlet resumes the jobs that are Job2. Errors are added for each Job that is not Job2. /// </summary> #if !CORECLR [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] [Cmdlet(VerbsLifecycle.Resume, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=210611")] #endif [OutputType(typeof(Job))] public class ResumeJobCommand : JobCmdletBase, IDisposable { #region Parameters /// <summary> /// Specifies the Jobs objects which need to be /// suspended /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JobParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Job[] Job { get { return _jobs; } set { _jobs = value; } } private Job[] _jobs; /// <summary> /// /// </summary> public override String[] Command { get { return null; } } /// <summary> /// Specifies whether to delay returning from the cmdlet until all jobs reach a running state. /// This could take significant time due to workflow throttling. /// </summary> [Parameter(ParameterSetName = ParameterAttribute.AllParameterSets)] public SwitchParameter Wait { get; set; } #endregion Parameters #region Overrides /// <summary> /// Resume the Job. /// </summary> protected override void ProcessRecord() { //List of jobs to resume List<Job> jobsToResume = null; switch (ParameterSetName) { case NameParameterSet: { jobsToResume = FindJobsMatchingByName(true, false, true, false); } break; case InstanceIdParameterSet: { jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false); } break; case SessionIdParameterSet: { jobsToResume = FindJobsMatchingBySessionId(true, false, true, false); } break; case StateParameterSet: { jobsToResume = FindJobsMatchingByState(false); } break; case FilterParameterSet: { jobsToResume = FindJobsMatchingByFilter(false); } break; default: { jobsToResume = CopyJobsToList(_jobs, false, false); } break; } _allJobsToResume.AddRange(jobsToResume); // Blue: 151804 When resuming a single suspended workfllow job, Resume-job cmdlet doesn't wait for the job to be in running state // Setting Wait to true so that this cmdlet will wait for the running job state. if (_allJobsToResume.Count == 1) Wait = true; foreach (Job job in jobsToResume) { var job2 = job as Job2; // If the job is not Job2, the resume operation is not supported. if (job2 == null) { WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); continue; } string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id); if (ShouldProcess(targetString, VerbsLifecycle.Resume)) { _cleanUpActions.Add(job2, HandleResumeJobCompleted); job2.ResumeJobCompleted += HandleResumeJobCompleted; lock (_syncObject) { if (!_pendingJobs.Contains(job2.InstanceId)) { _pendingJobs.Add(job2.InstanceId); } } job2.ResumeJobAsync(); } } } private bool _warnInvalidState = false; private readonly HashSet<Guid> _pendingJobs = new HashSet<Guid>(); private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); private readonly Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>> _cleanUpActions = new Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>>(); private readonly List<ErrorRecord> _errorsToWrite = new List<ErrorRecord>(); private readonly List<Job> _allJobsToResume = new List<Job>(); private readonly object _syncObject = new object(); private bool _needToCheckForWaitingJobs; private void HandleResumeJobCompleted(object sender, AsyncCompletedEventArgs eventArgs) { Job job = sender as Job; if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) { _warnInvalidState = true; } var parentJob = job as ContainerParentJob; if (parentJob != null && parentJob.ExecutionError.Count > 0) { foreach ( var e in parentJob.ExecutionError.Where(e => e.FullyQualifiedErrorId == "ContainerParentJobResumeAsyncError") ) { if (e.Exception is InvalidJobStateException) { // if any errors were invalid job state exceptions, warn the user. // This is to support Get-Job | Resume-Job scenarios when many jobs // are Completed, etc. _warnInvalidState = true; } else { _errorsToWrite.Add(e); } } parentJob.ExecutionError.Clear(); } bool releaseWait = false; lock (_syncObject) { if (_pendingJobs.Contains(job.InstanceId)) { _pendingJobs.Remove(job.InstanceId); } if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) releaseWait = true; } // end processing has been called // set waithandle if this is the last one if (releaseWait) _waitForJobs.Set(); } /// <summary> /// End Processing. /// </summary> protected override void EndProcessing() { bool jobsPending = false; lock (_syncObject) { _needToCheckForWaitingJobs = true; if (_pendingJobs.Count > 0) jobsPending = true; } if (Wait && jobsPending) _waitForJobs.WaitOne(); if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.ResumeJobInvalidJobState); foreach (var e in _errorsToWrite) WriteError(e); foreach (var j in _allJobsToResume) WriteObject(j); base.EndProcessing(); } /// <summary> /// /// </summary> protected override void StopProcessing() { _waitForJobs.Set(); } #endregion Overrides #region Dispose /// <summary> /// /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// /// </summary> /// <param name="disposing"></param> protected void Dispose(bool disposing) { if (!disposing) return; foreach (var pair in _cleanUpActions) { pair.Key.ResumeJobCompleted -= pair.Value; } _waitForJobs.Dispose(); } #endregion Dispose } }
// 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 ExtendToVector256SByte() { var test = new GenericUnaryOpTest__ExtendToVector256SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 GenericUnaryOpTest__ExtendToVector256SByte { private struct TestStruct { public Vector128<SByte> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(GenericUnaryOpTest__ExtendToVector256SByte testClass) { var result = Avx.ExtendToVector256<SByte>(_fld); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable; static GenericUnaryOpTest__ExtendToVector256SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public GenericUnaryOpTest__ExtendToVector256SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.ExtendToVector256<SByte>( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.ExtendToVector256<SByte>( Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.ExtendToVector256<SByte>( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256)) .MakeGenericMethod( new Type[] { typeof(SByte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256)) .MakeGenericMethod( new Type[] { typeof(SByte) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256)) .MakeGenericMethod( new Type[] { typeof(SByte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.ExtendToVector256<SByte>( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = Avx.ExtendToVector256<SByte>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = Avx.ExtendToVector256<SByte>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)); var result = Avx.ExtendToVector256<SByte>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new GenericUnaryOpTest__ExtendToVector256SByte(); var result = Avx.ExtendToVector256<SByte>(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.ExtendToVector256<SByte>(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.ExtendToVector256(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { if (firstOp[0] != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((i < (RetElementCount / 2)) ? firstOp[i] : 0)) { Succeeded = false; break; } } } if (!Succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtendToVector256)}<SByte>(Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.BeatmapListing.Panels { public abstract class BeatmapPanel : OsuClickableContainer, IHasContextMenu { public readonly BeatmapSetInfo SetInfo; private const double hover_transition_time = 400; private const int maximum_difficulty_icons = 10; private Container content; public PreviewTrack Preview => PlayButton.Preview; public IBindable<bool> PreviewPlaying => PlayButton?.Playing; protected abstract PlayButton PlayButton { get; } protected abstract Box PreviewBar { get; } protected virtual bool FadePlayButton => true; protected override Container<Drawable> Content => content; protected Action ViewBeatmap; protected BeatmapPanel(BeatmapSetInfo setInfo) { Debug.Assert(setInfo.OnlineBeatmapSetID != null); SetInfo = setInfo; } private readonly EdgeEffectParameters edgeEffectNormal = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Offset = new Vector2(0f, 1f), Radius = 2f, Colour = Color4.Black.Opacity(0.25f), }; private readonly EdgeEffectParameters edgeEffectHovered = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Offset = new Vector2(0f, 5f), Radius = 10f, Colour = Color4.Black.Opacity(0.3f), }; [BackgroundDependencyLoader(permitNulls: true)] private void load(BeatmapManager beatmaps, OsuColour colours, BeatmapSetOverlay beatmapSetOverlay) { AddInternal(content = new Container { RelativeSizeAxes = Axes.Both, Masking = true, EdgeEffect = edgeEffectNormal, Children = new[] { CreateBackground(), new DownloadProgressBar(SetInfo) { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Depth = -1, }, } }); Action = ViewBeatmap = () => { Debug.Assert(SetInfo.OnlineBeatmapSetID != null); beatmapSetOverlay?.FetchAndShowBeatmapSet(SetInfo.OnlineBeatmapSetID.Value); }; } protected override void Update() { base.Update(); if (PreviewPlaying.Value && Preview != null && Preview.TrackLoaded) { PreviewBar.Width = (float)(Preview.CurrentTime / Preview.Length); } } protected override bool OnHover(HoverEvent e) { content.TweenEdgeEffectTo(edgeEffectHovered, hover_transition_time, Easing.OutQuint); content.MoveToY(-4, hover_transition_time, Easing.OutQuint); if (FadePlayButton) PlayButton.FadeIn(120, Easing.InOutQuint); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { content.TweenEdgeEffectTo(edgeEffectNormal, hover_transition_time, Easing.OutQuint); content.MoveToY(0, hover_transition_time, Easing.OutQuint); if (FadePlayButton && !PreviewPlaying.Value) PlayButton.FadeOut(120, Easing.InOutQuint); base.OnHoverLost(e); } protected override void LoadComplete() { base.LoadComplete(); this.FadeInFromZero(200, Easing.Out); PreviewPlaying.ValueChanged += playing => { PlayButton.FadeTo(playing.NewValue || IsHovered || !FadePlayButton ? 1 : 0, 120, Easing.InOutQuint); PreviewBar.FadeTo(playing.NewValue ? 1 : 0, 120, Easing.InOutQuint); }; } protected List<DifficultyIcon> GetDifficultyIcons(OsuColour colours) { var icons = new List<DifficultyIcon>(); if (SetInfo.Beatmaps.Count > maximum_difficulty_icons) { foreach (var ruleset in SetInfo.Beatmaps.Select(b => b.Ruleset).Distinct()) icons.Add(new GroupedDifficultyIcon(SetInfo.Beatmaps.FindAll(b => b.Ruleset.Equals(ruleset)), ruleset, this is ListBeatmapPanel ? Color4.White : colours.Gray5)); } else { foreach (var b in SetInfo.Beatmaps.OrderBy(beatmap => beatmap.Ruleset.ID).ThenBy(beatmap => beatmap.StarDifficulty)) icons.Add(new DifficultyIcon(b)); } return icons; } protected Drawable CreateBackground() => new UpdateableBeatmapSetCover { RelativeSizeAxes = Axes.Both, BeatmapSet = SetInfo, }; public class Statistic : FillFlowContainer { private readonly SpriteText text; private int value; public int Value { get => value; set { this.value = value; text.Text = Value.ToString(@"N0"); } } public Statistic(IconUsage icon, int value = 0) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; AutoSizeAxes = Axes.Both; Direction = FillDirection.Horizontal; Spacing = new Vector2(5f, 0f); Children = new Drawable[] { text = new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.SemiBold, italics: true) }, new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = icon, Shadow = true, Size = new Vector2(14), }, }; Value = value; } } public MenuItem[] ContextMenuItems => new MenuItem[] { new OsuMenuItem("View Beatmap", MenuItemType.Highlighted, ViewBeatmap), }; } }
using UnityEngine; class SensorEditorUnity : Sensor { // for debugging the values in the editor public bool accelerometerAvailable = true; public bool magneticFieldAvailable = true; public bool orientationAvailable = true; public bool gyroscopeAvailable = true; public bool lightAvailable = true; public bool pressureAvailable = true; public bool temperatureAvailable = true; public bool proximityAvailable = true; public bool gravityAvailable = true; public bool linearAccelerationAvailable = true; public bool rotationVectorAvailable = true; public bool ambientTemperatureAvailable = true; public bool relativeHumidityAvailable = true; // Actual Values public Vector3 accelerometerDebugValue = Vector3.zero; public Vector3 magneticFieldDebugValue = Vector3.zero; public Vector3 orientationDebugValue = Vector3.zero; public Vector3 gyroscopeDebugValue = Vector3.zero; public float lightDebugValue = 0; public float pressureDebugValue = 0; public float temperatureDebugValue = 0; public float proximityDebugValue = 0; public Vector3 gravityDebugValue = Vector3.zero; public Vector3 linearAccelerationDebugValue = Vector3.zero; public Vector3 rotationVectorDebugValue = new Vector3(0, -270.0f, 0); public Vector3 getOrientationDebugValue = Vector3.zero; public float ambientTemperatureDebugValue = 0; public float relativeHumidityDebugValue = 0; //#if (!UNITY_ANDROID && !UNITY_IPHONE) || UNITY_EDITOR private const float AltitudeCoef = 1.0f / 5.255f; protected override void AwakeDevice() { if(!Application.isEditor) { Singleton = null; Destroy(this); } for (var i = 1; i <= Sensor.Count; i++) { // fill the sensor information array with debug values Sensors[i] = new Information(GetSensorDebugAvailable(i), 1, 0, "DEBUG", 0, 100, "DEBUG", 0, Description[i]); } } protected override void SetSensorOn(Type sensorID) { base.SetSensorOn(sensorID); Input.gyro.enabled = true; Input.compass.enabled = true; } protected override void DisableDevice() { // Nothing to do } protected override bool ActivateDeviceSensor(Type sensorID, Sensor.Delay sensorSpeed) { Input.gyro.enabled = true; Input.compass.enabled = true; Get (sensorID).available = GetSensorDebugAvailable((int)sensorID); Get (sensorID).active = true; return true; } protected override bool DeactivateDeviceSensor(Type sensorID) { Get (sensorID).active = false; return true; } public static SensorEditorUnity Instance { get { return (SensorEditorUnity) SensorEditorUnity.Singleton; } } public void PullDeviceSensor(Type sensorID) { var val = Get(sensorID).values; switch (sensorID) { case Type.Accelerometer: accelerometerDebugValue = val; break; case Type.Gravity: gravityDebugValue = val; break; case Type.Gyroscope: gyroscopeDebugValue = val; break; case Type.Light: lightDebugValue = val.x; break; case Type.LinearAcceleration: linearAccelerationDebugValue = val; break; case Type.MagneticField: magneticFieldDebugValue = val; break; case Type.Orientation: orientationDebugValue = val; break; case Type.Pressure: pressureDebugValue = val.x; break; case Type.Proximity: proximityDebugValue = val.x; break; case Type.RotationVector: rotationVectorDebugValue = val; break; case Type.Temperature: temperatureDebugValue = val.x; break; case Type.AmbientTemperature: ambientTemperatureDebugValue = val.x; break; case Type.RelativeHumidity: relativeHumidityDebugValue = val.x; break; } } Quaternion lastGyroAttitude = Quaternion.identity; Vector3 lastAcceleration; protected override Vector3 GetDeviceSensor(Type sensorID) { Get(sensorID).gotFirstValue = true; // if not everything is fine, use debug values (can be set in the inspector) switch (sensorID) { case Type.Accelerometer: if(Vector3.Distance(Input.acceleration, lastAcceleration) > 0.001f ) return Input.acceleration; lastAcceleration = Input.acceleration; return accelerometerDebugValue; case Type.Gravity: return gravityDebugValue; case Type.Gyroscope: return gyroscopeDebugValue; case Type.Light: return new Vector3(lightDebugValue, 0, 0); case Type.LinearAcceleration: return linearAccelerationDebugValue; case Type.MagneticField: return magneticFieldDebugValue; case Type.Orientation: return orientationDebugValue; case Type.Pressure: return new Vector3(pressureDebugValue, 0, 0); case Type.Proximity: return new Vector3(proximityDebugValue, 0, 0); case Type.RotationVector: if(Quaternion.Angle (Input.gyro.attitude, lastGyroAttitude) > 0.001f) return -(Quaternion.Euler (-90,0,0) * Input.gyro.attitude).eulerAngles; lastGyroAttitude = Input.gyro.attitude; return rotationVectorDebugValue; case Type.Temperature: return new Vector3(temperatureDebugValue, 0, 0); case Type.AmbientTemperature: return new Vector3(ambientTemperatureDebugValue, 0, 0); case Type.RelativeHumidity: return new Vector3(relativeHumidityDebugValue, 0, 0); default: return Vector3.zero; } } protected override Vector3 _getDeviceOrientation() { return getOrientationDebugValue; } protected override float GetDeviceAltitude(float pressure, float pressureAtSeaLevel = PressureValue.StandardAthmosphere) { if (pressure == 0) { return 0; } return 44330.0f * (1.0f - Mathf.Pow(pressure / pressureAtSeaLevel, AltitudeCoef)); // return -7 * Mathf.Log((pressure / 1000) / (pressureAtSeaLevel / 1000)) * 1000; } protected override Sensor.SurfaceRotation GetSurfaceRotation() { return Sensor.SurfaceRotation.Rotation0; } protected override Quaternion QuaternionFromDeviceRotationVector(Vector3 v) { return Quaternion.Euler( v ); // Get (Type.RotationVector).values); } protected override void CompensateDeviceOrientation(ref Vector3 k) { } protected Quaternion _getSurfaceRotationCompensation() { return Quaternion.Euler(0, 0, 0); } // Available-Checkbox for every sensor for testing whether sensor fallback etc. works private bool GetSensorDebugAvailable(int id) { switch ((Type) id) { case Type.Accelerometer: return accelerometerAvailable; case Type.Gravity: return gravityAvailable; case Type.Gyroscope: return gyroscopeAvailable; case Type.Light: return lightAvailable; case Type.LinearAcceleration: return linearAccelerationAvailable; case Type.MagneticField: return magneticFieldAvailable; case Type.Orientation: return orientationAvailable; case Type.Pressure: return pressureAvailable; case Type.Proximity: return proximityAvailable; case Type.RotationVector: return rotationVectorAvailable; case Type.Temperature: return temperatureAvailable; case Type.AmbientTemperature: return ambientTemperatureAvailable; case Type.RelativeHumidity: return relativeHumidityAvailable; default: return false; } } protected override ScreenOrientation ScreenOrientationDevice { get { return Screen.width >= Screen.height ? ScreenOrientation.LandscapeLeft : ScreenOrientation.Portrait; } } //#endif }
using System; using System.IO; using System.Net; using System.Security.Principal; using System.Threading; using System.Collections; using System.Web; using System.Web.Mail; using System.Web.Security; using newtelligence.DasBlog.Runtime.Proxies; using newtelligence.DasBlog.Web.Core; using newtelligence.DasBlog.Runtime; using newtelligence.DasBlog.Web.Services; namespace newtelligence.DasBlog.Web { /// <summary> /// Summary description for Global. /// </summary> public class Global : HttpApplication { private XSSUpstreamer xssUpstreamer = null; private Thread xssUpstreamerThread = null; private MailToWeblog mailToWeblog = null; private Thread mailToWeblogThread = null; private ReportMailer reportMailer = null; private Thread reportMailerThread = null; private bool identityLoaded = false; public Global() { InitializeComponent(); } protected void Application_Start(Object sender, EventArgs e) { //We clear out the Cache on App Restart... CacheFactory.GetCache().Clear(); ILoggingDataService loggingService = null; loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext()); loggingService.AddEvent(new EventDataItem(EventCodes.ApplicationStartup, "", "")); SiteConfig siteConfig = SiteConfig.GetSiteConfig(SiteConfig.GetConfigFilePathFromCurrentContext()); //if (siteConfig.EnableReportMailer) { reportMailer = new ReportMailer( SiteConfig.GetConfigFilePathFromCurrentContext(), SiteConfig.GetContentPathFromCurrentContext(), SiteConfig.GetLogPathFromCurrentContext() ); reportMailerThread = new Thread(new ThreadStart(reportMailer.Run)); reportMailerThread.Name = "ReportMailer"; reportMailerThread.IsBackground = true; reportMailerThread.Start(); } if (siteConfig.EnablePop3) { mailToWeblog = new MailToWeblog( SiteConfig.GetConfigFilePathFromCurrentContext(), SiteConfig.GetContentPathFromCurrentContext(), SiteConfig.GetBinariesPathFromCurrentContext(), SiteConfig.GetLogPathFromCurrentContext(), new Uri(new Uri(SiteConfig.GetSiteConfig().Root), SiteConfig.GetSiteConfig().BinariesDirRelative) ); mailToWeblogThread = new Thread(new ThreadStart(mailToWeblog.Run)); mailToWeblogThread.Name = "MailToWeblog"; mailToWeblogThread.IsBackground = true; mailToWeblogThread.Start(); } if (siteConfig.EnableXSSUpstream) { xssUpstreamer = new XSSUpstreamer( SiteConfig.GetConfigFilePathFromCurrentContext(), SiteConfig.GetContentPathFromCurrentContext(), SiteConfig.GetLogPathFromCurrentContext() ); xssUpstreamerThread = new Thread(new ThreadStart(xssUpstreamer.Run)); xssUpstreamerThread.Name = "XSSUpstreamer"; xssUpstreamerThread.IsBackground = true; xssUpstreamerThread.Start(); } /* if (siteConfig.EnableMovableTypeBlackList) { ReferralBlackListFactory.AddBlacklist(new MovableTypeBlacklist(), Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(), "blacklist.txt")); } */ if (siteConfig.EnableReferralUrlBlackList && siteConfig.ReferralUrlBlackList.Length != 0) { ReferralBlackListFactory.AddBlacklist(new ReferralUrlBlacklist(), siteConfig.ReferralUrlBlackList); } } protected void Session_Start(Object sender, EventArgs e) { } System.Text.RegularExpressions.Regex oldAtom = new System.Text.RegularExpressions.Regex("SyndicationServiceExperimental.asmx",System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase); protected void Application_BeginRequest(Object sender, EventArgs e) { if (identityLoaded == false) { Impersonation.ApplicationIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); identityLoaded = true; } HttpRequest request = HttpContext.Current.Request; HttpResponse response = HttpContext.Current.Response; //Custom 301 Permanent Redirect for requests for the order Atom 0.3 feed if (oldAtom.IsMatch(request.Path)) { if (request.RequestType == "GET") { response.StatusCode = 301; response.Status = "301 Moved Permanently"; response.RedirectLocation = oldAtom.Replace(request.Path,"SyndicationService.asmx"); response.End(); } } } protected void Application_EndRequest(Object sender, EventArgs e) { //Only needed on ASP.NET 1.1 if(System.Environment.Version.Major < 2) { foreach(string cookie in Response.Cookies) { const string HTTPONLY = ";HttpOnly"; string path = Response.Cookies[cookie].Path; if (path.EndsWith(HTTPONLY) == false) { //force HttpOnly to be added to the cookie problem Response.Cookies[cookie].Path += HTTPONLY; } } } } protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (Request.IsAuthenticated == true) { HttpCookie authenCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName); if (authenCookie == null) { FormsAuthentication.SignOut(); HttpContext.Current.User = null; return; } FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authenCookie.Value); FormsIdentity id = new FormsIdentity(ticket); UserToken token = SiteSecurity.GetToken(ticket.Name); if (token != null) { GenericPrincipal principal = new GenericPrincipal(id, new string[] {token.Role}); HttpContext.Current.User = principal; } else { FormsAuthentication.SignOut(); HttpContext.Current.User = null; } } } protected void Application_Error(Object sender, EventArgs e) { } protected void Session_End(Object sender, EventArgs e) { } protected void Application_End(Object sender, EventArgs e) { if (mailToWeblogThread != null) { mailToWeblogThread.Abort(); mailToWeblogThread.Join(); } if (reportMailerThread != null) { reportMailerThread.Abort(); reportMailerThread.Join(); } if (xssUpstreamerThread != null) { xssUpstreamerThread.Abort(); xssUpstreamerThread.Join(); } } #region Web 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() { // // Global // this.BeginRequest += new EventHandler(this.Application_BeginRequest); this.Error += new EventHandler(this.Application_Error); this.AuthenticateRequest += new EventHandler(this.Application_AuthenticateRequest); this.EndRequest += new EventHandler(this.Application_EndRequest); } #endregion } }
using System.Reactive; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Numerics; using Autofac; using AutoMapper; using Miningcore.Blockchain.Bitcoin; using Miningcore.Blockchain.Ergo.Configuration; using Miningcore.Configuration; using Miningcore.Extensions; using Miningcore.JsonRpc; using Miningcore.Messaging; using Miningcore.Mining; using Miningcore.Nicehash; using Miningcore.Notifications.Messages; using Miningcore.Persistence; using Miningcore.Persistence.Repositories; using Miningcore.Stratum; using Miningcore.Time; using Miningcore.Util; using Newtonsoft.Json; using static Miningcore.Util.ActionUtils; namespace Miningcore.Blockchain.Ergo; [CoinFamily(CoinFamily.Ergo)] public class ErgoPool : PoolBase { public ErgoPool(IComponentContext ctx, JsonSerializerSettings serializerSettings, IConnectionFactory cf, IStatsRepository statsRepo, IMapper mapper, IMasterClock clock, IMessageBus messageBus, NicehashService nicehashService) : base(ctx, serializerSettings, cf, statsRepo, mapper, clock, messageBus, nicehashService) { } protected object[] currentJobParams; protected ErgoJobManager manager; private ErgoPoolConfigExtra extraPoolConfig; private ErgoCoinTemplate coin; protected virtual async Task OnSubscribeAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest) { var request = tsRequest.Value; if(request.Id == null) throw new StratumException(StratumError.MinusOne, "missing request id"); var context = connection.ContextAs<ErgoWorkerContext>(); var requestParams = request.ParamsAs<string[]>(); var data = new object[] { new object[] { new object[] { BitcoinStratumMethods.SetDifficulty, connection.ConnectionId }, new object[] { BitcoinStratumMethods.MiningNotify, connection.ConnectionId } } } .Concat(manager.GetSubscriberData(connection)) .ToArray(); await connection.RespondAsync(data, request.Id); // setup worker context context.IsSubscribed = true; context.UserAgent = requestParams?.Length > 0 ? requestParams[0].Trim() : null; } protected virtual async Task OnAuthorizeAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct) { var request = tsRequest.Value; if(request.Id == null) throw new StratumException(StratumError.MinusOne, "missing request id"); var context = connection.ContextAs<ErgoWorkerContext>(); var requestParams = request.ParamsAs<string[]>(); var workerValue = requestParams?.Length > 0 ? requestParams[0] : null; var password = requestParams?.Length > 1 ? requestParams[1] : null; var passParts = password?.Split(PasswordControlVarsSeparator); // extract worker/miner var split = workerValue?.Split('.'); var minerName = split?.FirstOrDefault()?.Trim(); var workerName = split?.Skip(1).FirstOrDefault()?.Trim() ?? string.Empty; // assumes that minerName is an address context.IsAuthorized = await manager.ValidateAddress(minerName, ct); context.Miner = minerName; context.Worker = workerName; if(context.IsAuthorized) { // respond await connection.RespondAsync(context.IsAuthorized, request.Id); // log association logger.Info(() => $"[{connection.ConnectionId}] Authorized worker {workerValue}"); // extract control vars from password var staticDiff = GetStaticDiffFromPassparts(passParts); // Nicehash support var nicehashDiff = await GetNicehashStaticMinDiff(connection, context.UserAgent, coin.Name, coin.GetAlgorithmName()); if(nicehashDiff.HasValue) { if(!staticDiff.HasValue || nicehashDiff > staticDiff) { logger.Info(() => $"[{connection.ConnectionId}] Nicehash detected. Using API supplied difficulty of {nicehashDiff.Value}"); staticDiff = nicehashDiff; } else logger.Info(() => $"[{connection.ConnectionId}] Nicehash detected. Using miner supplied difficulty of {staticDiff.Value}"); } // Static diff if(staticDiff.HasValue && (context.VarDiff != null && staticDiff.Value >= context.VarDiff.Config.MinDiff || context.VarDiff == null && staticDiff.Value > context.Difficulty)) { context.VarDiff = null; // disable vardiff context.SetDifficulty(staticDiff.Value); logger.Info(() => $"[{connection.ConnectionId}] Setting static difficulty of {staticDiff.Value}"); } // send intial update await SendJob(connection, context, currentJobParams); } else { await connection.RespondErrorAsync(StratumError.UnauthorizedWorker, "Authorization failed", request.Id, context.IsAuthorized); // issue short-time ban if unauthorized to prevent DDos on daemon (validateaddress RPC) logger.Info(() => $"[{connection.ConnectionId}] Banning unauthorized worker {minerName} for {loginFailureBanTimeout.TotalSeconds} sec"); banManager.Ban(connection.RemoteEndpoint.Address, loginFailureBanTimeout); CloseConnection(connection); } } protected virtual async Task OnSubmitAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct) { var request = tsRequest.Value; var context = connection.ContextAs<ErgoWorkerContext>(); try { if(request.Id == null) throw new StratumException(StratumError.MinusOne, "missing request id"); // check age of submission (aged submissions are usually caused by high server load) var requestAge = clock.Now - tsRequest.Timestamp.UtcDateTime; if(requestAge > maxShareAge) { logger.Warn(() => $"[{connection.ConnectionId}] Dropping stale share submission request (server overloaded?)"); return; } // check worker state context.LastActivity = clock.Now; // validate worker if(!context.IsAuthorized) throw new StratumException(StratumError.UnauthorizedWorker, "unauthorized worker"); else if(!context.IsSubscribed) throw new StratumException(StratumError.NotSubscribed, "not subscribed"); // submit var requestParams = request.ParamsAs<string[]>(); var poolEndpoint = poolConfig.Ports[connection.LocalEndpoint.Port]; var share = await manager.SubmitShareAsync(connection, requestParams, poolEndpoint.Difficulty, ct); await connection.RespondAsync(true, request.Id); // publish messageBus.SendMessage(new StratumShare(connection, share)); // telemetry PublishTelemetry(TelemetryCategory.Share, clock.Now - tsRequest.Timestamp.UtcDateTime, true); logger.Info(() => $"[{connection.ConnectionId}] Share accepted: D={Math.Round(share.Difficulty * ErgoConstants.ShareMultiplier, 3)}"); // update pool stats if(share.IsBlockCandidate) poolStats.LastPoolBlockTime = clock.Now; // update client stats context.Stats.ValidShares++; await UpdateVarDiffAsync(connection); } catch(StratumException ex) { // telemetry PublishTelemetry(TelemetryCategory.Share, clock.Now - tsRequest.Timestamp.UtcDateTime, false); // update client stats context.Stats.InvalidShares++; logger.Info(() => $"[{connection.ConnectionId}] Share rejected: {ex.Message} [{context.UserAgent}]"); // banning ConsiderBan(connection, context, poolConfig.Banning); throw; } } protected virtual Task OnNewJobAsync(object[] jobParams) { currentJobParams = jobParams; logger.Info(() => "Broadcasting job"); return Guard(()=> Task.WhenAll(ForEachConnection(async connection => { if(!connection.IsAlive) return; var context = connection.ContextAs<ErgoWorkerContext>(); if(!context.IsSubscribed || !context.IsAuthorized || CloseIfDead(connection, context)) return; await SendJob(connection, context, currentJobParams); })), ex=> logger.Debug(() => $"{nameof(OnNewJobAsync)}: {ex.Message}")); } private async Task SendJob(StratumConnection connection, ErgoWorkerContext context, object[] jobParams) { // clone job params var jobParamsActual = new object[jobParams.Length]; for(var i = 0; i < jobParamsActual.Length; i++) jobParamsActual[i] = jobParams[i]; var target = new BigRational(BitcoinConstants.Diff1 * (BigInteger) (1 / context.Difficulty * 0x10000), 0x10000).GetWholePart(); jobParamsActual[6] = target.ToString(); // send static diff of 1 since actual diff gets pre-multiplied to target await connection.NotifyAsync(BitcoinStratumMethods.SetDifficulty, new object[] { 1 }); // send target await connection.NotifyAsync(BitcoinStratumMethods.MiningNotify, jobParamsActual); } public override double HashrateFromShares(double shares, double interval) { var multiplier = BitcoinConstants.Pow2x32 * ErgoConstants.ShareMultiplier; var result = shares * multiplier / interval; // add flat pool side hashrate bonus to account for miner dataset generation result *= 1.15; return result; } public override double ShareMultiplier => ErgoConstants.ShareMultiplier; #region Overrides public override void Configure(PoolConfig poolConfig, ClusterConfig clusterConfig) { coin = poolConfig.Template.As<ErgoCoinTemplate>(); extraPoolConfig = poolConfig.Extra.SafeExtensionDataAs<ErgoPoolConfigExtra>(); base.Configure(poolConfig, clusterConfig); } protected override async Task SetupJobManager(CancellationToken ct) { var extraNonce1Size = extraPoolConfig?.ExtraNonce1Size ?? 2; manager = ctx.Resolve<ErgoJobManager>( new TypedParameter(typeof(IExtraNonceProvider), new ErgoExtraNonceProvider(poolConfig.Id, extraNonce1Size, clusterConfig.InstanceId))); manager.Configure(poolConfig, clusterConfig); await manager.StartAsync(ct); if(poolConfig.EnableInternalStratum == true) { disposables.Add(manager.Jobs .Select(job => Observable.FromAsync(() => Guard(()=> OnNewJobAsync(job), ex=> logger.Debug(() => $"{nameof(OnNewJobAsync)}: {ex.Message}")))) .Concat() .Subscribe(_ => { }, ex => { logger.Debug(ex, nameof(OnNewJobAsync)); })); // start with initial blocktemplate await manager.Jobs.Take(1).ToTask(ct); } else { // keep updating NetworkStats disposables.Add(manager.Jobs.Subscribe()); } } protected override async Task InitStatsAsync() { await base.InitStatsAsync(); blockchainStats = manager.BlockchainStats; } protected override WorkerContextBase CreateWorkerContext() { return new ErgoWorkerContext(); } protected override async Task OnRequestAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct) { var request = tsRequest.Value; try { switch(request.Method) { case BitcoinStratumMethods.Subscribe: await OnSubscribeAsync(connection, tsRequest); break; case BitcoinStratumMethods.Authorize: await OnAuthorizeAsync(connection, tsRequest, ct); break; case BitcoinStratumMethods.SubmitShare: await OnSubmitAsync(connection, tsRequest, ct); break; default: logger.Debug(() => $"[{connection.ConnectionId}] Unsupported RPC request: {JsonConvert.SerializeObject(request, serializerSettings)}"); await connection.RespondErrorAsync(StratumError.Other, $"Unsupported request {request.Method}", request.Id); break; } } catch(StratumException ex) { await connection.RespondErrorAsync(ex.Code, ex.Message, request.Id, false); } } protected override async Task<double?> GetNicehashStaticMinDiff(StratumConnection connection, string userAgent, string coinName, string algoName) { var result= await base.GetNicehashStaticMinDiff(connection, userAgent, coinName, algoName); // adjust value to fit with our target value calculation if(result.HasValue) result = result.Value / uint.MaxValue; return result; } protected override async Task OnVarDiffUpdateAsync(StratumConnection connection, double newDiff) { var context = connection.ContextAs<ErgoWorkerContext>(); context.EnqueueNewDifficulty(newDiff); if(context.HasPendingDifficulty) { context.ApplyPendingDifficulty(); await SendJob(connection, context, currentJobParams); } } #endregion // Overrides }
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // 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. // This file was automatically generated and should not be edited directly. using System; namespace SharpVk.NVidia.Experimental { /// <summary> /// Opaque handle to an object table. /// </summary> public partial class ObjectTable : IDisposable { internal readonly SharpVk.Interop.NVidia.Experimental.ObjectTable handle; internal readonly CommandCache commandCache; internal readonly SharpVk.Device parent; internal ObjectTable(SharpVk.Device parent, SharpVk.Interop.NVidia.Experimental.ObjectTable handle) { this.handle = handle; this.parent = parent; this.commandCache = parent.commandCache; } /// <summary> /// The raw handle for this instance. /// </summary> public SharpVk.Interop.NVidia.Experimental.ObjectTable RawHandle => this.handle; /// <summary> /// Destroy a object table. /// </summary> /// <param name="allocator"> /// An optional AllocationCallbacks instance that controls host memory /// allocation. /// </param> public unsafe void Destroy(SharpVk.AllocationCallbacks? allocator = default(SharpVk.AllocationCallbacks?)) { try { SharpVk.Interop.AllocationCallbacks* marshalledAllocator = default(SharpVk.Interop.AllocationCallbacks*); if (allocator != null) { marshalledAllocator = (SharpVk.Interop.AllocationCallbacks*)(Interop.HeapUtil.Allocate<SharpVk.Interop.AllocationCallbacks>()); allocator.Value.MarshalTo(marshalledAllocator); } else { marshalledAllocator = default(SharpVk.Interop.AllocationCallbacks*); } SharpVk.Interop.NVidia.Experimental.VkObjectTableNVXDestroyDelegate commandDelegate = commandCache.Cache.vkDestroyObjectTableNVX; commandDelegate(this.parent.handle, this.handle, marshalledAllocator); } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// /// </summary> /// <param name="objectTableEntries"> /// </param> /// <param name="objectIndices"> /// </param> public unsafe void RegisterObjects(ArrayProxy<SharpVk.NVidia.Experimental.ObjectTableEntry>? objectTableEntries, ArrayProxy<uint>? objectIndices) { try { SharpVk.NVidia.Experimental.ObjectTableEntry** marshalledObjectTableEntries = default(SharpVk.NVidia.Experimental.ObjectTableEntry**); SharpVk.NVidia.Experimental.ObjectTableEntry* semiMarshalledObjectTableEntries = default(SharpVk.NVidia.Experimental.ObjectTableEntry*); uint* marshalledObjectIndices = default(uint*); if (objectTableEntries.IsNull()) { marshalledObjectTableEntries = null; } else { if (objectTableEntries.Value.Contents == ProxyContents.Single) { semiMarshalledObjectTableEntries = (SharpVk.NVidia.Experimental.ObjectTableEntry*)(Interop.HeapUtil.Allocate<SharpVk.NVidia.Experimental.ObjectTableEntry>()); *(SharpVk.NVidia.Experimental.ObjectTableEntry*)(semiMarshalledObjectTableEntries) = objectTableEntries.Value.GetSingleValue(); } else { var fieldPointer = (SharpVk.NVidia.Experimental.ObjectTableEntry*)(Interop.HeapUtil.AllocateAndClear<SharpVk.NVidia.Experimental.ObjectTableEntry>(Interop.HeapUtil.GetLength(objectTableEntries.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(objectTableEntries.Value)); index++) { fieldPointer[index] = objectTableEntries.Value[index]; } semiMarshalledObjectTableEntries = fieldPointer; var marshalledFieldPointer = (SharpVk.NVidia.Experimental.ObjectTableEntry**)(Interop.HeapUtil.AllocateAndClear<IntPtr>(Interop.HeapUtil.GetLength(objectTableEntries.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(objectTableEntries.Value)); index++) { marshalledFieldPointer[index] = &semiMarshalledObjectTableEntries[index]; } marshalledObjectTableEntries = marshalledFieldPointer; } } if (objectIndices.IsNull()) { marshalledObjectIndices = null; } else { if (objectIndices.Value.Contents == ProxyContents.Single) { marshalledObjectIndices = (uint*)(Interop.HeapUtil.Allocate<uint>()); *(uint*)(marshalledObjectIndices) = objectIndices.Value.GetSingleValue(); } else { var fieldPointer = (uint*)(Interop.HeapUtil.AllocateAndClear<uint>(Interop.HeapUtil.GetLength(objectIndices.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(objectIndices.Value)); index++) { fieldPointer[index] = objectIndices.Value[index]; } marshalledObjectIndices = fieldPointer; } } SharpVk.Interop.NVidia.Experimental.VkObjectTableNVXRegisterObjectsDelegate commandDelegate = commandCache.Cache.vkRegisterObjectsNVX; Result methodResult = commandDelegate(this.parent.handle, this.handle, (uint)(Interop.HeapUtil.GetLength(objectTableEntries)), marshalledObjectTableEntries, marshalledObjectIndices); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// /// </summary> /// <param name="objectEntryTypes"> /// </param> /// <param name="objectIndices"> /// </param> public unsafe void UnregisterObjects(ArrayProxy<SharpVk.NVidia.Experimental.ObjectEntryType>? objectEntryTypes, ArrayProxy<uint>? objectIndices) { try { SharpVk.NVidia.Experimental.ObjectEntryType* marshalledObjectEntryTypes = default(SharpVk.NVidia.Experimental.ObjectEntryType*); uint* marshalledObjectIndices = default(uint*); if (objectEntryTypes.IsNull()) { marshalledObjectEntryTypes = null; } else { if (objectEntryTypes.Value.Contents == ProxyContents.Single) { marshalledObjectEntryTypes = (SharpVk.NVidia.Experimental.ObjectEntryType*)(Interop.HeapUtil.Allocate<SharpVk.NVidia.Experimental.ObjectEntryType>()); *(SharpVk.NVidia.Experimental.ObjectEntryType*)(marshalledObjectEntryTypes) = objectEntryTypes.Value.GetSingleValue(); } else { var fieldPointer = (SharpVk.NVidia.Experimental.ObjectEntryType*)(Interop.HeapUtil.AllocateAndClear<SharpVk.NVidia.Experimental.ObjectEntryType>(Interop.HeapUtil.GetLength(objectEntryTypes.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(objectEntryTypes.Value)); index++) { fieldPointer[index] = objectEntryTypes.Value[index]; } marshalledObjectEntryTypes = fieldPointer; } } if (objectIndices.IsNull()) { marshalledObjectIndices = null; } else { if (objectIndices.Value.Contents == ProxyContents.Single) { marshalledObjectIndices = (uint*)(Interop.HeapUtil.Allocate<uint>()); *(uint*)(marshalledObjectIndices) = objectIndices.Value.GetSingleValue(); } else { var fieldPointer = (uint*)(Interop.HeapUtil.AllocateAndClear<uint>(Interop.HeapUtil.GetLength(objectIndices.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(objectIndices.Value)); index++) { fieldPointer[index] = objectIndices.Value[index]; } marshalledObjectIndices = fieldPointer; } } SharpVk.Interop.NVidia.Experimental.VkObjectTableNVXUnregisterObjectsDelegate commandDelegate = commandCache.Cache.vkUnregisterObjectsNVX; Result methodResult = commandDelegate(this.parent.handle, this.handle, (uint)(Interop.HeapUtil.GetLength(objectEntryTypes)), marshalledObjectEntryTypes, marshalledObjectIndices); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Destroys the handles and releases any unmanaged resources /// associated with it. /// </summary> public void Dispose() { this.Destroy(); } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Net; using System.Reflection; using System.Timers; using System.Threading.Tasks; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace InWorldz.RemoteAdmin { class RemoteAdminPlugin : IApplicationPlugin { #region Declares private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_name = "RemoteAdmin"; private string m_version = "0.0"; private static Object rslock = new Object(); private List<Scene> _scenes = new List<Scene>(); private RemoteAdmin m_admin = null; private OpenSimBase m_app = null; #endregion public string Version { get { return m_version; } } public string Name { get { return m_name; } } public void Initialise() { m_log.Info("[RADMIN]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } public void Initialise(OpenSimBase openSim) { m_app = openSim; m_admin = new RemoteAdmin(); } public void PostInitialise() { m_admin.AddCommand("Region", "Restart", RegionRestartHandler); m_admin.AddCommand("Region", "SendAlert", RegionSendAlertHandler); m_admin.AddCommand("Region", "Shutdown", RegionShutdownHandler); m_admin.AddCommand("Region", "Backup", RegionBackupHandler); m_admin.AddCommand("Region", "Restore", RegionRestoreHandler); m_admin.AddCommand("Region", "LoadOAR", LoadOARHandler); m_admin.AddCommand("Region", "SaveOAR", SaveOARHandler); m_admin.AddCommand("Region", "ChangeParcelFlags", RegionChangeParcelFlagsHandler); m_admin.AddHandler(MainServer.Instance); } public void Dispose() { m_admin.Dispose(); } #region RemoteAdmin Region Handlers private object RegionRestartHandler(IList args, IPEndPoint remoteClient) { m_admin.CheckSessionValid(new UUID((string)args[0])); UUID regionID = new UUID((string)args[1]); Scene rebootedScene; if (!m_app.SceneManager.TryGetScene(regionID, out rebootedScene)) throw new Exception("region not found"); rebootedScene.Restart(30); return (true); } public object RegionShutdownHandler(IList args, IPEndPoint remoteClient) { m_admin.CheckSessionValid(new UUID((string)args[0])); try { Scene rebootedScene; string message; UUID regionID = new UUID(Convert.ToString(args[1])); int delay = Convert.ToInt32(args[2]); if (!m_app.SceneManager.TryGetScene(regionID, out rebootedScene)) throw new Exception("Region not found"); message = GenerateShutdownMessage(delay); m_log.DebugFormat("[RADMIN] Shutdown: {0}", message); IDialogModule dialogModule = rebootedScene.RequestModuleInterface<IDialogModule>(); if (dialogModule != null) dialogModule.SendGeneralAlert(message); ulong tcNow = Util.GetLongTickCount(); ulong endTime = tcNow + (ulong)(delay * 1000); ulong nextReport = tcNow + (ulong)(60 * 1000); // Perform shutdown if (delay > 0) { while (true) { System.Threading.Thread.Sleep(1000); tcNow = Util.GetLongTickCount(); if (tcNow >= endTime) { break; } if (tcNow >= nextReport) { delay -= 60; if (delay >= 0) { GenerateShutdownMessage(delay); nextReport = tcNow + (ulong)(60 * 1000); } } } } // Do this on a new thread so the actual shutdown call returns successfully. Task.Factory.StartNew(() => { m_app.Shutdown(); }); } catch (Exception e) { m_log.ErrorFormat("[RADMIN] Shutdown: failed: {0}", e.Message); m_log.DebugFormat("[RADMIN] Shutdown: failed: {0}", e.ToString()); throw e; } m_log.Info("[RADMIN]: Shutdown Administrator Request complete"); return true; } private static string GenerateShutdownMessage(int delay) { string message; if (delay > 0) { if (delay <= 60) message = "Region is going down in " + delay.ToString() + " second(s)."; else message = "Region is going down in " + (delay / 60).ToString() + " minute(s)."; } else { message = "Region is going down now."; } return message; } public object RegionSendAlertHandler(IList args, IPEndPoint remoteClient) { m_admin.CheckSessionValid(new UUID((string)args[0])); if (args.Count < 3) return false; Scene scene; if (!m_app.SceneManager.TryGetScene((string)args[1], out scene)) throw new Exception("region not found"); String message = (string)args[2]; IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>(); if (dialogModule != null) dialogModule.SendGeneralAlert(message); return true; } /// <summary> /// Load an OAR file into a region.. /// <summary> /// <param name="request">incoming XML RPC request</param> /// <remarks> /// XmlRpcLoadOARMethod takes the following XMLRPC parameters /// <list type="table"> /// <listheader><term>parameter name</term><description>description</description></listheader> /// <item><term>session</term> /// <description>An authenticated session ID</description></item> /// <item><term>region_uuid</term> /// <description>UUID of the region</description></item> /// <item><term>filename</term> /// <description>file name of the OAR file</description></item> /// </list> /// /// Returns /// <list type="table"> /// <listheader><term>name</term><description>description</description></listheader> /// <item><term>success</term> /// <description>true or false</description></item> /// </list> /// </remarks> public object LoadOARHandler(IList args, IPEndPoint remoteClient) { m_admin.CheckSessionValid(new UUID((string)args[0])); Scene scene; if (!m_app.SceneManager.TryGetScene((string)args[1], out scene)) throw new Exception("region not found"); String filename = (string)args[2]; bool allowUserReassignment = Convert.ToBoolean(args[3]); bool skipErrorGroups = Convert.ToBoolean(args[4]); m_log.Info("[RADMIN]: Received Load OAR Administrator Request"); lock (rslock) { try { IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>(); if (archiver != null) archiver.DearchiveRegion(filename, allowUserReassignment, skipErrorGroups); else throw new Exception("Archiver module not present for scene"); m_log.Info("[RADMIN]: Load OAR Administrator Request complete"); return true; } catch (Exception e) { m_log.InfoFormat("[RADMIN] LoadOAR: {0}", e.Message); m_log.DebugFormat("[RADMIN] LoadOAR: {0}", e.ToString()); } return false; } } /// <summary> /// Load an OAR file into a region.. /// <summary> /// <param name="request">incoming XML RPC request</param> /// <remarks> /// XmlRpcLoadOARMethod takes the following XMLRPC parameters /// <list type="table"> /// <listheader><term>parameter name</term><description>description</description></listheader> /// <item><term>session</term> /// <description>An authenticated session ID</description></item> /// <item><term>region_uuid</term> /// <description>UUID of the region</description></item> /// <item><term>filename</term> /// <description>file name of the OAR file</description></item> /// </list> /// /// Returns /// <list type="table"> /// <listheader><term>name</term><description>description</description></listheader> /// <item><term>success</term> /// <description>true or false</description></item> /// </list> /// </remarks> public object SaveOARHandler(IList args, IPEndPoint remoteClient) { m_admin.CheckSessionValid(new UUID((string)args[0])); Scene scene; if (!m_app.SceneManager.TryGetScene((string)args[1], out scene)) throw new Exception("region not found"); String filename = (string)args[2]; bool storeAssets = Convert.ToBoolean(args[3]); m_log.Info("[RADMIN]: Received Save OAR Administrator Request"); lock (rslock) { try { IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>(); if (archiver != null) archiver.ArchiveRegion(filename, storeAssets); else throw new Exception("Archiver module not present for scene"); m_log.Info("[RADMIN]: Save OAR Administrator Request complete"); return true; } catch (Exception e) { m_log.InfoFormat("[RADMIN] LoadOAR: {0}", e.Message); m_log.DebugFormat("[RADMIN] LoadOAR: {0}", e.ToString()); } return false; } } /// <summary> /// Load an OAR file into a region.. /// <summary> /// <param name="request">incoming XML RPC request</param> /// <remarks> /// XmlRpcLoadOARMethod takes the following XMLRPC parameters /// <list type="table"> /// <listheader><term>parameter name</term><description>description</description></listheader> /// <item><term>session</term> /// <description>An authenticated session ID</description></item> /// <item><term>region_uuid</term> /// <description>UUID of the region</description></item> /// <item><term>filename</term> /// <description>file name of the OAR file</description></item> /// </list> /// /// Returns /// <list type="table"> /// <listheader><term>name</term><description>description</description></listheader> /// <item><term>success</term> /// <description>true or false</description></item> /// </list> /// </remarks> public object RegionBackupHandler(IList args, IPEndPoint remoteClient) { m_admin.CheckSessionValid(new UUID((string)args[0])); String regionName = (string)args[1]; String filename = (string)args[2]; bool storeAssets = Convert.ToBoolean(args[3]); m_log.Info("[RADMIN]: Received Region Backup (SaveExplicitOAR) Administrator Request"); lock (rslock) { try { m_app.SceneManager.SaveExplicitOar(regionName, filename, storeAssets); m_log.Info("[RADMIN]: Save OAR Administrator Request complete"); return true; } catch (Exception e) { m_log.ErrorFormat("[RADMIN] SaveOAR: {0}", e.ToString()); } return false; } } /// <summary> /// Load an OAR file into a region.. /// <summary> /// <param name="request">incoming XML RPC request</param> /// <remarks> /// XmlRpcLoadOARMethod takes the following XMLRPC parameters /// <list type="table"> /// <listheader><term>parameter name</term><description>description</description></listheader> /// <item><term>session</term> /// <description>An authenticated session ID</description></item> /// <item><term>region_uuid</term> /// <description>UUID of the region</description></item> /// <item><term>filename</term> /// <description>file name of the OAR file</description></item> /// </list> /// /// Returns /// <list type="table"> /// <listheader><term>name</term><description>description</description></listheader> /// <item><term>success</term> /// <description>true or false</description></item> /// </list> /// </remarks> public object RegionRestoreHandler(IList args, IPEndPoint remoteClient) { m_admin.CheckSessionValid(new UUID((string)args[0])); Scene scene; if (!m_app.SceneManager.TryGetScene((string)args[1], out scene)) throw new Exception("region not found"); String filename = (string)args[2]; bool allowUserReassignment = Convert.ToBoolean(args[3]); bool skipErrorGroups = Convert.ToBoolean(args[4]); m_log.Info("[RADMIN]: Received Region Restore Administrator Request"); lock (rslock) { try { IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>(); if (archiver != null) archiver.DearchiveRegion(filename, allowUserReassignment, skipErrorGroups); else throw new Exception("Archiver module not present for scene"); m_log.Info("[RADMIN]: Load OAR Administrator Request complete"); return true; } catch (Exception e) { m_log.InfoFormat("[RADMIN] LoadOAR: {0}", e.Message); m_log.DebugFormat("[RADMIN] LoadOAR: {0}", e.ToString()); } return false; } } /// <summary> /// Changes the flags for all parcels on a region /// <summary> public object RegionChangeParcelFlagsHandler(IList args, IPEndPoint remoteClient) { m_admin.CheckSessionValid(new UUID((string)args[0])); Scene scene; if (!m_app.SceneManager.TryGetScene((string)args[1], out scene)) throw new Exception("region not found"); bool enable = args[2].ToString().ToLower() == "enable"; uint mask = Convert.ToUInt32(args[3]); m_log.Info("[RADMIN]: Received Region Change Parcel Flags Request"); lock (rslock) { try { ILandChannel channel = scene.LandChannel; List<ILandObject> parcels = channel.AllParcels(); foreach (var parcel in parcels) { LandData data = parcel.landData.Copy(); if (enable) { data.Flags = data.Flags | mask; } else { data.Flags = data.Flags & ~mask; } scene.LandChannel.UpdateLandObject(parcel.landData.LocalID, data); } m_log.Info("[RADMIN]: Change Parcel Flags Request complete"); return true; } catch (Exception e) { m_log.InfoFormat("[RADMIN] ChangeParcelFlags: {0}", e.Message); m_log.DebugFormat("[RADMIN] ChangeParcelFlags: {0}", e.ToString()); } return false; } } #endregion #if false public XmlRpcResponse XmlRpcLoadHeightmapMethod(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); m_log.Info("[RADMIN]: Load height maps request started"); try { Hashtable requestData = (Hashtable)request.Params[0]; m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}", request.ToString()); // foreach (string k in requestData.Keys) // { // m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}: >{1}< {2}", // k, (string)requestData[k], ((string)requestData[k]).Length); // } checkStringParameters(request, new string[] { "password", "filename", "regionid" }); if (m_requiredPassword != String.Empty && (!requestData.Contains("password") || (string)requestData["password"] != m_requiredPassword)) throw new Exception("wrong password"); string file = (string)requestData["filename"]; UUID regionID = (UUID)(string)requestData["regionid"]; m_log.InfoFormat("[RADMIN]: Terrain Loading: {0}", file); responseData["accepted"] = true; Scene region = null; if (!m_app.SceneManager.TryGetScene(regionID, out region)) throw new Exception("1: unable to get a scene with that name"); ITerrainModule terrainModule = region.RequestModuleInterface<ITerrainModule>(); if (null == terrainModule) throw new Exception("terrain module not available"); terrainModule.LoadFromFile(file); responseData["success"] = false; response.Value = responseData; } catch (Exception e) { m_log.ErrorFormat("[RADMIN] Terrain Loading: failed: {0}", e.Message); m_log.DebugFormat("[RADMIN] Terrain Loading: failed: {0}", e.ToString()); responseData["success"] = false; responseData["error"] = e.Message; } m_log.Info("[RADMIN]: Load height maps request complete"); return response; } /// <summary> /// Create a new region. /// <summary> /// <param name="request">incoming XML RPC request</param> /// <remarks> /// XmlRpcCreateRegionMethod takes the following XMLRPC /// parameters /// <list type="table"> /// <listheader><term>parameter name</term><description>description</description></listheader> /// <item><term>password</term> /// <description>admin password as set in OpenSim.ini</description></item> /// <item><term>region_name</term> /// <description>desired region name</description></item> /// <item><term>region_id</term> /// <description>(optional) desired region UUID</description></item> /// <item><term>region_x</term> /// <description>desired region X coordinate (integer)</description></item> /// <item><term>region_y</term> /// <description>desired region Y coordinate (integer)</description></item> /// <item><term>region_master_first</term> /// <description>firstname of region master</description></item> /// <item><term>region_master_last</term> /// <description>lastname of region master</description></item> /// <item><term>region_master_uuid</term> /// <description>explicit UUID to use for master avatar (optional)</description></item> /// <item><term>listen_ip</term> /// <description>internal IP address (dotted quad)</description></item> /// <item><term>listen_port</term> /// <description>internal port (integer)</description></item> /// <item><term>external_address</term> /// <description>external IP address</description></item> /// <item><term>persist</term> /// <description>if true, persist the region info /// ('true' or 'false')</description></item> /// <item><term>public</term> /// <description>if true, the region is public /// ('true' or 'false') (optional, default: true)</description></item> /// <item><term>enable_voice</term> /// <description>if true, enable voice on all parcels, /// ('true' or 'false') (optional, default: false)</description></item> /// </list> /// /// XmlRpcCreateRegionMethod returns /// <list type="table"> /// <listheader><term>name</term><description>description</description></listheader> /// <item><term>success</term> /// <description>true or false</description></item> /// <item><term>error</term> /// <description>error message if success is false</description></item> /// <item><term>region_uuid</term> /// <description>UUID of the newly created region</description></item> /// <item><term>region_name</term> /// <description>name of the newly created region</description></item> /// </list> /// </remarks> public XmlRpcResponse XmlRpcCreateRegionMethod(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Info("[RADMIN]: CreateRegion: new request"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); lock (rslock) { int m_regionLimit = m_config.GetInt("region_limit", 0); bool m_enableVoiceForNewRegions = m_config.GetBoolean("create_region_enable_voice", false); bool m_publicAccess = m_config.GetBoolean("create_region_public", true); try { Hashtable requestData = (Hashtable)request.Params[0]; checkStringParameters(request, new string[] { "password", "region_name", "region_master_first", "region_master_last", "region_master_password", "listen_ip", "external_address" }); checkIntegerParams(request, new string[] { "region_x", "region_y", "listen_port" }); // check password if (!String.IsNullOrEmpty(m_requiredPassword) && (string)requestData["password"] != m_requiredPassword) throw new Exception("wrong password"); // check whether we still have space left (iff we are using limits) if (m_regionLimit != 0 && m_app.SceneManager.Scenes.Count >= m_regionLimit) throw new Exception(String.Format("cannot instantiate new region, server capacity {0} already reached; delete regions first", m_regionLimit)); // extract or generate region ID now Scene scene = null; UUID regionID = UUID.Zero; if (requestData.ContainsKey("region_id") && !String.IsNullOrEmpty((string)requestData["region_id"])) { regionID = (UUID)(string)requestData["region_id"]; if (m_app.SceneManager.TryGetScene(regionID, out scene)) throw new Exception( String.Format("region UUID already in use by region {0}, UUID {1}, <{2},{3}>", scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY)); } else { regionID = UUID.Random(); m_log.DebugFormat("[RADMIN] CreateRegion: new region UUID {0}", regionID); } // create volatile or persistent region info RegionInfo region = new RegionInfo(); region.RegionID = regionID; region.RegionName = (string)requestData["region_name"]; region.RegionLocX = Convert.ToUInt32(requestData["region_x"]); region.RegionLocY = Convert.ToUInt32(requestData["region_y"]); // check for collisions: region name, region UUID, // region location if (m_app.SceneManager.TryGetScene(region.RegionName, out scene)) throw new Exception( String.Format("region name already in use by region {0}, UUID {1}, <{2},{3}>", scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY)); if (m_app.SceneManager.TryGetScene(region.RegionLocX, region.RegionLocY, out scene)) throw new Exception( String.Format("region location <{0},{1}> already in use by region {2}, UUID {3}, <{4},{5}>", region.RegionLocX, region.RegionLocY, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY)); region.InternalEndPoint = new IPEndPoint(IPAddress.Parse((string)requestData["listen_ip"]), 0); region.InternalEndPoint.Port = Convert.ToInt32(requestData["listen_port"]); if (0 == region.InternalEndPoint.Port) throw new Exception("listen_port is 0"); if (m_app.SceneManager.TryGetScene(region.InternalEndPoint, out scene)) throw new Exception( String.Format( "region internal IP {0} and port {1} already in use by region {2}, UUID {3}, <{4},{5}>", region.InternalEndPoint.Address, region.InternalEndPoint.Port, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY)); region.ExternalHostName = (string)requestData["external_address"]; string masterFirst = (string)requestData["region_master_first"]; string masterLast = (string)requestData["region_master_last"]; string masterPassword = (string)requestData["region_master_password"]; UUID userID = UUID.Zero; if (requestData.ContainsKey("region_master_uuid")) { // ok, client wants us to use an explicit UUID // regardless of what the avatar name provided userID = new UUID((string)requestData["region_master_uuid"]); } else { // no client supplied UUID: look it up... CachedUserInfo userInfo = m_app.CommunicationsManager.UserProfileCacheService.GetUserDetails( masterFirst, masterLast); if (null == userInfo) { m_log.InfoFormat("master avatar does not exist, creating it"); // ...or create new user userID = m_app.CommunicationsManager.UserAdminService.AddUser( masterFirst, masterLast, masterPassword, "", region.RegionLocX, region.RegionLocY); if (userID == UUID.Zero) throw new Exception(String.Format("failed to create new user {0} {1}", masterFirst, masterLast)); } else { userID = userInfo.UserProfile.ID; } } region.MasterAvatarFirstName = masterFirst; region.MasterAvatarLastName = masterLast; region.MasterAvatarSandboxPassword = masterPassword; region.MasterAvatarAssignedUUID = userID; bool persist = Convert.ToBoolean((string)requestData["persist"]); if (persist) { // default place for region XML files is in the // Regions directory of the config dir (aka /bin) string regionConfigPath = Path.Combine(Util.configDir(), "Regions"); try { // OpenSim.ini can specify a different regions dir IConfig startupConfig = (IConfig)m_configSource.Configs["Startup"]; regionConfigPath = startupConfig.GetString("regionload_regionsdir", regionConfigPath).Trim(); } catch (Exception) { // No INI setting recorded. } string regionXmlPath = Path.Combine(regionConfigPath, String.Format( m_config.GetString("region_file_template", "{0}x{1}-{2}.xml"), region.RegionLocX.ToString(), region.RegionLocY.ToString(), regionID.ToString(), region.InternalEndPoint.Port.ToString(), region.RegionName.Replace(" ", "_").Replace(":", "_"). Replace("/", "_"))); m_log.DebugFormat("[RADMIN] CreateRegion: persisting region {0} to {1}", region.RegionID, regionXmlPath); region.SaveRegionToFile("dynamic region", regionXmlPath); } // Create the region and perform any initial initialization IScene newscene; m_app.CreateRegion(region, out newscene); // If an access specification was provided, use it. // Otherwise accept the default. newscene.RegionInfo.EstateSettings.PublicAccess = getBoolean(requestData, "public", m_publicAccess); // enable voice on newly created region if // requested by either the XmlRpc request or the // configuration if (getBoolean(requestData, "enable_voice", m_enableVoiceForNewRegions)) { List<ILandObject> parcels = ((Scene)newscene).LandChannel.AllParcels(); foreach (ILandObject parcel in parcels) { parcel.landData.Flags |= (uint)ParcelFlags.AllowVoiceChat; parcel.landData.Flags |= (uint)ParcelFlags.UseEstateVoiceChan; } } responseData["success"] = true; responseData["region_name"] = region.RegionName; responseData["region_uuid"] = region.RegionID.ToString(); response.Value = responseData; } catch (Exception e) { m_log.ErrorFormat("[RADMIN] CreateRegion: failed {0}", e.Message); m_log.DebugFormat("[RADMIN] CreateRegion: failed {0}", e.ToString()); responseData["success"] = false; responseData["error"] = e.Message; response.Value = responseData; } m_log.Info("[RADMIN]: CreateRegion: request complete"); return response; } } /// <summary> /// Delete a new region. /// <summary> /// <param name="request">incoming XML RPC request</param> /// <remarks> /// XmlRpcDeleteRegionMethod takes the following XMLRPC /// parameters /// <list type="table"> /// <listheader><term>parameter name</term><description>description</description></listheader> /// <item><term>password</term> /// <description>admin password as set in OpenSim.ini</description></item> /// <item><term>region_name</term> /// <description>desired region name</description></item> /// <item><term>region_id</term> /// <description>(optional) desired region UUID</description></item> /// </list> /// /// XmlRpcDeleteRegionMethod returns /// <list type="table"> /// <listheader><term>name</term><description>description</description></listheader> /// <item><term>success</term> /// <description>true or false</description></item> /// <item><term>error</term> /// <description>error message if success is false</description></item> /// </list> /// </remarks> public XmlRpcResponse XmlRpcDeleteRegionMethod(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Info("[RADMIN]: DeleteRegion: new request"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); lock (rslock) { try { Hashtable requestData = (Hashtable)request.Params[0]; checkStringParameters(request, new string[] { "password", "region_name" }); Scene scene = null; string regionName = (string)requestData["region_name"]; if (!m_app.SceneManager.TryGetScene(regionName, out scene)) throw new Exception(String.Format("region \"{0}\" does not exist", regionName)); m_app.RemoveRegion(scene, true); responseData["success"] = true; responseData["region_name"] = regionName; response.Value = responseData; } catch (Exception e) { m_log.ErrorFormat("[RADMIN] DeleteRegion: failed {0}", e.Message); m_log.DebugFormat("[RADMIN] DeleteRegion: failed {0}", e.ToString()); responseData["success"] = false; responseData["error"] = e.Message; response.Value = responseData; } m_log.Info("[RADMIN]: DeleteRegion: request complete"); return response; } } /// <summary> /// Change characteristics of an existing region. /// <summary> /// <param name="request">incoming XML RPC request</param> /// <remarks> /// XmlRpcModifyRegionMethod takes the following XMLRPC /// parameters /// <list type="table"> /// <listheader><term>parameter name</term><description>description</description></listheader> /// <item><term>password</term> /// <description>admin password as set in OpenSim.ini</description></item> /// <item><term>region_name</term> /// <description>desired region name</description></item> /// <item><term>region_id</term> /// <description>(optional) desired region UUID</description></item> /// <item><term>public</term> /// <description>if true, set the region to public /// ('true' or 'false'), else to private</description></item> /// <item><term>enable_voice</term> /// <description>if true, enable voice on all parcels of /// the region, else disable</description></item> /// </list> /// /// XmlRpcModifyRegionMethod returns /// <list type="table"> /// <listheader><term>name</term><description>description</description></listheader> /// <item><term>success</term> /// <description>true or false</description></item> /// <item><term>error</term> /// <description>error message if success is false</description></item> /// </list> /// </remarks> public XmlRpcResponse XmlRpcModifyRegionMethod(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Info("[RADMIN]: ModifyRegion: new request"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); lock (rslock) { try { Hashtable requestData = (Hashtable)request.Params[0]; checkStringParameters(request, new string[] { "password", "region_name" }); Scene scene = null; string regionName = (string)requestData["region_name"]; if (!m_app.SceneManager.TryGetScene(regionName, out scene)) throw new Exception(String.Format("region \"{0}\" does not exist", regionName)); // Modify access scene.RegionInfo.EstateSettings.PublicAccess = getBoolean(requestData, "public", scene.RegionInfo.EstateSettings.PublicAccess); if (requestData.ContainsKey("enable_voice")) { bool enableVoice = getBoolean(requestData, "enable_voice", true); List<ILandObject> parcels = ((Scene)scene).LandChannel.AllParcels(); foreach (ILandObject parcel in parcels) { if (enableVoice) { parcel.landData.Flags |= (uint)ParcelFlags.AllowVoiceChat; parcel.landData.Flags |= (uint)ParcelFlags.UseEstateVoiceChan; } else { parcel.landData.Flags &= ~(uint)ParcelFlags.AllowVoiceChat; parcel.landData.Flags &= ~(uint)ParcelFlags.UseEstateVoiceChan; } } } responseData["success"] = true; responseData["region_name"] = regionName; response.Value = responseData; } catch (Exception e) { m_log.ErrorFormat("[RADMIN] ModifyRegion: failed {0}", e.Message); m_log.DebugFormat("[RADMIN] ModifyRegion: failed {0}", e.ToString()); responseData["success"] = false; responseData["error"] = e.Message; response.Value = responseData; } m_log.Info("[RADMIN]: ModifyRegion: request complete"); return response; } } #endif } }
namespace Microsoft.Protocols.TestSuites.MS_OXORULE { using System; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// A folder entry id structure. /// </summary> public class FolderEntryID { /// <summary> /// MUST be zero. /// </summary> private byte[] flag = new byte[] { 0x00, 0x00, 0x00, 0x00 }; /// <summary> /// For a folder in a private mailbox MUST be set to the MailboxGuid field value from the RopLogon /// </summary> private byte[] providerUID = new byte[16]; /// <summary> /// Specify the folder type, 0x0001 means private folder. /// </summary> private byte[] folderType = new byte[2]; /// <summary> /// A GUID associated with the Store object, and corresponding to the ReplicaId field of the FID. /// </summary> private byte[] dataBaseGUID = new byte[16]; /// <summary> /// An unsigned 48-bit integer identifying the folder. /// </summary> private byte[] globalCounter = new byte[6]; /// <summary> /// MUST be zero. /// </summary> private byte[] pad = new byte[] { 0x00, 0x00 }; /// <summary> /// Initializes a new instance of the FolderEntryID class. /// </summary> /// <param name="objectType">Identify store object is a mailbox or a public folder.</param> /// <param name="providerUID">Provider id value which can get in logon response.</param> /// <param name="databaseGUID">DatabaseGUID of specific folder, which can get in folder's longterm id.</param> /// <param name="globalCounter">Global counter of specific folder, which can get in folder's longterm id.</param> public FolderEntryID(StoreObjectType objectType, byte[] providerUID, byte[] databaseGUID, byte[] globalCounter) { this.providerUID = providerUID; this.dataBaseGUID = databaseGUID; this.globalCounter = globalCounter; if (objectType == StoreObjectType.Mailbox) { this.folderType = new byte[] { 0x01, 0x00 }; } else { this.folderType = new byte[] { 0x03, 0x00 }; } } /// <summary> /// Initializes a new instance of the FolderEntryID class. /// </summary> /// <param name="objectType">Identify store object is a mailbox or a public folder.</param> public FolderEntryID(StoreObjectType objectType) { if (objectType == StoreObjectType.Mailbox) { this.folderType = new byte[] { 0x01, 0x00 }; } else { this.folderType = new byte[] { 0x03, 0x00 }; } } /// <summary> /// Gets or sets an unsigned 48-bit integer identifying the folder. /// </summary> public byte[] GlobalCounter { get { return this.globalCounter; } set { this.globalCounter = value; } } /// <summary> /// Gets or sets a GUID associated with the Store object, and corresponding to the ReplicaId field of the FID. /// </summary> public byte[] DataBaseGUID { get { return this.dataBaseGUID; } set { this.dataBaseGUID = value; } } /// <summary> /// Gets or sets ProviderUID that for a folder in a private mailbox MUST be set to the MailboxGuid field value from the RopLogon /// </summary> public byte[] ProviderUID { get { return this.providerUID; } set { this.providerUID = value; } } /// <summary> /// Gets or sets Pad that MUST be zero. /// </summary> public byte[] Pad { get { return this.pad; } set { this.pad = value; } } /// <summary> /// Gets or sets Flag that MUST be zero. /// </summary> public byte[] Flag { get { return this.flag; } set { this.flag = value; } } /// <summary> /// Gets or sets the folder type, 0x0001 means private folder. /// </summary> public byte[] FolderType { get { return this.folderType; } set { this.folderType = value; } } /// <summary> /// Get folder entry id bytes array. /// </summary> /// <returns>Bytes array of folder entry id.</returns> public byte[] Serialize() { byte[] value = new byte[46]; int index = 0; Array.Copy(this.flag, 0, value, index, this.flag.Length); index += this.flag.Length; Array.Copy(this.providerUID, 0, value, index, this.providerUID.Length); index += this.providerUID.Length; Array.Copy(this.folderType, 0, value, index, this.folderType.Length); index += this.folderType.Length; Array.Copy(this.dataBaseGUID, 0, value, index, this.dataBaseGUID.Length); index += this.dataBaseGUID.Length; Array.Copy(this.globalCounter, 0, value, index, this.globalCounter.Length); index += this.globalCounter.Length; Array.Copy(this.pad, 0, value, index, this.pad.Length); return value; } /// <summary> /// Deserialize FolderEntryID. /// </summary> /// <param name="buffer">Entry id data array.</param> public void Deserialize(byte[] buffer) { BufferReader reader = new BufferReader(buffer); byte[] currentFlag = reader.ReadBytes(4); if (!Common.CompareByteArray(currentFlag, this.flag)) { if (currentFlag != null) { string errorMessage = "Wrong flag error, the expect flag is { 0x00, 0x00, 0x00, 0x00}, actual is " + currentFlag.ToString() + "!"; throw new ArgumentException(errorMessage); } else { string errorMessage = "Wrong flag error, the expect flag is { 0x00, 0x00, 0x00, 0x00}, actual is null!"; throw new ArgumentException(errorMessage); } } this.providerUID = reader.ReadBytes(16); byte[] currentFolderType = reader.ReadBytes(2); if (!Common.CompareByteArray(currentFolderType, this.folderType)) { if (currentFlag != null) { string errorMessage = "Wrong folder type error, the expect folder type is " + this.folderType.ToString() + ", the actual is " + currentFolderType.ToString() + "!"; throw new ArgumentException(errorMessage); } else { string errorMessage = "Wrong folder type error, the expect folder type is " + this.folderType.ToString() + ", actual is null!"; throw new ArgumentException(errorMessage); } } this.dataBaseGUID = reader.ReadBytes(16); this.globalCounter = reader.ReadBytes(6); byte[] currentPad = reader.ReadBytes(2); if (!Common.CompareByteArray(currentPad, this.pad)) { if (currentFlag != null) { string errorMessage = "Wrong pad data, the expect pad data is " + this.pad.ToString() + ", the actual is " + currentPad.ToString() + "!"; throw new Exception(errorMessage); } else { string errorMessage = "Wrong pad data, the expect pad data is " + this.pad.ToString() + ", actual is null!"; throw new Exception(errorMessage); } } } } }
/*- * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * See the file LICENSE for license information. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Xml; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class LockTest : CSharpTestFixture { DatabaseEnvironment testLockStatsEnv; BTreeDatabase testLockStatsDb; int DeadlockDidPut = 0; [TestFixtureSetUp] public void SetUpTestFixture() { testFixtureName = "LockTest"; base.SetUpTestfixture(); } [Test] public void TestLockStats() { testName = "TestLockStats"; SetUpTest(true); // Configure locking subsystem. LockingConfig lkConfig = new LockingConfig(); lkConfig.MaxLockers = 60; lkConfig.MaxLocks = 50; lkConfig.MaxObjects = 70; lkConfig.Partitions = 20; lkConfig.DeadlockResolution = DeadlockPolicy.DEFAULT; // Configure and open environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.FreeThreaded = true; envConfig.LockSystemCfg = lkConfig; envConfig.LockTimeout = 1000; envConfig.MPoolSystemCfg = new MPoolConfig(); envConfig.MPoolSystemCfg.CacheSize = new CacheInfo(0, 104800, 1); envConfig.NoLocking = false; envConfig.TxnTimeout = 2000; envConfig.UseLocking = true; envConfig.UseMPool = true; envConfig.UseTxns = true; DatabaseEnvironment env = DatabaseEnvironment.Open(testHome, envConfig); // Get and confirm locking subsystem statistics. LockStats stats = env.LockingSystemStats(); env.Msgfile = testHome + "/" + testName+ ".log"; env.PrintLockingSystemStats(true, true); Assert.AreEqual(0, stats.AllocatedLockers); Assert.AreNotEqual(0, stats.AllocatedLocks); Assert.AreNotEqual(0, stats.AllocatedObjects); Assert.AreEqual(0, stats.InitLockers); Assert.AreNotEqual(0, stats.InitLocks); Assert.AreNotEqual(0, stats.InitObjects); Assert.AreEqual(0, stats.LastAllocatedLockerID); Assert.AreEqual(0, stats.LockConflictsNoWait); Assert.AreEqual(0, stats.LockConflictsWait); Assert.AreEqual(0, stats.LockDeadlocks); Assert.AreEqual(0, stats.LockDowngrades); Assert.AreEqual(0, stats.LockerNoWait); Assert.AreEqual(0, stats.Lockers); Assert.AreEqual(0, stats.LockerWait); Assert.AreEqual(9, stats.LockModes); Assert.AreEqual(0, stats.LockPuts); Assert.AreEqual(0, stats.LockRequests); Assert.AreEqual(0, stats.Locks); Assert.AreEqual(0, stats.LockSteals); Assert.AreEqual(1000, stats.LockTimeoutLength); Assert.AreEqual(0, stats.LockTimeouts); Assert.AreEqual(0, stats.LockUpgrades); Assert.AreEqual(0, stats.MaxBucketLength); Assert.AreEqual(0, stats.MaxLockers); Assert.AreEqual(60, stats.MaxLockersInTable); Assert.AreEqual(0, stats.MaxLocks); Assert.AreEqual(0, stats.MaxLocksInBucket); Assert.AreEqual(50, stats.MaxLocksInTable); Assert.AreEqual(0, stats.MaxLockSteals); Assert.AreEqual(0, stats.MaxObjects); Assert.AreEqual(0, stats.MaxObjectsInBucket); Assert.AreEqual(70, stats.MaxObjectsInTable); Assert.AreEqual(0, stats.MaxObjectSteals); Assert.AreEqual(0, stats.MaxPartitionLockNoWait); Assert.AreEqual(0, stats.MaxPartitionLockWait); Assert.AreNotEqual(0, stats.MaxUnusedID); Assert.AreEqual(20, stats.nPartitions); Assert.AreEqual(0, stats.ObjectNoWait); Assert.AreEqual(0, stats.Objects); Assert.AreEqual(0, stats.ObjectSteals); Assert.AreEqual(0, stats.ObjectWait); Assert.LessOrEqual(0, stats.PartitionLockNoWait); Assert.AreEqual(0, stats.PartitionLockWait); Assert.Less(0, stats.RegionNoWait); Assert.AreNotEqual(0, stats.RegionSize); Assert.AreEqual(0, stats.RegionWait); Assert.AreNotEqual(0, stats.TableSize); Assert.AreEqual(2000, stats.TxnTimeoutLength); Assert.AreEqual(0, stats.TxnTimeouts); env.PrintLockingSystemStats(); Transaction txn = env.BeginTransaction(); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; dbConfig.FreeThreaded = true; BTreeDatabase db = BTreeDatabase.Open( testName + ".db", dbConfig, txn); txn.Commit(); testLockStatsEnv = env; testLockStatsDb = db; // Use some locks, to ensure the stats work when populated. txn = testLockStatsEnv.BeginTransaction(); for (int i = 0; i < 500; i++) { testLockStatsDb.Put( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes( Configuration.RandomString(i))), txn); testLockStatsDb.Sync(); } txn.Commit(); env.PrintLockingSystemStats(); stats = env.LockingSystemStats(); Assert.Less(0, stats.LastAllocatedLockerID); Assert.Less(0, stats.LockDowngrades); Assert.LessOrEqual(0, stats.LockerNoWait); Assert.Less(0, stats.Lockers); Assert.LessOrEqual(0, stats.LockerWait); Assert.Less(0, stats.LockPuts); Assert.Less(0, stats.LockRequests); Assert.Less(0, stats.Locks); Assert.LessOrEqual(0, stats.LockSteals); Assert.LessOrEqual(0, stats.LockTimeouts); Assert.LessOrEqual(0, stats.LockUpgrades); Assert.Less(0, stats.MaxBucketLength); Assert.Less(0, stats.MaxLockers); Assert.Less(0, stats.MaxLocks); Assert.Less(0, stats.MaxLocksInBucket); Assert.LessOrEqual(0, stats.MaxLockSteals); Assert.Less(0, stats.MaxObjects); Assert.Less(0, stats.MaxObjectsInBucket); Assert.LessOrEqual(0, stats.MaxObjectSteals); Assert.LessOrEqual(0, stats.MaxPartitionLockNoWait); Assert.LessOrEqual(0, stats.MaxPartitionLockWait); Assert.Less(0, stats.MaxUnusedID); Assert.LessOrEqual(0, stats.ObjectNoWait); Assert.Less(0, stats.Objects); Assert.LessOrEqual(0, stats.ObjectSteals); Assert.LessOrEqual(0, stats.ObjectWait); Assert.Less(0, stats.PartitionLockNoWait); Assert.LessOrEqual(0, stats.PartitionLockWait); Assert.Less(0, stats.RegionNoWait); Assert.LessOrEqual(0, stats.RegionWait); Assert.LessOrEqual(0, stats.TxnTimeouts); // Force a deadlock to ensure the stats work. txn = testLockStatsEnv.BeginTransaction(); testLockStatsDb.Put(new DatabaseEntry(BitConverter.GetBytes(10)), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes( Configuration.RandomString(200))), txn); Thread thread1 = new Thread(GenerateDeadlock); thread1.Start(); while (DeadlockDidPut == 0) Thread.Sleep(10); try { testLockStatsDb.Get(new DatabaseEntry( BitConverter.GetBytes(100)), txn); } catch (DeadlockException) { } // Abort unconditionally - we don't care about the transaction txn.Abort(); thread1.Join(); stats = env.LockingSystemStats(); Assert.Less(0, stats.LockConflictsNoWait); Assert.LessOrEqual(0, stats.LockConflictsWait); db.Close(); env.Close(); } [Test] public void TestLockStatPrint() { testName = "TestLockStatPrint"; SetUpTest(true); string[] messageInfo = new string[] { "Last allocated locker ID", "Current maximum unused locker ID", "Number of lock modes", "Initial number of locks allocated", "Initial number of lockers allocated", "Initial number of lock objects allocated", "Maximum number of locks possible", "Maximum number of lockers possible", "Maximum number of lock objects possible", "Current number of locks allocated", "Current number of lockers allocated", "Current number of lock objects allocated", "Number of lock object partitions", "Size of object hash table", "Number of current locks", "Maximum number of locks at any one time", "Maximum number of locks in any one bucket", "Maximum number of locks stolen by for an empty partition", "Maximum number of locks stolen for any one partition", "Number of current lockers", "Maximum number of lockers at any one time", "Number of hits in the thread locker cache", "Total number of lockers reused", "Number of current lock objects", "Maximum number of lock objects at any one time", "Maximum number of lock objects in any one bucket", "Maximum number of objects stolen by for an empty partition", "Maximum number of objects stolen for any one partition", "Total number of locks requested", "Total number of locks released", "Total number of locks upgraded", "Total number of locks downgraded", "Lock requests not available due to conflicts, for which we waited", "Lock requests not available due to conflicts, for which we did not wait", "Number of deadlocks", "Lock timeout value", "Number of locks that have timed out", "Transaction timeout value", "Number of transactions that have timed out", "Region size", "The number of partition locks that required waiting (0%)", "The maximum number of times any partition lock was waited for (0%)", "The number of object queue operations that required waiting (0%)", "The number of locker allocations that required waiting (0%)", "The number of region locks that required waiting (0%)", "Maximum hash bucket length" }; // Configure locking subsystem. LockingConfig lkConfig = new LockingConfig(); lkConfig.MaxLockers = 60; lkConfig.MaxLocks = 50; lkConfig.MaxObjects = 70; lkConfig.Partitions = 20; lkConfig.DeadlockResolution = DeadlockPolicy.DEFAULT; // Configure and open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.LockSystemCfg = lkConfig; envConfig.LockTimeout = 1000; envConfig.NoLocking = false; envConfig.UseLocking = true; DatabaseEnvironment env = DatabaseEnvironment.Open(testHome, envConfig); // Confirm message file does not exist. string messageFile = testHome + "/" + "msgfile"; Assert.AreEqual(false, File.Exists(messageFile)); // Call set_msgfile() of env. env.Msgfile = messageFile; // Print env statistic to message file. env.PrintLockingSystemStats(); // Confirm message file exists now. Assert.AreEqual(true, File.Exists(messageFile)); env.Msgfile = ""; int counter = 0; string line; line = null; // Read the message file line by line. System.IO.StreamReader file = new System.IO.StreamReader(@"" + messageFile); while ((line = file.ReadLine()) != null) { string[] tempStr = line.Split('\t'); // Confirm the content of the message file. Assert.AreEqual(tempStr[1], messageInfo[counter]); counter++; } Assert.AreNotEqual(counter, 0); file.Close(); env.Close(); } public void GenerateDeadlock() { Transaction txn = testLockStatsEnv.BeginTransaction(); try { testLockStatsDb.Put( new DatabaseEntry(BitConverter.GetBytes(100)), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes( Configuration.RandomString(200))), txn); DeadlockDidPut = 1; testLockStatsDb.Get(new DatabaseEntry( BitConverter.GetBytes(10)), txn); } catch (DeadlockException) { } // Abort unconditionally - we don't care about the transaction txn.Abort(); } public static void LockingEnvSetUp(string testHome, string testName, out DatabaseEnvironment env, uint maxLock, uint maxLocker, uint maxObject, uint partition) { // Configure env and locking subsystem. LockingConfig lkConfig = new LockingConfig(); /* * If the maximum number of locks/lockers/objects * is given, then the LockingConfig is set. Unless, * it is not set to any value. */ if (maxLock != 0) lkConfig.MaxLocks = maxLock; if (maxLocker != 0) lkConfig.MaxLockers = maxLocker; if (maxObject != 0) lkConfig.MaxObjects = maxObject; if (partition != 0) lkConfig.Partitions = partition; DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.LockSystemCfg = lkConfig; envConfig.UseLocking = true; envConfig.ErrorPrefix = testName; env = DatabaseEnvironment.Open(testHome, envConfig); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using Gallio.Common; using Gallio.Model; using Gallio.Common.Reflection; using Gallio.Model.Schema; using Gallio.ReSharperRunner.Provider.Facade; using Gallio.ReSharperRunner.Reflection; using JetBrains.ProjectModel; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Tree; using JetBrains.ReSharper.TaskRunnerFramework.UnitTesting; using JetBrains.ReSharper.UnitTestFramework; using JetBrains.ReSharper.TaskRunnerFramework; namespace Gallio.ReSharperRunner.Provider.TestElements { /// <summary> /// Represents a Gallio test. /// </summary> public class GallioTestElement : GallioTestElementBase, IUnitTestViewElement { private readonly string testName; private readonly string testId; private readonly string kind; private readonly bool isTestCase; private readonly IProject project; private readonly IDeclaredElementResolver declaredElementResolver; private readonly string assemblyPath; private readonly string typeName; private readonly string namespaceName; private Memoizer<string> shortNameMemoizer; protected GallioTestElement(IUnitTestProvider provider, GallioTestElement parent, string testId, string testName, string kind, bool isTestCase, IProject project, IDeclaredElementResolver declaredElementResolver, string assemblyPath, string typeName, string namespaceName) : base(provider, testId, parent) { this.testId = testId; this.testName = testName; this.kind = kind; this.isTestCase = isTestCase; this.project = project; this.declaredElementResolver = declaredElementResolver; this.assemblyPath = assemblyPath; this.typeName = typeName; this.namespaceName = namespaceName; } public static GallioTestElement CreateFromTest(TestData test, ICodeElementInfo codeElement, IUnitTestProvider provider, GallioTestElement parent) { if (test == null) throw new ArgumentNullException("test"); // The idea here is to generate a test element object that does not retain any direct // references to the code element info and other heavyweight objects. A test element may // survive in memory for quite a long time so we don't want it holding on to all sorts of // irrelevant stuff. Basically we flatten out the test to just those properties that we // need to keep. var element = new GallioTestElement(provider, parent, test.Id, test.Name, test.Metadata.GetValue(MetadataKeys.TestKind) ?? "Unknown", test.IsTestCase, ReSharperReflectionPolicy.GetProject(codeElement), ReSharperReflectionPolicy.GetDeclaredElementResolver(codeElement), GetAssemblyPath(codeElement), GetTypeName(codeElement), GetNamespaceName(codeElement)); var categories = test.Metadata[MetadataKeys.Category]; if (categories.Count != 0) element.Categories = UnitTestElementCategory.Create(categories); var reason = test.Metadata.GetValue(MetadataKeys.IgnoreReason); if (reason != null) element.ExplicitReason = reason; return element; } private static string GetAssemblyPath(ICodeElementInfo codeElement) { IAssemblyInfo assembly = ReflectionUtils.GetAssembly(codeElement); return assembly != null ? assembly.Path : null; } private static string GetTypeName(ICodeElementInfo codeElement) { ITypeInfo type = ReflectionUtils.GetType(codeElement); return type != null ? type.FullName : ""; } private static string GetNamespaceName(ICodeElementInfo codeElement) { INamespaceInfo @namespace = ReflectionUtils.GetNamespace(codeElement); return @namespace != null ? @namespace.Name : ""; } public string GetAssemblyLocation() { return assemblyPath; } public string TestName { get { return testName; } } public override void Invalidate() { Valid = false; } public override IList<UnitTestTask> GetTaskSequence(IEnumerable<IUnitTestElement> explicitElements) { IList<UnitTestTask> testTasks; if (Parent != null) { testTasks = Parent.GetTaskSequence(explicitElements); testTasks.Add(new UnitTestTask(this, FacadeTaskFactory.CreateTestTaskFrom(this))); } else { testTasks = new List<UnitTestTask>(); // Add the run task. Must always be first. testTasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateRootTask())); testTasks.Add(new UnitTestTask(null, new AssemblyLoadTask(GetAssemblyLocation()))); if (explicitElements != null && explicitElements.Count() != 0) { // Add explicit element markers. foreach (GallioTestElement explicitElement in explicitElements) testTasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateExplicitTestTaskFrom(explicitElement))); } else { // No explicit elements but we must have at least one to filter by, so we consider // the top test explicitly selected. testTasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateExplicitTestTaskFrom(this))); } } return testTasks; } // R# uses this name as a filter for declared elements so that it can quickly determine // whether a given declared element is likely to be a test before asking the provider about // it. The result must be equal to IDeclaredElement.ShortName. public override string ShortName { get { return shortNameMemoizer.Memoize(() => { IDeclaredElement declaredElement = GetDeclaredElement(); return declaredElement != null && declaredElement.IsValid() ? declaredElement.ShortName : testName; }); } } public override bool Valid { get; set; } public string TestId { get { return testId; } } public bool IsTestCase { get { return isTestCase; } } public string GetTitle() { return testName; } public string GetTypeClrName() { return typeName; } public UnitTestNamespace GetNamespace() { return new UnitTestNamespace(namespaceName); } public IProject GetProject() { return project; } public IDeclaredElement GetDeclaredElement() { return declaredElementResolver.ResolveDeclaredElement(); } public bool Equals(GallioTestElement other) { return other != null && testId == other.testId; } public override bool Equals(IUnitTestElement other) { return Equals(other as GallioTestElement); } public bool Equals(IUnitTestViewElement other) { return Equals(other as GallioTestElement); } public override bool Equals(object obj) { return Equals(obj as GallioTestElement); } public override int GetHashCode() { return testId.GetHashCode(); } public int CompareTo(GallioTestElement other) { // Find common ancestor. var branches = new Dictionary<GallioTestElement, GallioTestElement>(); for (GallioTestElement thisAncestor = this, thisBranch = null; thisAncestor != null; thisBranch = thisAncestor, thisAncestor = thisAncestor.Parent as GallioTestElement) branches.Add(thisAncestor, thisBranch); for (GallioTestElement otherAncestor = other, otherBranch = null; otherAncestor != null; otherBranch = otherAncestor, otherAncestor = otherAncestor.Parent as GallioTestElement) { GallioTestElement thisBranch; if (branches.TryGetValue(otherAncestor, out thisBranch)) { // Compare the relative ordering of the branches leading from // the common ancestor to each child. int thisOrder = thisBranch != null ? otherAncestor.children.IndexOf(thisBranch) : -1; int otherOrder = otherBranch != null ? otherAncestor.children.IndexOf(otherBranch) : -1; return thisOrder.CompareTo(otherOrder); } } // No common ancestor, compare test ids. return testId.CompareTo(other.testId); } public int CompareTo(object obj) { GallioTestElement other = obj as GallioTestElement; return other != null ? CompareTo(other) : 1; // sort gallio test elements after all other kinds } public override string ToString() { return GetTitle(); } public UnitTestElementDisposition GetDisposition() { var element = GetDeclaredElement(); if (element == null || !element.IsValid()) return UnitTestElementDisposition.InvalidDisposition; var locations = new List<UnitTestElementLocation>(); foreach (var declaration in element.GetDeclarations()) { var file = declaration.GetContainingFile(); if (file != null) { locations.Add(new UnitTestElementLocation(file.GetSourceFile().ToProjectFile(), declaration.GetNameDocumentRange().TextRange, declaration.GetDocumentRange().TextRange)); } } return new UnitTestElementDisposition(locations, this); } public string Kind { get { return kind; } } } }
using System; using System.Threading; using Htc.Vita.Core.Log; using Htc.Vita.Core.Util; namespace Htc.Vita.Core.Net { /// <summary> /// Class NetworkManager. /// </summary> public abstract partial class NetworkManager { static NetworkManager() { TypeRegistry.RegisterDefault<NetworkManager, DefaultNetworkManager>(); } /// <summary> /// Registers the instance type. /// </summary> /// <typeparam name="T"></typeparam> public static void Register<T>() where T : NetworkManager, new() { TypeRegistry.Register<NetworkManager, T>(); } /// <summary> /// Gets the instance. /// </summary> /// <returns>NetworkManager.</returns> public static NetworkManager GetInstance() { return TypeRegistry.GetInstance<NetworkManager>(); } /// <summary> /// Gets the instance. /// </summary> /// <typeparam name="T"></typeparam> /// <returns>NetworkManager.</returns> public static NetworkManager GetInstance<T>() where T : NetworkManager, new() { return TypeRegistry.GetInstance<NetworkManager, T>(); } /// <summary> /// Gets the local port status. /// </summary> /// <param name="portNumber">The port number.</param> /// <returns>GetLocalPortStatusResult.</returns> public GetLocalPortStatusResult GetLocalPortStatus(int portNumber) { if (portNumber < 0 || portNumber > 65535) { return new GetLocalPortStatusResult { Status = GetLocalPortStatusStatus.InvalidData }; } GetLocalPortStatusResult result = null; try { result = OnGetLocalPortStatus(portNumber); } catch (Exception e) { Logger.GetInstance(typeof(NetworkManager)).Error(e.ToString()); } return result ?? new GetLocalPortStatusResult(); } /// <summary> /// Gets the network time. /// </summary> /// <returns>GetNetworkTimeResult.</returns> public GetNetworkTimeResult GetNetworkTime() { GetNetworkTimeResult result = null; try { result = OnGetNetworkTime(); } catch (Exception e) { Logger.GetInstance(typeof(NetworkManager)).Error(e.ToString()); } return result ?? new GetNetworkTimeResult(); } /// <summary> /// Gets the unused local port. /// </summary> /// <returns>GetUnusedLocalPortResult.</returns> public GetUnusedLocalPortResult GetUnusedLocalPort() { return GetUnusedLocalPort(false); } /// <summary> /// Gets the unused local port. /// </summary> /// <param name="shouldUseLastPortFirst">if set to <c>true</c> use last port first.</param> /// <returns>GetUnusedLocalPortResult.</returns> public GetUnusedLocalPortResult GetUnusedLocalPort(bool shouldUseLastPortFirst) { GetUnusedLocalPortResult result = null; try { result = OnGetUnusedLocalPort(shouldUseLastPortFirst); } catch (Exception e) { Logger.GetInstance(typeof(NetworkManager)).Error(e.ToString()); } return result ?? new GetUnusedLocalPortResult(); } /// <summary> /// Traces the route. /// </summary> /// <param name="hostNameOrIpAddress">The host name or ip address.</param> /// <returns>TraceRouteResult.</returns> public TraceRouteResult TraceRoute(string hostNameOrIpAddress) { return TraceRoute( hostNameOrIpAddress, CancellationToken.None ); } /// <summary> /// Traces the route. /// </summary> /// <param name="hostNameOrIpAddress">The host name or ip address.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>TraceRouteResult.</returns> public TraceRouteResult TraceRoute( string hostNameOrIpAddress, CancellationToken cancellationToken) { return TraceRoute( hostNameOrIpAddress, 20, 1000 * 5, cancellationToken ); } /// <summary> /// Traces the route. /// </summary> /// <param name="hostNameOrIpAddress">The host name or ip address.</param> /// <param name="maxHop">The maximum hop.</param> /// <param name="timeoutInMilli">The timeout in millisecond.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>TraceRouteResult.</returns> public TraceRouteResult TraceRoute( string hostNameOrIpAddress, int maxHop, int timeoutInMilli, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(hostNameOrIpAddress)) { return new TraceRouteResult { Status = TraceRouteStatus.InvalidData }; } if (maxHop <= 0 || timeoutInMilli <= 0) { return new TraceRouteResult { Status = TraceRouteStatus.InvalidData }; } TraceRouteResult result = null; try { result = OnTraceRoute( hostNameOrIpAddress, maxHop, timeoutInMilli, cancellationToken ); } catch (Exception e) { Logger.GetInstance(typeof(NetworkManager)).Error(e.ToString()); } return result ?? new TraceRouteResult(); } /// <summary> /// Verifies the local port status. /// </summary> /// <param name="portNumber">The port number.</param> /// <returns>VerifyLocalPortStatusResult.</returns> public VerifyLocalPortStatusResult VerifyLocalPortStatus(int portNumber) { if (portNumber < 0 || portNumber > 65535) { return new VerifyLocalPortStatusResult { Status = VerifyLocalPortStatusStatus.InvalidData }; } VerifyLocalPortStatusResult result = null; try { result = OnVerifyLocalPortStatus(portNumber); } catch (Exception e) { Logger.GetInstance(typeof(NetworkManager)).Error(e.ToString()); } return result ?? new VerifyLocalPortStatusResult(); } /// <summary> /// Called when getting local port status. /// </summary> /// <param name="portNumber">The port number.</param> /// <returns>GetLocalPortStatusResult.</returns> protected abstract GetLocalPortStatusResult OnGetLocalPortStatus(int portNumber); /// <summary> /// Called when getting network time. /// </summary> /// <returns>GetNetworkTimeResult.</returns> protected abstract GetNetworkTimeResult OnGetNetworkTime(); /// <summary> /// Called when getting unused local port. /// </summary> /// <param name="shouldUseLastPortFirst">if set to <c>true</c> use last port first.</param> /// <returns>GetUnusedLocalPortResult.</returns> protected abstract GetUnusedLocalPortResult OnGetUnusedLocalPort(bool shouldUseLastPortFirst); /// <summary> /// Called when tracing route. /// </summary> /// <param name="hostNameOrIpAddress">The host name or ip address.</param> /// <param name="maxHop">The maximum hop.</param> /// <param name="timeoutInMilli">The timeout in millisecond.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>TraceRouteResult.</returns> protected abstract TraceRouteResult OnTraceRoute( string hostNameOrIpAddress, int maxHop, int timeoutInMilli, CancellationToken cancellationToken ); /// <summary> /// Called when verifying local port status. /// </summary> /// <param name="portNumber">The port number.</param> /// <returns>VerifyLocalPortStatusResult.</returns> protected abstract VerifyLocalPortStatusResult OnVerifyLocalPortStatus(int portNumber); } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.42. // namespace WebsitePanel.Providers.DNS { using System.Diagnostics; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Xml.Serialization; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name = "DNSServerSoap", Namespace = "http://smbsaas/websitepanel/server/")] public partial class DNSServer : Microsoft.Web.Services3.WebServicesClientProtocol { public ServiceProviderSettingsSoapHeader ServiceProviderSettingsSoapHeaderValue; private System.Threading.SendOrPostCallback ZoneExistsOperationCompleted; private System.Threading.SendOrPostCallback GetZonesOperationCompleted; private System.Threading.SendOrPostCallback AddPrimaryZoneOperationCompleted; private System.Threading.SendOrPostCallback AddSecondaryZoneOperationCompleted; private System.Threading.SendOrPostCallback DeleteZoneOperationCompleted; private System.Threading.SendOrPostCallback UpdateSoaRecordOperationCompleted; private System.Threading.SendOrPostCallback GetZoneRecordsOperationCompleted; private System.Threading.SendOrPostCallback AddZoneRecordOperationCompleted; private System.Threading.SendOrPostCallback DeleteZoneRecordOperationCompleted; private System.Threading.SendOrPostCallback AddZoneRecordsOperationCompleted; private System.Threading.SendOrPostCallback DeleteZoneRecordsOperationCompleted; /// <remarks/> public DNSServer() { this.Url = "http://localhost/WebsitePanelServer11/DnsServer.asmx"; } /// <remarks/> public event ZoneExistsCompletedEventHandler ZoneExistsCompleted; /// <remarks/> public event GetZonesCompletedEventHandler GetZonesCompleted; /// <remarks/> public event AddPrimaryZoneCompletedEventHandler AddPrimaryZoneCompleted; /// <remarks/> public event AddSecondaryZoneCompletedEventHandler AddSecondaryZoneCompleted; /// <remarks/> public event DeleteZoneCompletedEventHandler DeleteZoneCompleted; /// <remarks/> public event UpdateSoaRecordCompletedEventHandler UpdateSoaRecordCompleted; /// <remarks/> public event GetZoneRecordsCompletedEventHandler GetZoneRecordsCompleted; /// <remarks/> public event AddZoneRecordCompletedEventHandler AddZoneRecordCompleted; /// <remarks/> public event DeleteZoneRecordCompletedEventHandler DeleteZoneRecordCompleted; /// <remarks/> public event AddZoneRecordsCompletedEventHandler AddZoneRecordsCompleted; /// <remarks/> public event DeleteZoneRecordsCompletedEventHandler DeleteZoneRecordsCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/ZoneExists", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool ZoneExists(string zoneName) { object[] results = this.Invoke("ZoneExists", new object[] { zoneName}); return ((bool)(results[0])); } /// <remarks/> public System.IAsyncResult BeginZoneExists(string zoneName, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("ZoneExists", new object[] { zoneName}, callback, asyncState); } /// <remarks/> public bool EndZoneExists(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((bool)(results[0])); } /// <remarks/> public void ZoneExistsAsync(string zoneName) { this.ZoneExistsAsync(zoneName, null); } /// <remarks/> public void ZoneExistsAsync(string zoneName, object userState) { if ((this.ZoneExistsOperationCompleted == null)) { this.ZoneExistsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnZoneExistsOperationCompleted); } this.InvokeAsync("ZoneExists", new object[] { zoneName}, this.ZoneExistsOperationCompleted, userState); } private void OnZoneExistsOperationCompleted(object arg) { if ((this.ZoneExistsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.ZoneExistsCompleted(this, new ZoneExistsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetZones", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string[] GetZones() { object[] results = this.Invoke("GetZones", new object[0]); return ((string[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetZones(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetZones", new object[0], callback, asyncState); } /// <remarks/> public string[] EndGetZones(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((string[])(results[0])); } /// <remarks/> public void GetZonesAsync() { this.GetZonesAsync(null); } /// <remarks/> public void GetZonesAsync(object userState) { if ((this.GetZonesOperationCompleted == null)) { this.GetZonesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetZonesOperationCompleted); } this.InvokeAsync("GetZones", new object[0], this.GetZonesOperationCompleted, userState); } private void OnGetZonesOperationCompleted(object arg) { if ((this.GetZonesCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetZonesCompleted(this, new GetZonesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/AddPrimaryZone", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void AddPrimaryZone(string zoneName, string[] secondaryServers) { this.Invoke("AddPrimaryZone", new object[] { zoneName, secondaryServers}); } /// <remarks/> public System.IAsyncResult BeginAddPrimaryZone(string zoneName, string[] secondaryServers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddPrimaryZone", new object[] { zoneName, secondaryServers}, callback, asyncState); } /// <remarks/> public void EndAddPrimaryZone(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void AddPrimaryZoneAsync(string zoneName, string[] secondaryServers) { this.AddPrimaryZoneAsync(zoneName, secondaryServers, null); } /// <remarks/> public void AddPrimaryZoneAsync(string zoneName, string[] secondaryServers, object userState) { if ((this.AddPrimaryZoneOperationCompleted == null)) { this.AddPrimaryZoneOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddPrimaryZoneOperationCompleted); } this.InvokeAsync("AddPrimaryZone", new object[] { zoneName, secondaryServers}, this.AddPrimaryZoneOperationCompleted, userState); } private void OnAddPrimaryZoneOperationCompleted(object arg) { if ((this.AddPrimaryZoneCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddPrimaryZoneCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/AddSecondaryZone", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void AddSecondaryZone(string zoneName, string[] masterServers) { this.Invoke("AddSecondaryZone", new object[] { zoneName, masterServers}); } /// <remarks/> public System.IAsyncResult BeginAddSecondaryZone(string zoneName, string[] masterServers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddSecondaryZone", new object[] { zoneName, masterServers}, callback, asyncState); } /// <remarks/> public void EndAddSecondaryZone(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void AddSecondaryZoneAsync(string zoneName, string[] masterServers) { this.AddSecondaryZoneAsync(zoneName, masterServers, null); } /// <remarks/> public void AddSecondaryZoneAsync(string zoneName, string[] masterServers, object userState) { if ((this.AddSecondaryZoneOperationCompleted == null)) { this.AddSecondaryZoneOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddSecondaryZoneOperationCompleted); } this.InvokeAsync("AddSecondaryZone", new object[] { zoneName, masterServers}, this.AddSecondaryZoneOperationCompleted, userState); } private void OnAddSecondaryZoneOperationCompleted(object arg) { if ((this.AddSecondaryZoneCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddSecondaryZoneCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteZone", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void DeleteZone(string zoneName) { this.Invoke("DeleteZone", new object[] { zoneName}); } /// <remarks/> public System.IAsyncResult BeginDeleteZone(string zoneName, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteZone", new object[] { zoneName}, callback, asyncState); } /// <remarks/> public void EndDeleteZone(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void DeleteZoneAsync(string zoneName) { this.DeleteZoneAsync(zoneName, null); } /// <remarks/> public void DeleteZoneAsync(string zoneName, object userState) { if ((this.DeleteZoneOperationCompleted == null)) { this.DeleteZoneOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteZoneOperationCompleted); } this.InvokeAsync("DeleteZone", new object[] { zoneName}, this.DeleteZoneOperationCompleted, userState); } private void OnDeleteZoneOperationCompleted(object arg) { if ((this.DeleteZoneCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteZoneCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/UpdateSoaRecord", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void UpdateSoaRecord(string zoneName, string host, string primaryNsServer, string primaryPerson) { this.Invoke("UpdateSoaRecord", new object[] { zoneName, host, primaryNsServer, primaryPerson}); } /// <remarks/> public System.IAsyncResult BeginUpdateSoaRecord(string zoneName, string host, string primaryNsServer, string primaryPerson, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateSoaRecord", new object[] { zoneName, host, primaryNsServer, primaryPerson}, callback, asyncState); } /// <remarks/> public void EndUpdateSoaRecord(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void UpdateSoaRecordAsync(string zoneName, string host, string primaryNsServer, string primaryPerson) { this.UpdateSoaRecordAsync(zoneName, host, primaryNsServer, primaryPerson, null); } /// <remarks/> public void UpdateSoaRecordAsync(string zoneName, string host, string primaryNsServer, string primaryPerson, object userState) { if ((this.UpdateSoaRecordOperationCompleted == null)) { this.UpdateSoaRecordOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateSoaRecordOperationCompleted); } this.InvokeAsync("UpdateSoaRecord", new object[] { zoneName, host, primaryNsServer, primaryPerson}, this.UpdateSoaRecordOperationCompleted, userState); } private void OnUpdateSoaRecordOperationCompleted(object arg) { if ((this.UpdateSoaRecordCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateSoaRecordCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetZoneRecords", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public DnsRecord[] GetZoneRecords(string zoneName) { object[] results = this.Invoke("GetZoneRecords", new object[] { zoneName}); return ((DnsRecord[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetZoneRecords(string zoneName, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetZoneRecords", new object[] { zoneName}, callback, asyncState); } /// <remarks/> public DnsRecord[] EndGetZoneRecords(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((DnsRecord[])(results[0])); } /// <remarks/> public void GetZoneRecordsAsync(string zoneName) { this.GetZoneRecordsAsync(zoneName, null); } /// <remarks/> public void GetZoneRecordsAsync(string zoneName, object userState) { if ((this.GetZoneRecordsOperationCompleted == null)) { this.GetZoneRecordsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetZoneRecordsOperationCompleted); } this.InvokeAsync("GetZoneRecords", new object[] { zoneName}, this.GetZoneRecordsOperationCompleted, userState); } private void OnGetZoneRecordsOperationCompleted(object arg) { if ((this.GetZoneRecordsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetZoneRecordsCompleted(this, new GetZoneRecordsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/AddZoneRecord", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void AddZoneRecord(string zoneName, DnsRecord record) { this.Invoke("AddZoneRecord", new object[] { zoneName, record}); } /// <remarks/> public System.IAsyncResult BeginAddZoneRecord(string zoneName, DnsRecord record, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddZoneRecord", new object[] { zoneName, record}, callback, asyncState); } /// <remarks/> public void EndAddZoneRecord(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void AddZoneRecordAsync(string zoneName, DnsRecord record) { this.AddZoneRecordAsync(zoneName, record, null); } /// <remarks/> public void AddZoneRecordAsync(string zoneName, DnsRecord record, object userState) { if ((this.AddZoneRecordOperationCompleted == null)) { this.AddZoneRecordOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddZoneRecordOperationCompleted); } this.InvokeAsync("AddZoneRecord", new object[] { zoneName, record}, this.AddZoneRecordOperationCompleted, userState); } private void OnAddZoneRecordOperationCompleted(object arg) { if ((this.AddZoneRecordCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddZoneRecordCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteZoneRecord", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void DeleteZoneRecord(string zoneName, DnsRecord record) { this.Invoke("DeleteZoneRecord", new object[] { zoneName, record}); } /// <remarks/> public System.IAsyncResult BeginDeleteZoneRecord(string zoneName, DnsRecord record, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteZoneRecord", new object[] { zoneName, record}, callback, asyncState); } /// <remarks/> public void EndDeleteZoneRecord(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void DeleteZoneRecordAsync(string zoneName, DnsRecord record) { this.DeleteZoneRecordAsync(zoneName, record, null); } /// <remarks/> public void DeleteZoneRecordAsync(string zoneName, DnsRecord record, object userState) { if ((this.DeleteZoneRecordOperationCompleted == null)) { this.DeleteZoneRecordOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteZoneRecordOperationCompleted); } this.InvokeAsync("DeleteZoneRecord", new object[] { zoneName, record}, this.DeleteZoneRecordOperationCompleted, userState); } private void OnDeleteZoneRecordOperationCompleted(object arg) { if ((this.DeleteZoneRecordCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteZoneRecordCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/AddZoneRecords", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void AddZoneRecords(string zoneName, DnsRecord[] records) { this.Invoke("AddZoneRecords", new object[] { zoneName, records}); } /// <remarks/> public System.IAsyncResult BeginAddZoneRecords(string zoneName, DnsRecord[] records, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddZoneRecords", new object[] { zoneName, records}, callback, asyncState); } /// <remarks/> public void EndAddZoneRecords(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void AddZoneRecordsAsync(string zoneName, DnsRecord[] records) { this.AddZoneRecordsAsync(zoneName, records, null); } /// <remarks/> public void AddZoneRecordsAsync(string zoneName, DnsRecord[] records, object userState) { if ((this.AddZoneRecordsOperationCompleted == null)) { this.AddZoneRecordsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddZoneRecordsOperationCompleted); } this.InvokeAsync("AddZoneRecords", new object[] { zoneName, records}, this.AddZoneRecordsOperationCompleted, userState); } private void OnAddZoneRecordsOperationCompleted(object arg) { if ((this.AddZoneRecordsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddZoneRecordsCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteZoneRecords", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void DeleteZoneRecords(string zoneName, DnsRecord[] records) { this.Invoke("DeleteZoneRecords", new object[] { zoneName, records}); } /// <remarks/> public System.IAsyncResult BeginDeleteZoneRecords(string zoneName, DnsRecord[] records, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteZoneRecords", new object[] { zoneName, records}, callback, asyncState); } /// <remarks/> public void EndDeleteZoneRecords(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void DeleteZoneRecordsAsync(string zoneName, DnsRecord[] records) { this.DeleteZoneRecordsAsync(zoneName, records, null); } /// <remarks/> public void DeleteZoneRecordsAsync(string zoneName, DnsRecord[] records, object userState) { if ((this.DeleteZoneRecordsOperationCompleted == null)) { this.DeleteZoneRecordsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteZoneRecordsOperationCompleted); } this.InvokeAsync("DeleteZoneRecords", new object[] { zoneName, records}, this.DeleteZoneRecordsOperationCompleted, userState); } private void OnDeleteZoneRecordsOperationCompleted(object arg) { if ((this.DeleteZoneRecordsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteZoneRecordsCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void ZoneExistsCompletedEventHandler(object sender, ZoneExistsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class ZoneExistsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal ZoneExistsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public bool Result { get { this.RaiseExceptionIfNecessary(); return ((bool)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetZonesCompletedEventHandler(object sender, GetZonesCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetZonesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetZonesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public string[] Result { get { this.RaiseExceptionIfNecessary(); return ((string[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void AddPrimaryZoneCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void AddSecondaryZoneCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void DeleteZoneCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void UpdateSoaRecordCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetZoneRecordsCompletedEventHandler(object sender, GetZoneRecordsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetZoneRecordsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetZoneRecordsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public DnsRecord[] Result { get { this.RaiseExceptionIfNecessary(); return ((DnsRecord[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void AddZoneRecordCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void DeleteZoneRecordCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void AddZoneRecordsCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void DeleteZoneRecordsCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); }
/** @file tools/sdk/cs/Test.cs @author Luke Tokheim, luke@motionnode.com @version 2.2 Copyright (c) 2015, Motion Workshop All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using Motion.SDK; namespace Test { /** Test functions for the Motion SDK. */ class Test { // Use 32079 for preview data service. // Use 32078 for sensor data service // Use 32077 for raw data service. // Use 32076 for configurable data service. // Use 32075 for console service. const int PortPreview = 32079; const int PortSensor = 32078; const int PortRaw = 32077; const int PortConfigurable = 32076; const int PortConsole = 32075; // Read this many samples in our test loops. const int NSample = 10; static void test_LuaConsole(String host, int port) { try { Client client = new Client(host, port); Console.WriteLine("Connected to " + host + ":" + port); String chunk = "if not node.is_reading() then" + " node.close()" + " node.scan()" + " node.start()" + " end" + " if node.is_reading() then" + " print('Reading from ' .. node.num_reading() .. ' device(s)')" + " else" + " print('Failed to start reading')" + " end"; LuaConsole.ResultType result = LuaConsole.SendChunk(client, chunk); if (LuaConsole.ResultCode.Success == result.first) { Console.WriteLine(result.second); } else if (LuaConsole.ResultCode.Continue == result.first) { Console.WriteLine("incomplete Lua chunk: " + result.second); } else { Console.WriteLine("command failed: " + result.second); } client.close(); client = null; } catch (Exception e) { Console.WriteLine(e.ToString()); } } static void test_Client(String host, int port) { try { Client client = new Client(host, port); Console.WriteLine("Connected to " + host + ":" + port); // The Configurable data service requires that we specify a list of channels // that we would like to receive. if (PortConfigurable == port) { // Access the global quaternion and calibrated accelerometer streams. String xml_definition = "<?xml version=\"1.0\"?>" + "<configurable>" + "<preview><Gq/></preview>" + "<sensor><a/></sensor>" + "</configurable>"; if (client.writeData(xml_definition)) { Console.WriteLine("Sent active channel definition to Configurable service"); } } if (client.waitForData()) { int sample_count = 0; while (true) { byte[] data = client.readData(); if ((null == data) || (sample_count++ >= NSample)) { break; } if (PortPreview == port) { IDictionary<int, Format.PreviewElement> container = Format.Preview(data); foreach (KeyValuePair<int, Format.PreviewElement> itr in container) { float[] q = itr.Value.getQuaternion(false); Console.WriteLine("q(" + itr.Key + ") = (" + q[0] + ", " + q[1] + "i, " + q[2] + "j, " + q[3] + "k)"); } } if (PortSensor == port) { IDictionary<int, Format.SensorElement> container = Format.Sensor(data); foreach (KeyValuePair<int, Format.SensorElement> itr in container) { float[] a = itr.Value.getAccelerometer(); Console.WriteLine("a(" + itr.Key + ") = (" + a[0] + ", " + a[1] + ", " + a[2] + ") g"); } } if (PortRaw == port) { IDictionary<int, Format.RawElement> container = Format.Raw(data); foreach (KeyValuePair<int, Format.RawElement> itr in container) { short[] a = itr.Value.getAccelerometer(); Console.WriteLine("a(" + itr.Key + ") = (" + a[0] + ", " + a[1] + ", " + a[2] + ") g"); } } if (PortConfigurable == port) { IDictionary<int, Format.ConfigurableElement> container = Format.Configurable(data); foreach (KeyValuePair<int, Format.ConfigurableElement> itr in container) { Console.Write("data(" + itr.Key + ") = ("); for (int i=0; i<itr.Value.size(); i++) { if (i > 0) { Console.Write(", "); } Console.Write(itr.Value.value(i)); } Console.WriteLine(")"); } } } } client.close(); client = null; } catch (Exception e) { Console.WriteLine(e.ToString()); } } static void test_File() { try { String filename = "../../../../test_data/output.bin"; Console.WriteLine("test_File, reading data file: \"" + filename + "\""); File file = new File(filename); int i = 0; while (i++ < 10) { float[] x = file.readOutputData(); if (null == x) { break; } else { Console.WriteLine("q(" + i + ") = <" + x[0] + ", " + x[1] + "i, " + x[2] + "j, " + x[3] + "k>"); } } file.close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } static void Main(string[] args) { String host = ""; if (args.Length > 0) { host = args[0]; } test_LuaConsole(host, PortConsole); test_Client(host, PortPreview); test_Client(host, PortSensor); test_Client(host, PortRaw); test_Client(host, PortConfigurable); //test_File(); } } }
using System; namespace IBatisNet.Common.Test.Domain { public enum Days : int { Sat = 1, Sun = 2, Mon = 3, Tue = 4, Wed = 5, Thu = 6, Fri = 7 }; /// <summary> /// Summary description for Property. /// </summary> public class Property { public string publicString = string.Empty; public int publicInt = int.MinValue; public DateTime publicDateTime = DateTime.MinValue; public decimal publicDecimal = decimal.MinValue; public sbyte publicSbyte = sbyte.MinValue; public byte publicByte = byte.MinValue; public char publicChar = char.MinValue; public short publicShort = short.MinValue; public ushort publicUshort = ushort.MinValue; public uint publicUint = uint.MinValue; public long publicLong = long.MinValue; public ulong publicUlong = ulong.MinValue; public bool publicBool = false; public double publicDouble = double.MinValue; public float publicFloat = float.MinValue; public Guid publicGuid = Guid.Empty; public TimeSpan publicTimeSpan = TimeSpan.MinValue; public Account publicAccount = null; public Days publicDay; private string _string = string.Empty; private int _int = int.MinValue; private DateTime _dateTime = DateTime.MinValue; private decimal _decimal = decimal.MinValue; private sbyte _sbyte = sbyte.MinValue; private byte _byte = byte.MinValue; private char _char = char.MinValue; private short _short = short.MinValue; private ushort _ushort = ushort.MinValue; private uint _uint = uint.MinValue; private long _long = long.MinValue; private ulong _ulong = ulong.MinValue; private bool _bool = false; private double _double = double.MinValue; private float _float = float.MinValue; private Guid _guid = Guid.Empty; private TimeSpan _timeSpan = TimeSpan.MinValue; private Account _account = null; private Days _day; protected string protectedString = string.Empty; protected int protectedInt = int.MinValue; protected DateTime protectedDateTime = DateTime.MinValue; protected decimal protectedDecimal = decimal.MinValue; protected sbyte protectedSbyte = sbyte.MinValue; protected byte protectedByte = byte.MinValue; protected char protectedChar = char.MinValue; protected short protectedShort = short.MinValue; protected ushort protectedUshort = ushort.MinValue; protected uint protectedUint = uint.MinValue; protected long protectedLong = long.MinValue; protected ulong protectedUlong = ulong.MinValue; protected bool protectedBool = false; protected double protectedDouble = double.MinValue; protected float protectedFloat = float.MinValue; protected Guid protectedGuid = Guid.Empty; protected TimeSpan protectedTimeSpan = TimeSpan.MinValue; protected Account protectedAccount = null; protected Days protectedDay; #if dotnet2 private Int32? _intNullable = null; public Int32? publicintNullable = null; protected Int32? protectedintNullable = null; public Int32? IntNullable { get { return _intNullable; } set { _intNullable = value; } } #endif public Property() { } public Days Day { get { return _day; } set { _day = value; } } public string String { get { return _string; } set { _string = value; } } public virtual int Int { get { return _int; } set { _int = value; } } public virtual DateTime DateTime { get { return _dateTime; } set { _dateTime = value; } } public decimal Decimal { get { return _decimal; } set { _decimal = value; } } public sbyte SByte { get { return _sbyte; } set { _sbyte = value; } } public byte Byte { get { return _byte; } set { _byte = value; } } public char Char { get { return _char; } set { _char = value; } } public short Short { get { return _short; } set { _short = value; } } public ushort UShort { get { return _ushort; } set { _ushort = value; } } public uint UInt { get { return _uint; } set { _uint = value; } } public long Long { get { return _long; } set { _long = value; } } public ulong ULong { get { return _ulong; } set { _ulong = value; } } public bool Bool { get { return _bool; } set { _bool = value; } } public virtual double Double { get { return _double; } set { _double = value; } } public float Float { get { return _float; } set { _float = value; } } public Guid Guid { get { return _guid; } set { _guid = value; } } public virtual TimeSpan TimeSpan { get { return _timeSpan; } set { _timeSpan = value; } } public virtual Account Account { get { return _account; } set { _account = value; } } } public class PropertySon : Property { private int _int = int.MinValue; private int _float = int.MinValue; private int PrivateIndex { set { _int = value; } } public int Index { get { return _int; } #if dotnet2 protected set { _int = value; } #else set { _int = value; } #endif } public override Account Account { get { return new Account(Days.Wed); } set { throw new InvalidOperationException("Test virtual"); } } public override int Int { get { return -88; } set { throw new InvalidOperationException("Test virtual"); } } public override DateTime DateTime { get { return new DateTime(2000,1,1); } set { throw new InvalidOperationException("Test virtual"); } } public new int Float { get { return _float; } set { _float = value*2; } } #if dotnet2 private SpecialReference<Account> _referenceAccount = null; public SpecialReference<Account> ReferenceAccount { get { return _referenceAccount; } set { _referenceAccount = value; } } #endif } #if dotnet2 public class SpecialReference<T> where T : class { private T _value =null; public T Value { get { return _value; } set { _value = value; } } } #endif }
using System; using System.IdentityModel.Selectors; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Security; using System.Text; namespace SolarWinds.InformationService.Contract2 { [DataContract(Name = "Windows", Namespace = "http://schema.solarwinds.com/2007/08/IS")] public class WindowsCredential : ServiceCredentials { public string Domain { get; set; } public string Username { get; set; } public SecureString Password { get; private set; } public TokenImpersonationLevel ImpersonationLevel { get; set; } = TokenImpersonationLevel.Impersonation; public WindowsCredential() : this(string.Empty, string.Empty, string.Empty) { } public WindowsCredential(string username, string password) { SetUsername(username); Password = SecurePassword(password); } public WindowsCredential(string domain, string username, string password) { Domain = domain; Username = username; Password = SecurePassword(password); } public WindowsCredential(string username, SecureString password) { SetUsername(username); Password = password; } public WindowsCredential(string domain, string username, SecureString password) { Domain = domain; Username = username; Password = password; } private void SetUsername(string username) { int index = username.IndexOf('\\'); if (index < 0 || index == (username.Length - 1)) { Username = username; } else if (index > 0) { Domain = username.Substring(0, index); Username = username.Substring(index + 1); } } public override CredentialType CredentialType { get { return CredentialType.Windows; } } private static SecureString SecurePassword(string password) { SecureString pass = new SecureString(); foreach (char c in password) { pass.AppendChar(c); } return pass; } public override void ApplyTo(ChannelFactory channelFactory) { if (!string.IsNullOrEmpty(Domain)) { channelFactory.Credentials.Windows.ClientCredential.Domain = Domain; string host = channelFactory.Endpoint.Address.Uri.Host; if (string.IsNullOrEmpty(host) || host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) host = Environment.MachineName; channelFactory.Endpoint.Address = new EndpointAddress(channelFactory.Endpoint.Address.Uri, new SpnEndpointIdentity("HOST/" + host)); } if (!string.IsNullOrEmpty(Username)) { channelFactory.Credentials.Windows.ClientCredential.UserName = Username; } if (Password.Length > 0) channelFactory.Credentials.Windows.ClientCredential.Password = GetPassword(); channelFactory.Credentials.Windows.AllowedImpersonationLevel = ImpersonationLevel; channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; X509ChainPolicy chainPolicy = new X509ChainPolicy(); chainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority | X509VerificationFlags.IgnoreNotTimeValid; // Previously, this was calling X509CertificateValidator.CreateChainTrustValidator, but this is not available for .NET Standard and .NET Core. // The CreateChainTrustValidator method returned a new ChainTrustValidator. // The source for that class has been adapted and included as a private class below. // https://github.com/microsoft/referencesource/blob/5697c29004a34d80acdaf5742d7e699022c64ecd/System.IdentityModel/System/IdentityModel/Selectors/X509CertificateValidator.cs#L76 channelFactory.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = new ChainTrustValidator(chainPolicy); } public string GetPassword() { IntPtr bstr = IntPtr.Zero; string insecureString; try { bstr = Marshal.SecureStringToBSTR(Password); insecureString = Marshal.PtrToStringBSTR(bstr); } catch { insecureString = string.Empty; } finally { if (bstr != IntPtr.Zero) { Marshal.ZeroFreeBSTR(bstr); } } return insecureString; } protected override void Dispose(bool disposing) { if (Password != null) { Password.Dispose(); Password = null; } base.Dispose(disposing); } // Adapted from https://github.com/microsoft/referencesource/blob/5697c29004a34d80acdaf5742d7e699022c64ecd/System.IdentityModel/System/IdentityModel/Selectors/X509CertificateValidator.cs#L188 // Several simplifications have been made because the constructor parameters are known. private class ChainTrustValidator : X509CertificateValidator { private readonly X509ChainPolicy _chainPolicy; public ChainTrustValidator(X509ChainPolicy chainPolicy) { _chainPolicy = chainPolicy ?? throw new ArgumentNullException(nameof(chainPolicy)); } public override void Validate(X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } X509Chain chain = new X509Chain(true) { ChainPolicy = _chainPolicy }; if (!chain.Build(certificate)) { // In the .NET Framework source, this throws a SecurityTokenValidationException instead. throw new InvalidOperationException($"The specific X.509 certificate chain building failed. The certificate that was used ({GetCertificateId(certificate)}) has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. Chain status: {GetChainStatusInformation(chain.ChainStatus)}"); } } private static string GetChainStatusInformation(X509ChainStatus[] chainStatus) { if (chainStatus != null) { StringBuilder error = new StringBuilder(128); for (int i = 0; i < chainStatus.Length; ++i) { error.Append(chainStatus[i].StatusInformation); error.Append(" "); } return error.ToString(); } return string.Empty; } // From https://github.com/microsoft/referencesource/blob/5697c29004a34d80acdaf5742d7e699022c64ecd/System.IdentityModel/System/IdentityModel/SecurityUtils.cs#L152 private static string GetCertificateId(X509Certificate2 certificate) { string certificateId = certificate.SubjectName.Name; if (string.IsNullOrEmpty(certificateId)) { certificateId = certificate.Thumbprint; } return certificateId; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using Mogre; using MogreFramework; namespace AntKiller { /// <summary> /// Class that builds the Scene and the Objects in it /// </summary> class AntBuilder { #region Properties //private Light light; private static List<Object> objects; public static List<Object> Objects { get { return objects; } } private static List<Object> toBeRemoved; public static List<Object> ToBeRemoved { get { return toBeRemoved; } } private static List<Object> toBeAdded; public static List<Object> ToBeAdded { get { return toBeAdded; } } private AntKiller antKiller; private static TextWriter textWriter; public static TextWriter TextWriter { get { return textWriter; } } private static Boolean pause; public static Boolean Pause { get { return pause; } set { pause = value; } } private static Boolean attacking; public static Boolean Attacking { get { return attacking; } set { attacking = value; } } private float time; private IntersectionSceneQuery intersectionSceneQuery; #endregion public AntBuilder(OgreWindow win) { AntBuilder.objects = new List<Object>(); AntBuilder.toBeRemoved = new List<Object>(); AntBuilder.toBeAdded = new List<Object>(); time = 0.0f; antKiller = (AntKiller)win; antKiller.SceneCreating += new OgreWindow.SceneEventHandler(win_SceneCreating); } void win_SceneCreating(OgreWindow win) { antKiller.Root.FrameStarted += new FrameListener.FrameStartedHandler(Root_FrameStarted); //win.SceneManager.SetSkyDome(true, "Examples/CloudySky", 5, 8); win.SceneManager.SetWorldGeometry("terrain.cfg"); createAnts(win); antKiller.Camera.Position = antKiller.Camera.Orientation * new Vector3(Options.screenX * 0.5f, Options.cameraY, Options.screenZ * 0.5f); antKiller.Camera.Pitch(new Degree(-90).ValueRadians); intersectionSceneQuery = win.SceneManager.CreateIntersectionQuery(); } bool Root_FrameStarted(FrameEvent evt) { if (!AntBuilder.Pause) { foreach (Object obj in AntBuilder.Objects) { obj.Update(evt); } while (AntBuilder.ToBeAdded.Count > 0) { Object obj = AntBuilder.ToBeAdded[0]; if (!AntBuilder.Objects.Contains(obj)) { AntBuilder.Objects.Add(obj); } else { AntBuilder.ToBeAdded.Remove(obj); } } while (AntBuilder.ToBeRemoved.Count > 0) { Object obj = AntBuilder.ToBeRemoved[0]; if (obj.GetType() == typeof(Food)) { AntBuilder.Objects.Add(new Food(obj.Win, obj.Win.SceneManager.RootSceneNode.CreateChildSceneNode(), Options.randomPoint())); } else if (obj.GetType() == typeof(Ant)) { ((Ant)obj).Colony.Counter--; } AntBuilder.Objects.Remove(obj); obj.Detach(); //obj.Destroy(); AntBuilder.ToBeRemoved.Remove(obj); } time += evt.timeSinceLastFrame; } CheckCollision(); AntBuilder.TextWriter.setText("Time", "Time: " + (int)time + (AntBuilder.Pause ? " (Paused)" : "") + (AntBuilder.Attacking ? "" : " (Attack Off)")); return true; } void createAnts(OgreWindow win) { AntBuilder.textWriter = new TextWriter(win); Colony colony1 = new Colony( win, win.SceneManager.RootSceneNode.CreateChildSceneNode(), AntColor.BLACK, new Vector3(Options.screenX * 0.25f, 0, Options.screenZ * 0.25f)); AntBuilder.Objects.Add(colony1); AntBuilder.TextWriter.addTextBox(colony1.Name + "Stock", "Stock: " + colony1.Stock, 10, 10, 200, 20, new ColourValue(0.6f, 0.6f, 0.6f)); AntBuilder.TextWriter.addTextBox(colony1.Name + "Ants", "Ants: " + colony1.Counter, 210, 10, 200, 20, new ColourValue(0.6f, 0.6f, 0.6f)); Colony colony2 = new Colony( win, win.SceneManager.RootSceneNode.CreateChildSceneNode(), AntColor.RED, new Vector3(Options.screenX * 0.75f, 0, Options.screenZ * 0.75f)); AntBuilder.Objects.Add(colony2); AntBuilder.TextWriter.addTextBox(colony2.Name + "Stock", "Stock: " + colony2.Stock, 10, 30, 200, 20, new ColourValue(1, 0, 0)); AntBuilder.TextWriter.addTextBox(colony2.Name + "Ants", "Ants: " + colony2.Counter, 210, 30, 200, 20, new ColourValue(1, 0, 0)); for (int i = 0; i < Options.antsPerSide; i++) { AntBuilder.Objects.Add(new Ant(win, win.SceneManager.RootSceneNode.CreateChildSceneNode(), colony1)); AntBuilder.Objects.Add(new Ant(win, win.SceneManager.RootSceneNode.CreateChildSceneNode(), colony2)); } for (int i = 0; i < Options.foodPieces; i++) { AntBuilder.Objects.Add(new Food(win, win.SceneManager.RootSceneNode.CreateChildSceneNode(), Options.randomPoint())); } AntBuilder.TextWriter.addTextBox("Time", "Time: 0", 10, 50, 200, 20, new ColourValue(0, 0, 1)); } private void CheckCollision() { IntersectionSceneQueryResult result = intersectionSceneQuery.Execute(); SceneQueryMovableIntersectionList list = result.movables2movables; IEnumerator<Pair<MovableObject, MovableObject>> iter = list.GetEnumerator(); while (iter.MoveNext()) { Object first = null, second = null; foreach (Object obj in AntBuilder.Objects) { // Check if Moveable Objects are any Entity's of our Objects if (obj.Entity == (Entity)iter.Current.first) first = obj; if (obj.Entity == (Entity)iter.Current.second) second = obj; if (first != null && second != null) break; } // Did we find both Objects? if (first != null && second != null) { // Did we find food? if (first.GetType() == typeof(Food) || second.GetType() == typeof(Food)) { if (first.GetType() == typeof(Ant)) { FoundFood(first as Ant, second as Food); } if (second.GetType() == typeof(Ant)) { FoundFood(second as Ant, first as Food); } } // Is there interaction between Ants? if (first.GetType() == typeof(Ant) && second.GetType() == typeof(Ant)) { AntsInteract(first as Ant, second as Ant); } } } } private void FoundFood(Ant ant, Food food) { if (ant.CurrentState.GetType() != typeof(HomeState)) { food.Amount--; if (food.Amount > 0) { if (ant.CurrentState.GetType() == typeof(SearchState) || ant.CurrentState.GetType() == typeof(BackState)) { ant.CurrentState = new HomeState(ant, new Mission(MissionType.FOOD_FOUND, food.Name, food.SceneNode.Position)); } else { ant.CurrentState = new HomeState(ant, new Mission(MissionType.FOOD_RETURN, food.Name, food.SceneNode.Position)); } } else if (food.Amount == 0) { ant.CurrentState = new HomeState(ant, new Mission(MissionType.LAST_FOOD, food.Name, food.SceneNode.Position)); } else { ant.CurrentState = new HomeState(ant, new Mission(MissionType.FOOD_EMPTY, food.Name, food.SceneNode.Position)); } } } private void AntsInteract(Ant first, Ant second) { if (first.Colony == second.Colony) { //Console.WriteLine("Friendly Interaction {0}, {1}", first.CurrentState.GetType().Name, second.CurrentState.GetType().Name); if (first.CurrentState.GetType() == typeof(HomeState) || second.CurrentState.GetType() == typeof(HomeState)) { if(first.CurrentState.GetType() == typeof(FoodState)) { ExchangeFoodMessage(second, first); } if(second.CurrentState.GetType() == typeof(FoodState)) { ExchangeFoodMessage(first, second); } } } else if (AntBuilder.Attacking) { // None are exploding? if (first.CurrentState.GetType() != typeof(ExplodeState) && second.CurrentState.GetType() != typeof(ExplodeState)) { if (first.CurrentState.GetType() != typeof(AttackState)) { first.CurrentState = new AttackState(first, second); } if (second.CurrentState.GetType() != typeof(AttackState)) { second.CurrentState = new AttackState(second, first); } } } } private void ExchangeFoodMessage(Ant home, Ant food) { Mission mission = (home.CurrentState as HomeState).Mission; FoodState foodAntState = food.CurrentState as FoodState; if ((mission.MissionType == MissionType.FOOD_EMPTY || mission.MissionType == MissionType.LAST_FOOD) && mission.ObjectName == foodAntState.ObjectName) { //Console.WriteLine(home.Name + " to " + food.Name + ": 'food is gone'!"); food.CurrentState = new HomeState(food, new Mission(MissionType.FOOD_EMPTY, foodAntState.ObjectName, food.SceneNode.Position)); } } } }
#region Licence... /* The MIT License (MIT) Copyright (c) 2014 Oleg Shilo 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 Licence... using System; using System.Collections.Generic; using System.Linq; using WixSharp.CommonTasks; using IO = System.IO; namespace WixSharp { /// <summary> /// Defines all files of a given source directory and all subdirectories to be installed on target system. /// <para> /// Use this class to define files to be automatically included into the deployment solution /// if their name matches specified wildcard character pattern (<see cref="Files.IncludeMask"/>). /// </para> /// <para> /// This class is a logical equivalent of <see cref="DirFiles"/> except it also analyses all files in all subdirectories. /// <see cref="DirFiles"/> excludes files in subdirectories. /// </para> /// <para>You can control inclusion of empty directories during wild card resolving by adjusting the compiler setting /// <c>Compiler.AutoGeneration.IgnoreWildCardEmptyDirectories.</c></para> /// </summary> /// <remarks> /// Note that all files matching wildcard are resolved into absolute path thus it may not always be suitable /// if the Wix# script is to be compiled into WiX XML source only (Compiler.<see cref="WixSharp.Compiler.BuildWxs(WixSharp.Project)"/>). Though it is not a problem at all if the Wix# script /// is compiled into MSI file (Compiler.<see cref="Compiler.BuildMsi(WixSharp.Project)"/>). /// </remarks>b /// <example>The following is an example of defining installation files with wildcard character pattern. /// <code> /// new Project("MyProduct", /// new Dir(@"%ProgramFiles%\MyCompany\MyProduct", /// new Files(@"Release\Bin\*.*"), /// ... /// </code> /// </example> public partial class Files : WixEntity { /// <summary> /// Aggregates the files from the build directory. It is nothing else but a simplified creation of the /// <see cref="WixSharp.Files"/> as below: /// <code> /// new Files(buildDir.PathJoin("*.*"), /// f => f.EndsWithAny(ignoreCase: true, new[]{".exe",".dll,".xml",".config", ".json"})) /// </code> /// </summary> /// <param name="buildDir">The build dir.</param> /// <param name="fileExtensions">The file extensions to match the files that need to be included in the deployment.</param> /// <returns></returns> public static Files FromBuildDir(string buildDir, string fileExtensions = ".exe|.dll|.xml|.config|.json") => new Files(buildDir.PathJoin("*.*"), f => f.EndsWithAny(true, fileExtensions.Split('|'))); /// <summary> /// Initializes a new instance of the <see cref="Files"/> class. /// </summary> public Files() { } /// <summary> /// Initializes a new instance of the <see cref="Files"/> class with properties/fields initialized with specified parameters. /// <para>You can control inclusion of empty folders (if picked by the wild card patter) by setting /// <see cref="AutoGenerationOptions.IgnoreWildCardEmptyDirectories"/> to <c>true</c>.</para> /// <para>If more specific control is required you can always use a flat list of <c>Dirs</c> of the /// Project.<see cref="Project.AllDirs"/> to remove the undesired folder from its parent collection. /// </para> /// </summary> /// <param name="sourcePath">The relative path to source directory. It must include wildcard pattern for files to be included /// into MSI (e.g. <c>new Files(@"Release\Bin\*.*")</c>).</param> public Files(string sourcePath) { IncludeMask = IO.Path.GetFileName(sourcePath); Directory = IO.Path.GetDirectoryName(sourcePath); } /// <summary> /// Initializes a new instance of the <see cref="Files"/> class with properties/fields initialized with specified parameters. /// <para>You can control inclusion of empty folders (if picked by the wild card patter) by setting /// <see cref="AutoGenerationOptions.IgnoreWildCardEmptyDirectories"/> to <c>true</c>.</para> /// <para>If more specific control is required you can always use a flat list of <c>Dirs</c> of the /// Project.<see cref="Project.AllDirs"/> to remove the undesired folder from its parent collection. /// </para> /// </summary> /// <param name="sourcePath">The relative path to source directory. It must include wildcard pattern for files to be included /// into MSI (e.g. <c>new Files(@"Release\Bin\*.*")</c>).</param> /// <param name="filter">Filter to be applied for every file to be evaluated for the inclusion into MSI. /// (e.g. <c>new Files(typical, @"Release\Bin\*.dll", f => !f.EndsWith(".Test.dll"))</c>).</param> public Files(string sourcePath, Predicate<string> filter) { IncludeMask = IO.Path.GetFileName(sourcePath); Directory = IO.Path.GetDirectoryName(sourcePath); Filter = filter; } /// <summary> /// Initializes a new instance of the <see cref="Files"/> class with properties/fields initialized with specified parameters. /// <para>You can control inclusion of empty folders (if picked by the wild card patter) by setting /// <see cref="AutoGenerationOptions.IgnoreWildCardEmptyDirectories"/> to <c>true</c>.</para> /// <para>If more specific control is required you can always use a flat list of <c>Dirs</c> of the /// Project.<see cref="Project.AllDirs"/> to remove the undesired folder from its parent collection. /// </para> /// </summary> /// <param name="feature"><see cref="Feature"></see> the directory files should be included in.</param> /// <param name="sourcePath">The relative path to source directory. It must include wildcard pattern for files to be included /// into MSI (e.g. <c>new Files(@"Release\Bin\*.*")</c>).</param> public Files(Feature feature, string sourcePath) { IncludeMask = IO.Path.GetFileName(sourcePath); Directory = IO.Path.GetDirectoryName(sourcePath); Feature = feature; } /// <summary> /// Initializes a new instance of the <see cref="Files"/> class with properties/fields initialized with specified parameters. /// <para>You can control inclusion of empty folders (if picked by the wild card patter) by setting /// <see cref="AutoGenerationOptions.IgnoreWildCardEmptyDirectories"/> to <c>true</c>.</para> /// <para>If more specific control is required you can always use a flat list of <c>Dirs</c> of the /// Project.<see cref="Project.AllDirs"/> to remove the undesired folder from its parent collection. /// </para> /// </summary> /// <param name="feature"><see cref="Feature"></see> the directory files should be included in.</param> /// <param name="sourcePath">The relative path to source directory. It must include wildcard pattern for files to be included /// into MSI (e.g. <c>new Files(@"Release\Bin\*.*")</c>).</param> /// <param name="filter">Filter to be applied for every file to be evaluated for the inclusion into MSI. /// (e.g. <c>new Files(typical, @"Release\Bin\*.dll", f => !f.EndsWith(".Test.dll"))</c>).</param> public Files(Feature feature, string sourcePath, Predicate<string> filter) { IncludeMask = IO.Path.GetFileName(sourcePath); Directory = IO.Path.GetDirectoryName(sourcePath); Filter = filter; Feature = feature; } /// <summary> /// The relative path to source directory to search for files matching the <see cref="Files.IncludeMask"/>. /// </summary> public string Directory = ""; /// <summary> /// The filter delegate. It is applied for every file to be evaluated for the inclusion into MSI. /// </summary> public Predicate<string> Filter = (file => true); /// <summary> /// The delegate that is called when a file matching the wildcard of the sourcePath is processed /// and a <see cref="WixSharp.File"/> item is added to the project. It is the most convenient way of /// adjusting the <see cref="WixSharp.File"/> item properties. /// </summary> public Action<File> OnProcess = null; /// <summary> /// Wildcard pattern for files to be included into MSI. /// <para>Default value is <c>*.*</c>.</para> /// </summary> public string IncludeMask = "*.*"; /// <summary> /// Analyses <paramref name="baseDirectory"/> and returns all files (including subdirectories) matching <see cref="Files.IncludeMask"/>. /// </summary> /// <param name="baseDirectory">The base directory for file analysis. It is used in conjunction with /// relative <see cref="Files.Directory"/>. Though <see cref="Files.Directory"/> takes precedence if it is an absolute path.</param> /// <returns>Array of <see cref="WixEntity"/> instances, which are either <see cref="File"/> or/and <see cref="Dir"/> objects.</returns> /// <param name="parentWixDir">Parent Wix# directory</param> public WixEntity[] GetAllItems(string baseDirectory, Dir parentWixDir = null) { if (IO.Path.IsPathRooted(Directory)) baseDirectory = Directory; if (baseDirectory.IsEmpty()) baseDirectory = Environment.CurrentDirectory; baseDirectory = IO.Path.GetFullPath(baseDirectory); string rootDirPath; if (IO.Path.IsPathRooted(Directory)) rootDirPath = Directory; else rootDirPath = Utils.PathCombine(baseDirectory, Directory); void AgregateSubDirs(Dir parentDir, string dirPath) { foreach (var subDirPath in IO.Directory.GetDirectories(dirPath)) { var dirName = IO.Path.GetFileName(subDirPath); Dir subDir = parentDir.Dirs.FirstOrDefault(dir => dir.Name.SameAs(dirName, ignoreCase: true)); if (subDir == null) { subDir = new Dir(dirName); parentDir.AddDir(subDir); } subDir.AddFeatures(this.ActualFeatures); subDir.AddDirFileCollection( new DirFiles(IO.Path.Combine(subDirPath, this.IncludeMask)) { Feature = this.Feature, Features = this.Features, AttributesDefinition = this.AttributesDefinition, Attributes = this.Attributes, Filter = this.Filter, OnProcess = this.OnProcess }); AgregateSubDirs(subDir, subDirPath); } }; var items = new List<WixEntity> { new DirFiles(IO.Path.Combine(rootDirPath, this.IncludeMask)) { Feature = this.Feature, Features = this.Features, AttributesDefinition = this.AttributesDefinition, Attributes = this.Attributes.Clone(), Filter = this.Filter, OnProcess = this.OnProcess } }; if (!IO.Directory.Exists(rootDirPath)) throw new IO.DirectoryNotFoundException(rootDirPath); foreach (var subDirPath in System.IO.Directory.GetDirectories(rootDirPath)) { var dirName = IO.Path.GetFileName(subDirPath); var subDir = parentWixDir?.Dirs.FirstOrDefault(dir => dir.Name.SameAs(dirName, ignoreCase: true)); if (subDir == null) { subDir = new Dir(dirName); items.Add(subDir); } subDir.AddFeatures(this.ActualFeatures); subDir.AddDirFileCollection( new DirFiles(IO.Path.Combine(subDirPath, this.IncludeMask)) { Feature = this.Feature, Features = this.Features, AttributesDefinition = this.AttributesDefinition, Attributes = this.Attributes, Filter = this.Filter, OnProcess = this.OnProcess }); AgregateSubDirs(subDir, subDirPath); } return items.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System; using System.Xml; using System.Globalization; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Collections; using System.Configuration; using System.Xml.Serialization.Configuration; /// <summary> /// The <see cref="XmlCustomFormatter"/> class provides a set of static methods for converting /// primitive type values to and from their XML string representations.</summary> internal class XmlCustomFormatter { private static DateTimeSerializationSection.DateTimeSerializationMode s_mode; private static DateTimeSerializationSection.DateTimeSerializationMode Mode { [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] get { if (s_mode == DateTimeSerializationSection.DateTimeSerializationMode.Default) { s_mode = DateTimeSerializationSection.DateTimeSerializationMode.Roundtrip; } return s_mode; } } private XmlCustomFormatter() { } internal static string FromDefaultValue(object value, string formatter) { if (value == null) return null; Type type = value.GetType(); if (type == typeof(DateTime)) { if (formatter == "DateTime") { return FromDateTime((DateTime)value); } if (formatter == "Date") { return FromDate((DateTime)value); } if (formatter == "Time") { return FromTime((DateTime)value); } } else if (type == typeof(string)) { if (formatter == "XmlName") { return FromXmlName((string)value); } if (formatter == "XmlNCName") { return FromXmlNCName((string)value); } if (formatter == "XmlNmToken") { return FromXmlNmToken((string)value); } if (formatter == "XmlNmTokens") { return FromXmlNmTokens((string)value); } } throw new XmlException(SR.Format(SR.XmlUnsupportedDefaultType, type.FullName)); } internal static string FromDate(DateTime value) { return XmlConvert.ToString(value, "yyyy-MM-dd"); } internal static string FromTime(DateTime value) { if (!LocalAppContextSwitches.IgnoreKindInUtcTimeSerialization && value.Kind == DateTimeKind.Utc) { return XmlConvert.ToString(DateTime.MinValue + value.TimeOfDay, "HH:mm:ss.fffffffZ"); } else { return XmlConvert.ToString(DateTime.MinValue + value.TimeOfDay, "HH:mm:ss.fffffffzzzzzz"); } } internal static string FromDateTime(DateTime value) { if (Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local) { return XmlConvert.ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz"); } else { // for mode DateTimeSerializationMode.Roundtrip and DateTimeSerializationMode.Default return XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind); } } internal static string FromChar(char value) { return XmlConvert.ToString((ushort)value); } internal static string FromXmlName(string name) { return XmlConvert.EncodeName(name); } internal static string FromXmlNCName(string ncName) { return XmlConvert.EncodeLocalName(ncName); } internal static string FromXmlNmToken(string nmToken) { return XmlConvert.EncodeNmToken(nmToken); } internal static string FromXmlNmTokens(string nmTokens) { if (nmTokens == null) return null; if (!nmTokens.Contains(' ')) return FromXmlNmToken(nmTokens); else { string[] toks = nmTokens.Split(new char[] { ' ' }); StringBuilder sb = new StringBuilder(); for (int i = 0; i < toks.Length; i++) { if (i > 0) sb.Append(' '); sb.Append(FromXmlNmToken(toks[i])); } return sb.ToString(); } } internal static void WriteArrayBase64(XmlWriter writer, byte[] inData, int start, int count) { if (inData == null || count == 0) { return; } writer.WriteBase64(inData, start, count); } internal static string FromByteArrayHex(byte[] value) { if (value == null) return null; if (value.Length == 0) return ""; return XmlConvert.ToBinHexString(value); } internal static string FromEnum(long val, string[] vals, long[] ids, string typeName) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (ids.Length != vals.Length) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Invalid enum")); #endif long originalValue = val; StringBuilder sb = new StringBuilder(); int iZero = -1; for (int i = 0; i < ids.Length; i++) { if (ids[i] == 0) { iZero = i; continue; } if (val == 0) { break; } if ((ids[i] & originalValue) == ids[i]) { if (sb.Length != 0) sb.Append(" "); sb.Append(vals[i]); val &= ~ids[i]; } } if (val != 0) { // failed to parse the enum value throw new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, originalValue, typeName == null ? "enum" : typeName)); } if (sb.Length == 0 && iZero >= 0) { sb.Append(vals[iZero]); } return sb.ToString(); } internal static object ToDefaultValue(string value, string formatter) { if (formatter == "DateTime") { return ToDateTime(value); } if (formatter == "Date") { return ToDate(value); } if (formatter == "Time") { return ToTime(value); } if (formatter == "XmlName") { return ToXmlName(value); } if (formatter == "XmlNCName") { return ToXmlNCName(value); } if (formatter == "XmlNmToken") { return ToXmlNmToken(value); } if (formatter == "XmlNmTokens") { return ToXmlNmTokens(value); } throw new XmlException(SR.Format(SR.XmlUnsupportedDefaultValue, formatter)); // Debug.WriteLineIf(CompModSwitches.XmlSerialization.TraceVerbose, "XmlSerialization::Unhandled default value " + value + " formatter " + formatter); // return DBNull.Value; } private static string[] s_allDateTimeFormats = new string[] { "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz", "yyyy", "---dd", "---ddZ", "---ddzzzzzz", "--MM-dd", "--MM-ddZ", "--MM-ddzzzzzz", "--MM--", "--MM--Z", "--MM--zzzzzz", "yyyy-MM", "yyyy-MMZ", "yyyy-MMzzzzzz", "yyyyzzzzzz", "yyyy-MM-dd", "yyyy-MM-ddZ", "yyyy-MM-ddzzzzzz", "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff", "HH:mm:ss.ffff", "HH:mm:ss.fffff", "HH:mm:ss.ffffff", "HH:mm:ss.fffffff", "HH:mm:ssZ", "HH:mm:ss.fZ", "HH:mm:ss.ffZ", "HH:mm:ss.fffZ", "HH:mm:ss.ffffZ", "HH:mm:ss.fffffZ", "HH:mm:ss.ffffffZ", "HH:mm:ss.fffffffZ", "HH:mm:sszzzzzz", "HH:mm:ss.fzzzzzz", "HH:mm:ss.ffzzzzzz", "HH:mm:ss.fffzzzzzz", "HH:mm:ss.ffffzzzzzz", "HH:mm:ss.fffffzzzzzz", "HH:mm:ss.ffffffzzzzzz", "HH:mm:ss.fffffffzzzzzz", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:ss.f", "yyyy-MM-ddTHH:mm:ss.ff", "yyyy-MM-ddTHH:mm:ss.fff", "yyyy-MM-ddTHH:mm:ss.ffff", "yyyy-MM-ddTHH:mm:ss.fffff", "yyyy-MM-ddTHH:mm:ss.ffffff", "yyyy-MM-ddTHH:mm:ss.fffffff", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:ss.fZ", "yyyy-MM-ddTHH:mm:ss.ffZ", "yyyy-MM-ddTHH:mm:ss.fffZ", "yyyy-MM-ddTHH:mm:ss.ffffZ", "yyyy-MM-ddTHH:mm:ss.fffffZ", "yyyy-MM-ddTHH:mm:ss.ffffffZ", "yyyy-MM-ddTHH:mm:ss.fffffffZ", "yyyy-MM-ddTHH:mm:sszzzzzz", "yyyy-MM-ddTHH:mm:ss.fzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffzzzzzz", "yyyy-MM-ddTHH:mm:ss.fffzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffffzzzzzz", "yyyy-MM-ddTHH:mm:ss.fffffzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffffffzzzzzz", }; private static string[] s_allDateFormats = new string[] { "yyyy-MM-ddzzzzzz", "yyyy-MM-dd", "yyyy-MM-ddZ", "yyyy", "---dd", "---ddZ", "---ddzzzzzz", "--MM-dd", "--MM-ddZ", "--MM-ddzzzzzz", "--MM--", "--MM--Z", "--MM--zzzzzz", "yyyy-MM", "yyyy-MMZ", "yyyy-MMzzzzzz", "yyyyzzzzzz", }; private static string[] s_allTimeFormats = new string[] { "HH:mm:ss.fffffffzzzzzz", "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff", "HH:mm:ss.ffff", "HH:mm:ss.fffff", "HH:mm:ss.ffffff", "HH:mm:ss.fffffff", "HH:mm:ssZ", "HH:mm:ss.fZ", "HH:mm:ss.ffZ", "HH:mm:ss.fffZ", "HH:mm:ss.ffffZ", "HH:mm:ss.fffffZ", "HH:mm:ss.ffffffZ", "HH:mm:ss.fffffffZ", "HH:mm:sszzzzzz", "HH:mm:ss.fzzzzzz", "HH:mm:ss.ffzzzzzz", "HH:mm:ss.fffzzzzzz", "HH:mm:ss.ffffzzzzzz", "HH:mm:ss.fffffzzzzzz", "HH:mm:ss.ffffffzzzzzz", }; internal static DateTime ToDateTime(string value) { if (Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local) { return ToDateTime(value, s_allDateTimeFormats); } else { // for mode DateTimeSerializationMode.Roundtrip and DateTimeSerializationMode.Default return XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind); } } internal static DateTime ToDateTime(string value, string[] formats) { return XmlConvert.ToDateTime(value, formats); } internal static DateTime ToDate(string value) { return ToDateTime(value, s_allDateFormats); } internal static DateTime ToTime(string value) { if (!LocalAppContextSwitches.IgnoreKindInUtcTimeSerialization) { return DateTime.ParseExact(value, s_allTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.RoundtripKind); } else { return DateTime.ParseExact(value, s_allTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.NoCurrentDateDefault); } } internal static char ToChar(string value) { return (char)XmlConvert.ToUInt16(value); } internal static string ToXmlName(string value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } internal static string ToXmlNCName(string value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } internal static string ToXmlNmToken(string value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } internal static string ToXmlNmTokens(string value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } internal static byte[] ToByteArrayBase64(string value) { if (value == null) return null; value = value.Trim(); if (value.Length == 0) return Array.Empty<byte>(); return Convert.FromBase64String(value); } internal static byte[] ToByteArrayHex(string value) { if (value == null) return null; value = value.Trim(); return XmlConvert.FromBinHexString(value); } internal static long ToEnum(string val, Hashtable vals, string typeName, bool validate) { long value = 0; string[] parts = val.Split(null); for (int i = 0; i < parts.Length; i++) { object id = vals[parts[i]]; if (id != null) value |= (long)id; else if (validate && parts[i].Length > 0) throw new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, parts[i], typeName)); } return value; } private static string CollapseWhitespace(string value) { if (value == null) return null; return value.Trim(); } } }
using System.Collections.Generic; using Lucene.Net.Documents; namespace Lucene.Net.Index { using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using Lucene.Net.Util.Automaton; using NUnit.Framework; using AutomatonQuery = Lucene.Net.Search.AutomatonQuery; using BytesRef = Lucene.Net.Util.BytesRef; using CheckHits = Lucene.Net.Search.CheckHits; using Codec = Lucene.Net.Codecs.Codec; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using SeekStatus = Lucene.Net.Index.TermsEnum.SeekStatus; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestTermsEnum2 : LuceneTestCase { private Directory Dir; private IndexReader Reader; private IndexSearcher Searcher; private SortedSet<BytesRef> Terms; // the terms we put in the index private Automaton TermsAutomaton; // automata of the same internal int NumIterations; [SetUp] public override void SetUp() { base.SetUp(); // we generate aweful regexps: good for testing. // but for preflex codec, the test can be very slow, so use less iterations. NumIterations = Codec.Default.Name.Equals("Lucene3x") ? 10 * RANDOM_MULTIPLIER : AtLeast(50); Dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.KEYWORD, false)).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000))); Document doc = new Document(); Field field = NewStringField("field", "", Field.Store.YES); doc.Add(field); Terms = new SortedSet<BytesRef>(); int num = AtLeast(200); for (int i = 0; i < num; i++) { string s = TestUtil.RandomUnicodeString(Random()); field.StringValue = s; Terms.Add(new BytesRef(s)); writer.AddDocument(doc); } TermsAutomaton = BasicAutomata.MakeStringUnion(Terms); Reader = writer.Reader; Searcher = NewSearcher(Reader); writer.Dispose(); } [TearDown] public override void TearDown() { Reader.Dispose(); Dir.Dispose(); base.TearDown(); } /// <summary> /// tests a pre-intersected automaton against the original </summary> [Test] public virtual void TestFiniteVersusInfinite() { for (int i = 0; i < NumIterations; i++) { string reg = AutomatonTestUtil.RandomRegexp(Random()); Automaton automaton = (new RegExp(reg, RegExp.NONE)).ToAutomaton(); IList<BytesRef> matchedTerms = new List<BytesRef>(); foreach (BytesRef t in Terms) { if (BasicOperations.Run(automaton, t.Utf8ToString())) { matchedTerms.Add(t); } } Automaton alternate = BasicAutomata.MakeStringUnion(matchedTerms); //System.out.println("match " + matchedTerms.Size() + " " + alternate.getNumberOfStates() + " states, sigma=" + alternate.getStartPoints().Length); //AutomatonTestUtil.minimizeSimple(alternate); //System.out.println("minmize done"); AutomatonQuery a1 = new AutomatonQuery(new Term("field", ""), automaton); AutomatonQuery a2 = new AutomatonQuery(new Term("field", ""), alternate); CheckHits.CheckEqual(a1, Searcher.Search(a1, 25).ScoreDocs, Searcher.Search(a2, 25).ScoreDocs); } } /// <summary> /// seeks to every term accepted by some automata </summary> [Test] public virtual void TestSeeking() { for (int i = 0; i < NumIterations; i++) { string reg = AutomatonTestUtil.RandomRegexp(Random()); Automaton automaton = (new RegExp(reg, RegExp.NONE)).ToAutomaton(); TermsEnum te = MultiFields.GetTerms(Reader, "field").Iterator(null); IList<BytesRef> unsortedTerms = new List<BytesRef>(Terms); unsortedTerms = CollectionsHelper.Shuffle(unsortedTerms); foreach (BytesRef term in unsortedTerms) { if (BasicOperations.Run(automaton, term.Utf8ToString())) { // term is accepted if (Random().NextBoolean()) { // seek exact Assert.IsTrue(te.SeekExact(term)); } else { // seek ceil Assert.AreEqual(SeekStatus.FOUND, te.SeekCeil(term)); Assert.AreEqual(term, te.Term()); } } } } } /// <summary> /// mixes up seek and next for all terms </summary> [Test] public virtual void TestSeekingAndNexting() { for (int i = 0; i < NumIterations; i++) { TermsEnum te = MultiFields.GetTerms(Reader, "field").Iterator(null); foreach (BytesRef term in Terms) { int c = Random().Next(3); if (c == 0) { Assert.AreEqual(term, te.Next()); } else if (c == 1) { Assert.AreEqual(SeekStatus.FOUND, te.SeekCeil(term)); Assert.AreEqual(term, te.Term()); } else { Assert.IsTrue(te.SeekExact(term)); } } } } /// <summary> /// tests intersect: TODO start at a random term! </summary> [Test] public virtual void TestIntersect() { for (int i = 0; i < NumIterations; i++) { string reg = AutomatonTestUtil.RandomRegexp(Random()); Automaton automaton = (new RegExp(reg, RegExp.NONE)).ToAutomaton(); CompiledAutomaton ca = new CompiledAutomaton(automaton, SpecialOperations.IsFinite(automaton), false); TermsEnum te = MultiFields.GetTerms(Reader, "field").Intersect(ca, null); Automaton expected = BasicOperations.Intersection(TermsAutomaton, automaton); SortedSet<BytesRef> found = new SortedSet<BytesRef>(); while (te.Next() != null) { found.Add(BytesRef.DeepCopyOf(te.Term())); } Automaton actual = BasicAutomata.MakeStringUnion(found); Assert.IsTrue(BasicOperations.SameLanguage(expected, actual)); } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmCustomerStatementRun { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmCustomerStatementRun() : base() { FormClosed += frmCustomerStatementRun_FormClosed; KeyPress += frmCustomerStatementRun_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Button withEventsField_cmdClear; public System.Windows.Forms.Button cmdClear { get { return withEventsField_cmdClear; } set { if (withEventsField_cmdClear != null) { withEventsField_cmdClear.Click -= cmdClear_Click; } withEventsField_cmdClear = value; if (withEventsField_cmdClear != null) { withEventsField_cmdClear.Click += cmdClear_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPrint; public System.Windows.Forms.Button cmdPrint { get { return withEventsField_cmdPrint; } set { if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click -= cmdPrint_Click; } withEventsField_cmdPrint = value; if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click += cmdPrint_Click; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.CheckedListBox lstCustomer; public Microsoft.VisualBasic.PowerPacks.RectangleShape Shape1; public System.Windows.Forms.Label lbl; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.Shape1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdClear = new System.Windows.Forms.Button(); this.cmdPrint = new System.Windows.Forms.Button(); this.cmdExit = new System.Windows.Forms.Button(); this.lstCustomer = new System.Windows.Forms.CheckedListBox(); this.lbl = new System.Windows.Forms.Label(); this.picButtons.SuspendLayout(); this.SuspendLayout(); // //ShapeContainer1 // this.ShapeContainer1.Location = new System.Drawing.Point(0, 0); this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0); this.ShapeContainer1.Name = "ShapeContainer1"; this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this.Shape1 }); this.ShapeContainer1.Size = new System.Drawing.Size(358, 406); this.ShapeContainer1.TabIndex = 5; this.ShapeContainer1.TabStop = false; // //Shape1 // this.Shape1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this.Shape1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this.Shape1.BorderColor = System.Drawing.SystemColors.WindowText; this.Shape1.FillColor = System.Drawing.Color.Black; this.Shape1.Location = new System.Drawing.Point(9, 63); this.Shape1.Name = "Shape1"; this.Shape1.Size = new System.Drawing.Size(340, 328); // //picButtons // this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Controls.Add(this.cmdClear); this.picButtons.Controls.Add(this.cmdPrint); this.picButtons.Controls.Add(this.cmdExit); this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.Name = "picButtons"; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Size = new System.Drawing.Size(358, 39); this.picButtons.TabIndex = 1; // //cmdClear // this.cmdClear.BackColor = System.Drawing.SystemColors.Control; this.cmdClear.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClear.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClear.Location = new System.Drawing.Point(183, 3); this.cmdClear.Name = "cmdClear"; this.cmdClear.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClear.Size = new System.Drawing.Size(73, 29); this.cmdClear.TabIndex = 5; this.cmdClear.TabStop = false; this.cmdClear.Text = "&Clear All"; this.cmdClear.UseVisualStyleBackColor = false; // //cmdPrint // this.cmdPrint.BackColor = System.Drawing.SystemColors.Control; this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrint.Location = new System.Drawing.Point(5, 3); this.cmdPrint.Name = "cmdPrint"; this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrint.Size = new System.Drawing.Size(73, 29); this.cmdPrint.TabIndex = 3; this.cmdPrint.TabStop = false; this.cmdPrint.Text = "&Print"; this.cmdPrint.UseVisualStyleBackColor = false; // //cmdExit // this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Location = new System.Drawing.Point(276, 3); this.cmdExit.Name = "cmdExit"; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Size = new System.Drawing.Size(73, 29); this.cmdExit.TabIndex = 2; this.cmdExit.TabStop = false; this.cmdExit.Text = "E&xit"; this.cmdExit.UseVisualStyleBackColor = false; // //lstCustomer // this.lstCustomer.BackColor = System.Drawing.SystemColors.Window; this.lstCustomer.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lstCustomer.Cursor = System.Windows.Forms.Cursors.Default; this.lstCustomer.ForeColor = System.Drawing.SystemColors.WindowText; this.lstCustomer.Location = new System.Drawing.Point(21, 75); this.lstCustomer.Name = "lstCustomer"; this.lstCustomer.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lstCustomer.Size = new System.Drawing.Size(316, 302); this.lstCustomer.TabIndex = 0; this.lstCustomer.Tag = "0"; // //lbl // this.lbl.AutoSize = true; this.lbl.BackColor = System.Drawing.Color.Transparent; this.lbl.Cursor = System.Windows.Forms.Cursors.Default; this.lbl.ForeColor = System.Drawing.SystemColors.ControlText; this.lbl.Location = new System.Drawing.Point(12, 48); this.lbl.Name = "lbl"; this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lbl.Size = new System.Drawing.Size(68, 13); this.lbl.TabIndex = 4; this.lbl.Text = "&1. Customers"; // //frmCustomerStatementRun // this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.ClientSize = new System.Drawing.Size(358, 406); this.ControlBox = false; this.Controls.Add(this.picButtons); this.Controls.Add(this.lstCustomer); this.Controls.Add(this.lbl); this.Controls.Add(this.ShapeContainer1); this.Cursor = System.Windows.Forms.Cursors.Default; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Location = new System.Drawing.Point(3, 22); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmCustomerStatementRun"; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Customer Statement Run"; this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Collections; using System.Threading; using Tamir.SharpSsh.java.lang; using Tamir.SharpSsh.java.net; namespace Tamir.SharpSsh.jsch { /* -*-mode:java; c-basic-offset:2; -*- */ /* Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ChannelForwardedTCPIP : Channel { internal static ArrayList pool = new ArrayList(); // static private final int LOCAL_WINDOW_SIZE_MAX=0x20000; private static int LOCAL_WINDOW_SIZE_MAX = 0x100000; private static int LOCAL_MAXIMUM_PACKET_SIZE = 0x4000; internal SocketFactory factory = null; internal String target; internal int lport; internal int rport; internal ChannelForwardedTCPIP() : base() { setLocalWindowSizeMax(LOCAL_WINDOW_SIZE_MAX); setLocalWindowSize(LOCAL_WINDOW_SIZE_MAX); setLocalPacketSize(LOCAL_MAXIMUM_PACKET_SIZE); } public override void init() { try { io = new IO(); if (lport == -1) { var c = Type.GetType(target); ForwardedTCPIPDaemon daemon = (ForwardedTCPIPDaemon) Activator.CreateInstance(c); daemon.setChannel(this); Object[] foo = getPort(session, rport); daemon.setArg((Object[]) foo[3]); new JavaThread(daemon).Start(); connected = true; return; } else { Socket socket = (factory == null) ? new Socket(target, lport) : factory.createSocket(target, lport); socket.setTcpNoDelay(true); io.setInputStream(socket.getInputStream()); io.setOutputStream(socket.getOutputStream()); connected = true; } } catch (Exception e) { Console.WriteLine("target={0},port={1}", target, lport); Console.WriteLine(e); } } public override void run() { thread = new JavaThread(Thread.CurrentThread); Buffer buf = new Buffer(rmpsize); Packet packet = new Packet(buf); int i = 0; try { while (thread != null && io != null && io.ins != null) { i = io.ins.Read(buf.buffer, 14, buf.buffer.Length - 14 - 32 - 20 // padding and mac ); if (i <= 0) { eof(); break; } packet.reset(); if (_close) break; buf.putByte((byte) Session.SSH_MSG_CHANNEL_DATA); buf.putInt(recipient); buf.putInt(i); buf.skip(i); session.write(packet, this, i); } } catch (Exception) { //System.out.println(e); } //thread=null; //eof(); disconnect(); } internal override void getData(Buffer buf) { setRecipient(buf.getInt()); setRemoteWindowSize(buf.getInt()); setRemotePacketSize(buf.getInt()); byte[] addr = buf.getString(); int port = buf.getInt(); byte[] orgaddr = buf.getString(); int orgport = buf.getInt(); /* System.out.println("addr: "+new String(addr)); System.out.println("port: "+port); System.out.println("orgaddr: "+new String(orgaddr)); System.out.println("orgport: "+orgport); */ lock (pool) { for (int i = 0; i < pool.Count; i++) { Object[] foo = (Object[]) (pool[i]); if (foo[0] != session) continue; if (Int32.Parse(foo[1] + "") != port) continue; this.rport = port; this.target = (String) foo[2]; if (foo[3] == null || (foo[3] is Object[])) { this.lport = -1; } else { this.lport = Int32.Parse(foo[3] + ""); } if (foo.Length >= 5) { this.factory = ((SocketFactory) foo[4]); } break; } if (target == null) { Console.WriteLine("??"); } } } internal static Object[] getPort(Session session, int rport) { lock (pool) { for (int i = 0; i < pool.Count; i++) { Object[] bar = (Object[]) (pool[i]); if (bar[0] != session) continue; if (Int32.Parse(bar[1] + "") != rport) continue; return bar; } return null; } } internal static String[] getPortForwarding(Session session) { ArrayList foo = new ArrayList(); lock (pool) { for (int i = 0; i < pool.Count; i++) { Object[] bar = (Object[]) (pool[i]); if (bar[0] != session) continue; if (bar[3] == null) { foo.Add(bar[1] + ":" + bar[2] + ":"); } else { foo.Add(bar[1] + ":" + bar[2] + ":" + bar[3]); } } } String[] bar2 = new String[foo.Count]; for (int i = 0; i < foo.Count; i++) { bar2[i] = (String) (foo[i]); } return bar2; } internal static void addPort(Session session, int port, String target, int lport, SocketFactory factory) { lock (pool) { if (getPort(session, port) != null) { throw new JSchException("PortForwardingR: remote port " + port + " is already registered."); } Object[] foo = new Object[5]; foo[0] = session; foo[1] = int.Parse(port + ""); foo[2] = target; foo[3] = int.Parse(port + ""); foo[4] = factory; pool.Add(foo); } } internal static void addPort(Session session, int port, String daemon, Object[] arg) { lock (pool) { if (getPort(session, port) != null) { throw new JSchException("PortForwardingR: remote port " + port + " is already registered."); } Object[] foo = new Object[4]; foo[0] = session; foo[1] = int.Parse(port + ""); foo[2] = daemon; foo[3] = arg; pool.Add(foo); } } internal static void delPort(ChannelForwardedTCPIP c) { delPort(c.session, c.rport); } internal static void delPort(Session session, int rport) { lock (pool) { Object[] foo = null; for (int i = 0; i < pool.Count; i++) { Object[] bar = (Object[]) (pool[i]); if (bar[0] != session) continue; if (int.Parse(bar[1] + "") != rport) continue; foo = bar; break; } if (foo == null) return; pool.Remove(foo); } Buffer buf = new Buffer(100); // ?? Packet packet = new Packet(buf); try { // byte SSH_MSG_GLOBAL_REQUEST 80 // string "cancel-tcpip-forward" // boolean want_reply // string address_to_bind (e.g. "127.0.0.1") // uint32 port number to bind packet.reset(); buf.putByte((byte) 80 /*SSH_MSG_GLOBAL_REQUEST*/); buf.putString("cancel-tcpip-forward".GetBytes()); buf.putByte((byte) 0); buf.putString("0.0.0.0".GetBytes()); buf.putInt(rport); session.write(packet); } catch (Exception) { // throw new JSchException(e.toString()); } } internal static void delPort(Session session) { int[] rport = null; int count = 0; lock (pool) { rport = new int[pool.Count]; for (int i = 0; i < pool.Count; i++) { Object[] bar = (Object[]) (pool[i]); if (bar[0] == session) { rport[count++] = int.Parse(bar[1] + ""); } } } for (int i = 0; i < count; i++) { delPort(session, rport[i]); } } public int getRemotePort() { return rport; } private void setSocketFactory(SocketFactory factory) { this.factory = factory; } } }
using System; using System.Diagnostics; using System.Text; using u32 = System.UInt32; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2004 April 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used to translate between UTF-8, ** UTF-16, UTF-16BE, and UTF-16LE. ** ** Notes on UTF-8: ** ** Byte-0 Byte-1 Byte-2 Byte-3 Value ** 0xxxxxxx 00000000 00000000 0xxxxxxx ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** ** ** Notes on UTF-16: (with wwww+1==uuuuu) ** ** Word-0 Word-1 Value ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx ** ** ** BOM or Byte Order Mark: ** 0xff 0xfe little-endian utf-16 follows ** 0xfe 0xff big-endian utf-16 follows ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "sqliteInt.h" //#include <assert.h> //#include "vdbeInt.h" #if !SQLITE_AMALGAMATION /* ** The following constant value is used by the SQLITE_BIGENDIAN and ** SQLITE_LITTLEENDIAN macros. */ //const int sqlite3one = 1; #endif //* SQLITE_AMALGAMATION */ /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. */ static byte[] sqlite3Utf8Trans1 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; //#define WRITE_UTF8(zOut, c) { \ // if( c<0x00080 ){ \ // *zOut++ = (u8)(c&0xFF); \ // } \ // else if( c<0x00800 ){ \ // *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // } \ // else if( c<0x10000 ){ \ // *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ // *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // }else{ \ // *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ // *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ // *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // } \ //} //#define WRITE_UTF16LE(zOut, c) { \ // if( c<=0xFFFF ){ \ // *zOut++ = (u8)(c&0x00FF); \ // *zOut++ = (u8)((c>>8)&0x00FF); \ // }else{ \ // *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ // *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ // *zOut++ = (u8)(c&0x00FF); \ // *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ // } \ //} //#define WRITE_UTF16BE(zOut, c) { \ // if( c<=0xFFFF ){ \ // *zOut++ = (u8)((c>>8)&0x00FF); \ // *zOut++ = (u8)(c&0x00FF); \ // }else{ \ // *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ // *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ // *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ // *zOut++ = (u8)(c&0x00FF); \ // } \ //} //#define READ_UTF16LE(zIn, TERM, c){ \ // c = (*zIn++); \ // c += ((*zIn++)<<8); \ // if( c>=0xD800 && c<0xE000 && TERM ){ \ // int c2 = (*zIn++); \ // c2 += ((*zIn++)<<8); \ // c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ // } \ //} //#define READ_UTF16BE(zIn, TERM, c){ \ // c = ((*zIn++)<<8); \ // c += (*zIn++); \ // if( c>=0xD800 && c<0xE000 && TERM ){ \ // int c2 = ((*zIn++)<<8); \ // c2 += (*zIn++); \ // c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ // } \ //} /* ** Translate a single UTF-8 character. Return the unicode value. ** ** During translation, assume that the byte that zTerm points ** is a 0x00. ** ** Write a pointer to the next unread byte back into pzNext. ** ** Notes On Invalid UTF-8: ** ** * This routine never allows a 7-bit character (0x00 through 0x7f) to ** be encoded as a multi-byte character. Any multi-byte character that ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. ** ** * This routine never allows a UTF16 surrogate value to be encoded. ** If a multi-byte character attempts to encode a value between ** 0xd800 and 0xe000 then it is rendered as 0xfffd. ** ** * Bytes in the range of 0x80 through 0xbf which occur as the first ** byte of a character are interpreted as single-byte characters ** and rendered as themselves even though they are technically ** invalid characters. ** ** * This routine accepts an infinite number of different UTF8 encodings ** for unicode values 0x80 and greater. It do not change over-length ** encodings to 0xfffd as some systems recommend. */ //#define READ_UTF8(zIn, zTerm, c) \ // c = *(zIn++); \ // if( c>=0xc0 ){ \ // c = sqlite3Utf8Trans1[c-0xc0]; \ // while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ // c = (c<<6) + (0x3f & *(zIn++)); \ // } \ // if( c<0x80 \ // || (c&0xFFFFF800)==0xD800 \ // || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ // } static int sqlite3Utf8Read( string zIn, /* First byte of UTF-8 character */ ref string pzNext /* Write first byte past UTF-8 char here */ ) { //unsigned int c; /* Same as READ_UTF8() above but without the zTerm parameter. ** For this routine, we assume the UTF8 string is always zero-terminated. */ if ( String.IsNullOrEmpty( zIn ) ) return 0; //c = *( zIn++ ); //if ( c >= 0xc0 ) //{ // c = sqlite3Utf8Trans1[c - 0xc0]; // while ( ( *zIn & 0xc0 ) == 0x80 ) // { // c = ( c << 6 ) + ( 0x3f & *( zIn++ ) ); // } // if ( c < 0x80 // || ( c & 0xFFFFF800 ) == 0xD800 // || ( c & 0xFFFFFFFE ) == 0xFFFE ) { c = 0xFFFD; } //} //*pzNext = zIn; int zIndex = 0; int c = zIn[zIndex++]; if ( c >= 0xc0 ) { //if ( c > 0xff ) c = 0; //else { //c = sqlite3Utf8Trans1[c - 0xc0]; while ( zIndex != zIn.Length && ( zIn[zIndex] & 0xc0 ) == 0x80 ) { c = ( c << 6 ) + ( 0x3f & zIn[zIndex++] ); } if ( c < 0x80 || ( c & 0xFFFFF800 ) == 0xD800 || ( c & 0xFFFFFFFE ) == 0xFFFE ) { c = 0xFFFD; } } } pzNext = zIn.Substring( zIndex ); return c; } /* ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). */ /* #define TRANSLATE_TRACE 1 */ #if ! SQLITE_OMIT_UTF16 /* ** This routine transforms the internal text encoding used by pMem to ** desiredEnc. It is an error if the string is already of the desired ** encoding, or if pMem does not contain a string value. */ static int sqlite3VdbeMemTranslate(Mem pMem, int desiredEnc){ int len; /* Maximum length of output string in bytes */ Debugger.Break (); // TODO - //unsigned char *zOut; /* Output buffer */ //unsigned char *zIn; /* Input iterator */ //unsigned char *zTerm; /* End of input */ //unsigned char *z; /* Output iterator */ //unsigned int c; Debug.Assert( pMem.db==null || sqlite3_mutex_held(pMem.db.mutex) ); Debug.Assert( (pMem.flags&MEM_Str )!=0); Debug.Assert( pMem.enc!=desiredEnc ); Debug.Assert( pMem.enc!=0 ); Debug.Assert( pMem.n>=0 ); #if TRANSLATE_TRACE && SQLITE_DEBUG { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "INPUT: %s\n", zBuf); } #endif /* If the translation is between UTF-16 little and big endian, then ** all that is required is to swap the byte order. This case is handled ** differently from the others. */ Debugger.Break (); // TODO - //if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ // u8 temp; // int rc; // rc = sqlite3VdbeMemMakeWriteable(pMem); // if( rc!=SQLITE_OK ){ // Debug.Assert( rc==SQLITE_NOMEM ); // return SQLITE_NOMEM; // } // zIn = (u8*)pMem.z; // zTerm = &zIn[pMem->n&~1]; // while( zIn<zTerm ){ // temp = *zIn; // *zIn = *(zIn+1); // zIn++; // *zIn++ = temp; // } // pMem->enc = desiredEnc; // goto translate_out; //} /* Set len to the maximum number of bytes required in the output buffer. */ if( desiredEnc==SQLITE_UTF8 ){ /* When converting from UTF-16, the maximum growth results from ** translating a 2-byte character to a 4-byte UTF-8 character. ** A single byte is required for the output string ** nul-terminator. */ pMem->n &= ~1; len = pMem.n * 2 + 1; }else{ /* When converting from UTF-8 to UTF-16 the maximum growth is caused ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 ** character. Two bytes are required in the output buffer for the ** nul-terminator. */ len = pMem.n * 2 + 2; } /* Set zIn to point at the start of the input buffer and zTerm to point 1 ** byte past the end. ** ** Variable zOut is set to point at the output buffer, space obtained ** from sqlite3Malloc(). */ Debugger.Break (); // TODO - //zIn = (u8*)pMem.z; //zTerm = &zIn[pMem->n]; //zOut = sqlite3DbMallocRaw(pMem->db, len); //if( !zOut ){ // return SQLITE_NOMEM; //} //z = zOut; //if( pMem->enc==SQLITE_UTF8 ){ // if( desiredEnc==SQLITE_UTF16LE ){ // /* UTF-8 -> UTF-16 Little-endian */ // while( zIn<zTerm ){ ///* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */ //READ_UTF8(zIn, zTerm, c); // WRITE_UTF16LE(z, c); // } // }else{ // Debug.Assert( desiredEnc==SQLITE_UTF16BE ); // /* UTF-8 -> UTF-16 Big-endian */ // while( zIn<zTerm ){ ///* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */ //READ_UTF8(zIn, zTerm, c); // WRITE_UTF16BE(z, c); // } // } // pMem->n = (int)(z - zOut); // *z++ = 0; //}else{ // Debug.Assert( desiredEnc==SQLITE_UTF8 ); // if( pMem->enc==SQLITE_UTF16LE ){ // /* UTF-16 Little-endian -> UTF-8 */ // while( zIn<zTerm ){ // READ_UTF16LE(zIn, zIn<zTerm, c); // WRITE_UTF8(z, c); // } // }else{ // /* UTF-16 Big-endian -> UTF-8 */ // while( zIn<zTerm ){ // READ_UTF16BE(zIn, zIn<zTerm, c); // WRITE_UTF8(z, c); // } // } // pMem->n = (int)(z - zOut); //} //*z = 0; //Debug.Assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); //sqlite3VdbeMemRelease(pMem); //pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem); //pMem->enc = desiredEnc; //pMem->flags |= (MEM_Term|MEM_Dyn); //pMem.z = (char*)zOut; //pMem.zMalloc = pMem.z; translate_out: #if TRANSLATE_TRACE && SQLITE_DEBUG { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "OUTPUT: %s\n", zBuf); } #endif return SQLITE_OK; } /* ** This routine checks for a byte-order mark at the beginning of the ** UTF-16 string stored in pMem. If one is present, it is removed and ** the encoding of the Mem adjusted. This routine does not do any ** byte-swapping, it just sets Mem.enc appropriately. ** ** The allocation (static, dynamic etc.) and encoding of the Mem may be ** changed by this function. */ static int sqlite3VdbeMemHandleBom(Mem pMem){ int rc = SQLITE_OK; int bom = 0; byte[] b01 = new byte[2]; Encoding.Unicode.GetBytes( pMem.z, 0, 1,b01,0 ); assert( pMem->n>=0 ); if( pMem->n>1 ){ // u8 b1 = *(u8 *)pMem.z; // u8 b2 = *(((u8 *)pMem.z) + 1); if( b01[0]==0xFE && b01[1]==0xFF ){// if( b1==0xFE && b2==0xFF ){ bom = SQLITE_UTF16BE; } if( b01[0]==0xFF && b01[1]==0xFE ){ // if( b1==0xFF && b2==0xFE ){ bom = SQLITE_UTF16LE; } } if( bom!=0 ){ rc = sqlite3VdbeMemMakeWriteable(pMem); if( rc==SQLITE_OK ){ pMem.n -= 2; Debugger.Break (); // TODO - //memmove(pMem.z, pMem.z[2], pMem.n); //pMem.z[pMem.n] = '\0'; //pMem.z[pMem.n+1] = '\0'; pMem.flags |= MEM_Term; pMem.enc = bom; } } return rc; } #endif // * SQLITE_OMIT_UTF16 */ /* ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, ** return the number of unicode characters in pZ up to (but not including) ** the first 0x00 byte. If nByte is not less than zero, return the ** number of unicode characters in the first nByte of pZ (or up to ** the first 0x00, whichever comes first). */ static int sqlite3Utf8CharLen( string zIn, int nByte ) { //int r = 0; //string z = zIn; if ( zIn.Length == 0 ) return 0; int zInLength = zIn.Length; int zTerm = ( nByte >= 0 && nByte <= zInLength ) ? nByte : zInLength; //Debug.Assert( z<=zTerm ); //for ( int i = 0 ; i < zTerm ; i++ ) //while( *z!=0 && z<zTerm ){ //{ // SQLITE_SKIP_UTF8( ref z);// SQLITE_SKIP_UTF8(z); // r++; //} //return r; if ( zTerm == zInLength ) return zInLength - ( zIn[zTerm - 1] == 0 ? 1 : 0 ); else return nByte; } /* This test function is not currently used by the automated test-suite. ** Hence it is only available in debug builds. */ #if SQLITE_TEST && SQLITE_DEBUG /* ** Translate UTF-8 to UTF-8. ** ** This has the effect of making sure that the string is well-formed ** UTF-8. Miscoded characters are removed. ** ** The translation is done in-place and aborted if the output ** overruns the input. */ static int sqlite3Utf8To8(byte[] zIn){ //byte[] zOut = zIn; //byte[] zStart = zIn; //u32 c; // while( zIn[0] && zOut<=zIn ){ // c = sqlite3Utf8Read(zIn, (const u8**)&zIn); // if( c!=0xfffd ){ // WRITE_UTF8(zOut, c); // } //} //zOut = 0; //return (int)(zOut - zStart); try { string z1 = Encoding.UTF8.GetString( zIn ); byte[] zOut = Encoding.UTF8.GetBytes( z1 ); //if ( zOut.Length != zIn.Length ) // return 0; //else { Array.Copy( zOut, 0, zIn, 0,zIn.Length ); return zIn.Length;} } catch ( EncoderFallbackException e ) { return 0; } } #endif #if !SQLITE_OMIT_UTF16 /* ** Convert a UTF-16 string in the native encoding into a UTF-8 string. ** Memory to hold the UTF-8 string is obtained from sqlite3Malloc and must ** be freed by the calling function. ** ** NULL is returned if there is an allocation error. */ static string sqlite3Utf16to8(sqlite3 db, string z, int nByte, u8 enc){ Debugger.Break (); // TODO - Mem m = Pool.Allocate_Mem(); // memset(&m, 0, sizeof(m)); // m.db = db; // sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC); // sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8); // if( db.mallocFailed !=0{ // sqlite3VdbeMemRelease(&m); // m.z = 0; // } // Debug.Assert( (m.flags & MEM_Term)!=0 || db.mallocFailed !=0); // Debug.Assert( (m.flags & MEM_Str)!=0 || db.mallocFailed !=0); assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed ); assert( m.z || db->mallocFailed ); return m.z; } /* ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter ** enc. A pointer to the new string is returned, and the value of *pnOut ** is set to the length of the returned string in bytes. The call should ** arrange to call sqlite3DbFree() on the returned pointer when it is ** no longer required. ** ** If a malloc failure occurs, NULL is returned and the db.mallocFailed ** flag set. */ #if SQLITE_ENABLE_STAT2 char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){ Mem m; memset(&m, 0, sizeof(m)); m.db = db; sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC); if( sqlite3VdbeMemTranslate(&m, enc) ){ assert( db->mallocFailed ); return 0; } assert( m.z==m.zMalloc ); *pnOut = m.n; return m.z; } #endif /* ** zIn is a UTF-16 encoded unicode string at least nChar characters long. ** Return the number of bytes in the first nChar unicode characters ** in pZ. nChar must be non-negative. */ int sqlite3Utf16ByteLen(const void *zIn, int nChar){ int c; unsigned char const *z = zIn; int n = 0; if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){ while( n<nChar ){ READ_UTF16BE(z, 1, c); n++; } }else{ while( n<nChar ){ READ_UTF16LE(z, 1, c); n++; } } return (int)(z-(unsigned char const *)zIn); } #if SQLITE_TEST /* ** This routine is called from the TCL test function "translate_selftest". ** It checks that the primitives for serializing and deserializing ** characters in each encoding are inverses of each other. */ /* ** This routine is called from the TCL test function "translate_selftest". ** It checks that the primitives for serializing and deserializing ** characters in each encoding are inverses of each other. */ void sqlite3UtfSelfTest(void){ unsigned int i, t; unsigned char zBuf[20]; unsigned char *z; int n; unsigned int c; for(i=0; i<0x00110000; i++){ z = zBuf; WRITE_UTF8(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; c = sqlite3Utf8Read(z, (const u8**)&z); t = i; if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; assert( c==t ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16LE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16LE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16BE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16BE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } } #endif // * SQLITE_TEST */ #endif // * SQLITE_OMIT_UTF16 */ } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace MindTouch.Dream { /// <summary> /// Provides Dream Service meta-data for <see cref="IDreamService"/> implementations. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public class DreamServiceAttribute : Attribute { //--- Fields --- private string _name; private string _copyright; private string _info; private XUri[] _sid; //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> /// <param name="name">Dream Service name.</param> /// <param name="copyright">Copyright notice.</param> public DreamServiceAttribute(string name, string copyright) { _name = name; _copyright = copyright; } /// <summary> /// Create new attribute. /// </summary> /// <param name="name">Dream Service name.</param> /// <param name="copyright">Copyright notice.</param> /// <param name="info">Service information Uri.</param> public DreamServiceAttribute(string name, string copyright, string info) { _name = name; _copyright = copyright; _info = info; } //--- Properties --- /// <summary> /// Dream Service name. /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Copyright notice. /// </summary> public string Copyright { get { return _copyright; } set { _copyright = value; } } /// <summary> /// Service inforamtion Uri. /// </summary> public string Info { get { return _info; } set { _info = value; } } /// <summary> /// Service Identifier Uris. /// </summary> public string[] SID { get { return Array.ConvertAll<XUri, string>(_sid, delegate(XUri uri) { return uri.ToString(); }); } set { _sid = Array.ConvertAll<string, XUri>(value, delegate(string uri) { return new XUri(uri); }); } } //--- Methods --- /// <summary> /// Get all Service Identifiers as XUri array. /// </summary> /// <returns>Array of Service Identifiers.</returns> public XUri[] GetSIDAsUris() { return _sid ?? new XUri[0]; } } /// <summary> /// Provides meta data about expected service configuration key. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public class DreamServiceConfigAttribute : Attribute { //--- Fields --- private string _name; private string _valueType; private string _description; //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> /// <param name="name">Configuration Key.</param> /// <param name="type">Configuration Data Type.</param> /// <param name="description">Description of configuration value.</param> public DreamServiceConfigAttribute(string name, string type, string description) { _name = name; _valueType = type; _description = description; } //--- Properties --- /// <summary> /// Configuration key. /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Configuration Data Type. /// </summary> public string ValueType { get { return _valueType; } set { _valueType = value; } } /// <summary> /// Description of configuration value. /// </summary> public string Description { get { return _description; } set { _description = value; } } } /// <summary> /// Provides addtional <see cref="IDreamService"/> blueprint meta-data. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public class DreamServiceBlueprintAttribute : Attribute { //--- Fields --- /// <summary> /// Name of meta-data key. /// </summary> public string Name; /// <summary> /// Blueprint meta-data value. /// </summary> public string Value; //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> /// <param name="name">Name of meta-data key.</param> /// <param name="value">Blueprint meta-data value.</param> public DreamServiceBlueprintAttribute(string name, string value) { if(string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } this.Name = name; this.Value = value; } /// <summary> /// Create new attribute /// </summary> /// <param name="name">Name of meta-data key.</param> public DreamServiceBlueprintAttribute(string name) : this(name, string.Empty) { } } /// <summary> /// Marks a method as <see cref="DreamFeature"/> and provides feature meta-data. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class DreamFeatureAttribute : Attribute { // TODO (steveb): enforce syntax for feature definitions // NOTE (steveb): grammar for definition string // definition ::= id ":" path pattern // path ::= ( id // "/" ) // pattern ::= ( "/" // ( "*" | name | id )? ( "/" ( name )? "?" )* ( "//" ( "*" | name ))? ( "/" )? // name ::= "{" id "}" // id ::= ( 'a'..'z' | 'A'..'Z' | '0'..'9' | '-' | '.' | '_' | '~' | '%' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' | ':' | '@' )* //--- Fields --- private string _pattern; private string _description; private string _info; private string _version = "*"; private string _obsolete = null; //--- Constructors --- /// <summary> /// Obsolete: This form of the attribute construtor is deprecated. Please DreamFeatureAttribute(string,string) instead. /// </summary> [Obsolete("This form of the attribute construtor is deprecated. Please DreamFeatureAttribute(string,string) instead.")] public DreamFeatureAttribute(string path, string signature, string verb, string description, string info) { // remove trailing slash if((path.Length > 0) && (path[path.Length - 1] == '/')) { path = path.Substring(0, path.Length - 1); } // add initial slash if((signature.Length == 0) || (signature[0] != '/')) { signature = "/" + signature; } // initialize fields _pattern = verb + ":" + path + signature; _description = description; _info = info; } /// <summary> /// Create new attribute. /// </summary> /// <param name="pattern">The Uri pattern that this feature responds to.</param> /// <param name="description">Description of the <see cref="DreamFeature"/>.</param> public DreamFeatureAttribute(string pattern, string description) { _pattern = pattern; _description = description; } //--- Properties --- /// <summary> /// The Uri pattern that this feature responds to. /// </summary> public string Pattern { get { return _pattern; } set { _pattern = value; } } /// <summary> /// Description of the <see cref="DreamFeature"/>. /// </summary> public string Description { get { return _description; } set { _description = value; } } /// <summary> /// Information Uri for this <see cref="DreamFeature"/>. /// </summary> public string Info { get { return _info; } set { _info = value; } } /// <summary> /// <see cref="DreamFeature"/> Version. /// </summary> public string Version { get { return _version; } set { _version = value; } } /// <summary> /// True if this feature is obsolete. /// </summary> public string Obsolete { get { return _obsolete; } set { _obsolete = value; } } } /// <summary> /// Defines a <see cref="DreamFeature"/> input parameter. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class DreamFeatureParamAttribute : Attribute { //--- Fields --- private string _name; private string _valueType; private string _description; //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> /// <param name="name">Name of the parameter.</param> /// <param name="type">Parameter Data Type.</param> /// <param name="description">Description of the parameter.</param> public DreamFeatureParamAttribute(string name, string type, string description) { _name = name; _valueType = type; _description = description; } //--- Properties --- /// <summary> /// Name of the parameter. /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Parameter Data Type. /// </summary> public string ValueType { get { return _valueType; } set { _valueType = value; } } /// <summary> /// Description of the parameter. /// </summary> public string Description { get { return _description; } set { _description = value; } } } /// <summary> /// Provides <see cref="DreamFeature"/> meta-data about possible <see cref="DreamStatus"/> responses from feature. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class DreamFeatureStatusAttribute : Attribute { //--- Fields --- private DreamStatus _status; private string _description; //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> /// <param name="status">Status message for Feature.</param> /// <param name="description">Description of scenario under which Status is returned.</param> public DreamFeatureStatusAttribute(DreamStatus status, string description) { _status = status; _description = description; } //--- Properties --- /// <summary> /// Status message for Feature. /// </summary> public DreamStatus Status { get { return _status; } set { _status = value; } } /// <summary> /// Description of scenario under which Status is returned. /// </summary> public string Description { get { return _description; } set { _description = value; } } } /// <summary> /// Defines a <see cref="DreamFeature"/> input header parameter. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public class HeaderAttribute : Attribute { //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> public HeaderAttribute() { } /// <summary> /// Create new attribute. /// </summary> public HeaderAttribute(string description) { this.Description = description; } //--- Properties --- /// <summary> /// Name of the parameter. /// </summary> public string Name { get; set; } /// <summary> /// Description of the parameter. /// </summary> public string Description { get; set; } } /// <summary> /// Defines a <see cref="DreamFeature"/> input cookie parameter. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public class CookieAttribute : Attribute { //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> public CookieAttribute() { } /// <summary> /// Create new attribute. /// </summary> /// <param name="description">Description of the parameter.</param> public CookieAttribute(string description) { this.Description = description; } //--- Properties --- /// <summary> /// Name of the parameter. /// </summary> public string Name { get; set; } /// <summary> /// Description of the parameter. /// </summary> public string Description { get; set; } } /// <summary> /// Defines a <see cref="DreamFeature"/> input path parameter. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public class PathAttribute : Attribute { //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> public PathAttribute() { } /// <summary> /// Create new attribute. /// </summary> /// <param name="description">Description of the parameter.</param> public PathAttribute(string description) { this.Description = description; } //--- Properties --- /// <summary> /// Name of the parameter. /// </summary> public string Name { get; set; } /// <summary> /// Description of the parameter. /// </summary> public string Description { get; set; } } /// <summary> /// Defines a <see cref="DreamFeature"/> input query parameter. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public class QueryAttribute : Attribute { //--- Constructors --- /// <summary> /// Create new attribute. /// </summary> public QueryAttribute() { } /// <summary> /// Create new attribute. /// </summary> /// <param name="description">Description of the parameter.</param> public QueryAttribute(string description) { this.Description = description; } //--- Properties --- /// <summary> /// Name of the parameter. /// </summary> public string Name { get; set; } /// <summary> /// Description of the parameter. /// </summary> public string Description { get; set; } } }
// 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.Xml; using System.Text; using System.Collections; using System.Globalization; using System.Diagnostics; using System.Reflection; namespace System.Xml.Schema { // This is an atomic value converted for Silverlight XML core that knows only how to convert to and from string. // It does not recognize XmlAtomicValue or XPathItemType. internal class XmlUntypedStringConverter { // Fields private bool _listsAllowed; private XmlUntypedStringConverter _listItemConverter; // Cached types private static readonly Type s_decimalType = typeof(decimal); private static readonly Type s_int32Type = typeof(int); private static readonly Type s_int64Type = typeof(long); private static readonly Type s_stringType = typeof(string); private static readonly Type s_objectType = typeof(object); private static readonly Type s_byteType = typeof(byte); private static readonly Type s_int16Type = typeof(short); private static readonly Type s_SByteType = typeof(sbyte); private static readonly Type s_UInt16Type = typeof(ushort); private static readonly Type s_UInt32Type = typeof(uint); private static readonly Type s_UInt64Type = typeof(ulong); private static readonly Type s_doubleType = typeof(double); private static readonly Type s_singleType = typeof(float); private static readonly Type s_dateTimeType = typeof(DateTime); private static readonly Type s_dateTimeOffsetType = typeof(DateTimeOffset); private static readonly Type s_booleanType = typeof(bool); private static readonly Type s_byteArrayType = typeof(Byte[]); private static readonly Type s_xmlQualifiedNameType = typeof(XmlQualifiedName); private static readonly Type s_uriType = typeof(Uri); private static readonly Type s_timeSpanType = typeof(TimeSpan); private static readonly string s_untypedStringTypeName = "xdt:untypedAtomic"; // Static convertor instance internal static XmlUntypedStringConverter Instance = new XmlUntypedStringConverter(true); private XmlUntypedStringConverter(bool listsAllowed) { _listsAllowed = listsAllowed; if (listsAllowed) { _listItemConverter = new XmlUntypedStringConverter(false); } } internal string ToString(object value, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException("value"); Type sourceType = value.GetType(); //we can consider avoiding the type equality checks and instead doing a "is" check //similar to what we did for Uri and XmlQualifiedName below if (sourceType == s_booleanType) return XmlConvert.ToString((bool)value); if (sourceType == s_byteType) return XmlConvert.ToString((byte)value); if (sourceType == s_byteArrayType) return Base64BinaryToString((byte[])value); if (sourceType == s_dateTimeType) return DateTimeToString((DateTime)value); if (sourceType == s_dateTimeOffsetType) return DateTimeOffsetToString((DateTimeOffset)value); if (sourceType == s_decimalType) return XmlConvert.ToString((decimal)value); if (sourceType == s_doubleType) return XmlConvert.ToString((double)value); if (sourceType == s_int16Type) return XmlConvert.ToString((short)value); if (sourceType == s_int32Type) return XmlConvert.ToString((int)value); if (sourceType == s_int64Type) return XmlConvert.ToString((long)value); if (sourceType == s_SByteType) return XmlConvert.ToString((sbyte)value); if (sourceType == s_singleType) return XmlConvert.ToString((float)value); if (sourceType == s_stringType) return ((string)value); if (sourceType == s_timeSpanType) return DurationToString((TimeSpan)value); if (sourceType == s_UInt16Type) return XmlConvert.ToString((ushort)value); if (sourceType == s_UInt32Type) return XmlConvert.ToString((uint)value); if (sourceType == s_UInt64Type) return XmlConvert.ToString((ulong)value); if (value is Uri) return AnyUriToString((Uri)value); if (value is XmlQualifiedName) return QNameToString((XmlQualifiedName)value, nsResolver); return (string)ListTypeToString(value, nsResolver); } internal object FromString(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException("value"); if (destinationType == null) throw new ArgumentNullException("destinationType"); if (destinationType == s_objectType) destinationType = typeof(string); if (destinationType == s_booleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == s_byteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); if (destinationType == s_byteArrayType) return StringToBase64Binary((string)value); if (destinationType == s_dateTimeType) return StringToDateTime((string)value); if (destinationType == s_dateTimeOffsetType) return StringToDateTimeOffset((string)value); if (destinationType == s_decimalType) return XmlConvert.ToDecimal((string)value); if (destinationType == s_doubleType) return XmlConvert.ToDouble((string)value); if (destinationType == s_int16Type) return Int32ToInt16(XmlConvert.ToInt32((string)value)); if (destinationType == s_int32Type) return XmlConvert.ToInt32((string)value); if (destinationType == s_int64Type) return XmlConvert.ToInt64((string)value); if (destinationType == s_SByteType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); if (destinationType == s_singleType) return XmlConvert.ToSingle((string)value); if (destinationType == s_timeSpanType) return StringToDuration((string)value); if (destinationType == s_UInt16Type) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); if (destinationType == s_UInt32Type) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); if (destinationType == s_UInt64Type) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); if (destinationType == s_uriType) return XmlConvert.ToUri((string)value); if (destinationType == s_xmlQualifiedNameType) return StringToQName((string)value, nsResolver); if (destinationType == s_stringType) return ((string)value); return StringToListType(value, destinationType, nsResolver); } private byte Int32ToByte(int value) { if (value < (int)Byte.MinValue || value > (int)Byte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "Byte")); return (byte)value; } private short Int32ToInt16(int value) { if (value < (int)Int16.MinValue || value > (int)Int16.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "Int16")); return (short)value; } private sbyte Int32ToSByte(int value) { if (value < (int)SByte.MinValue || value > (int)SByte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "SByte")); return (sbyte)value; } private ushort Int32ToUInt16(int value) { if (value < (int)UInt16.MinValue || value > (int)UInt16.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "UInt16")); return (ushort)value; } private uint Int64ToUInt32(long value) { if (value < (long)UInt32.MinValue || value > (long)UInt32.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "UInt32")); return (uint)value; } private ulong DecimalToUInt64(decimal value) { if (value < (decimal)UInt64.MinValue || value > (decimal)UInt64.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "UInt64")); return (ulong)value; } private string Base64BinaryToString(byte[] value) { return Convert.ToBase64String(value); } private byte[] StringToBase64Binary(string value) { return Convert.FromBase64String(XmlConvert.TrimString(value)); } private string DateTimeToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } private static DateTime StringToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private static string DateTimeOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } private static DateTimeOffset StringToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private string DurationToString(TimeSpan value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToString(XsdDuration.DurationType.Duration); } private TimeSpan StringToDuration(string value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToTimeSpan(XsdDuration.DurationType.Duration); } private string AnyUriToString(Uri value) { return value.OriginalString; } protected static string QNameToString(XmlQualifiedName qname, IXmlNamespaceResolver nsResolver) { string prefix; if (nsResolver == null) { return string.Concat("{", qname.Namespace, "}", qname.Name); } prefix = nsResolver.LookupPrefix(qname.Namespace); if (prefix == null) { throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname.ToString(), qname.Namespace)); } return (prefix.Length != 0) ? string.Concat(prefix, ":", qname.Name) : qname.Name; } private static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolver nsResolver) { string prefix, localName, ns; value = value.Trim(); // Parse prefix:localName try { ValidateNames.ParseQNameThrow(value, out prefix, out localName); } catch (XmlException e) { throw new FormatException(e.Message); } // Throw error if no namespaces are in scope if (nsResolver == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); if (ns == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualfiedName return new XmlQualifiedName(localName, ns); } private string ListTypeToString(object value, IXmlNamespaceResolver nsResolver) { if (!_listsAllowed || !(value is IEnumerable)) { throw CreateInvalidClrMappingException(value.GetType(), typeof(string)); } StringBuilder bldr = new StringBuilder(); foreach (object item in ((IEnumerable)value)) { // skip null values if (item != null) { // Separate values by single space character if (bldr.Length != 0) bldr.Append(' '); // Append string value of next item in the list bldr.Append(_listItemConverter.ToString(item, nsResolver)); } } return bldr.ToString(); } private object StringToListType(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (_listsAllowed && destinationType.IsArray) { Type itemTypeDst = destinationType.GetElementType(); if (itemTypeDst == s_objectType) return ToArray<object>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_booleanType) return ToArray<bool>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_byteType) return ToArray<byte>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_byteArrayType) return ToArray<byte[]>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_dateTimeType) return ToArray<DateTime>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_dateTimeOffsetType) return ToArray<DateTimeOffset>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_decimalType) return ToArray<decimal>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_doubleType) return ToArray<double>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int16Type) return ToArray<short>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int32Type) return ToArray<int>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int64Type) return ToArray<long>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_SByteType) return ToArray<sbyte>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_singleType) return ToArray<float>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_stringType) return ToArray<string>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_timeSpanType) return ToArray<TimeSpan>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt16Type) return ToArray<ushort>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt32Type) return ToArray<uint>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt64Type) return ToArray<ulong>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_uriType) return ToArray<Uri>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_xmlQualifiedNameType) return ToArray<XmlQualifiedName>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); } throw CreateInvalidClrMappingException(typeof(string), destinationType); } private T[] ToArray<T>(string[] stringArray, IXmlNamespaceResolver nsResolver) { T[] arrDst = new T[stringArray.Length]; for (int i = 0; i < stringArray.Length; i++) { arrDst[i] = (T)_listItemConverter.FromString(stringArray[i], typeof(T), nsResolver); } return arrDst; } private Exception CreateInvalidClrMappingException(Type sourceType, Type destinationType) { return new InvalidCastException(SR.Format(SR.XmlConvert_TypeListBadMapping2, s_untypedStringTypeName, sourceType.ToString(), destinationType.ToString())); } } }
// ----- // Copyright 2010 Deyan Timnev // This file is part of the Matrix Platform (www.matrixplatform.com). // The Matrix Platform is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. The Matrix Platform is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License along with the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html // ----- using System; using System.Collections.Generic; using Matrix.Framework.MessageBus.Core; using Matrix.Framework.SuperPool.Clients; using Matrix.Framework.SuperPool.DynamicProxy; using Matrix.Common.Core.Collections; using Matrix.Common.Core; #if Matrix_Diagnostics using Matrix.Common.Diagnostics; #endif namespace Matrix.Framework.SuperPool.Core { /// <summary> /// Top of the message super pool class stack, this is the one that manages clients. /// </summary> public class SuperPoolClients : IDisposable { protected volatile ProxyTypeManager _proxyTypeManager = null; /// <summary> /// Manages proxy objects creation and operation. /// </summary> internal ProxyTypeManager ProxyTypeManager { get { return _proxyTypeManager; } } /// <summary> /// A collection indicating all the types and what clients implement them. /// /// *IMPORTANT* hot swap specific functionality used, do not refactor without consideration. /// </summary> protected HotSwapDictionary<Type, HotSwapList<ClientId>> _clientsInterfaces = new HotSwapDictionary<Type, HotSwapList<ClientId>>(); protected IMessageBus _messageBus; /// <summary> /// The message bus the super pool uses for communication. /// </summary> public IMessageBus MessageBus { get { return _messageBus; } } /// <summary> /// Client of the super pool, used to all separate pool instances to talk to each other. /// </summary> protected SuperPoolClient IntercomClient { get; private set; } #if Matrix_Diagnostics /// <summary> /// /// </summary> protected InstanceMonitor InstanceMonitor { get; private set; } #endif /// <summary> /// Name of the super pool, same as the name of the underlying bus. /// </summary> public string Name { get { IMessageBus messageBus = _messageBus; if (messageBus == null) { return string.Empty; } return messageBus.Name; } } /// <summary> /// Constructor. /// </summary> public SuperPoolClients() { #if Matrix_Diagnostics InstanceMonitor = new InstanceMonitor(this); #endif _proxyTypeManager = new ProxyTypeManager(); } public virtual void Dispose() { ProxyTypeManager manager = _proxyTypeManager; if (manager != null) { manager.Dispose(); _proxyTypeManager = null; } IMessageBus messageBus = _messageBus; _messageBus = null; if (messageBus != null) { messageBus.ClientAddedEvent -= new MessageBusClientUpdateDelegate(_messageBus_ClientAddedEvent); messageBus.ClientRemovedEvent -= new MessageBusClientRemovedDelegate(_messageBus_ClientRemovedEvent); messageBus.ClientUpdateEvent -= new MessageBusClientUpdateDelegate(_messageBus_ClientUpdateEvent); messageBus.Dispose(); } } /// <summary> /// Initialize the pool for operation, by supplying it with a message bus. /// </summary> protected virtual bool Initialize(IMessageBus messageBus) { lock (this) { if (_messageBus != null || messageBus == null) { return false; } _messageBus = messageBus; _messageBus.ClientAddedEvent += new MessageBusClientUpdateDelegate(_messageBus_ClientAddedEvent); _messageBus.ClientRemovedEvent += new MessageBusClientRemovedDelegate(_messageBus_ClientRemovedEvent); _messageBus.ClientUpdateEvent += new MessageBusClientUpdateDelegate(_messageBus_ClientUpdateEvent); // Add a client with self to the message bus. IntercomClient = new SuperPoolClient("SuperPool.Intercom", this); } if (this.AddClient(IntercomClient) == false) { #if Matrix_Diagnostics InstanceMonitor.Fatal("Failed to add super pool main client."); #endif lock (this) { IntercomClient.Dispose(); IntercomClient = null; _messageBus.ClientAddedEvent -= new MessageBusClientUpdateDelegate(_messageBus_ClientAddedEvent); _messageBus.ClientRemovedEvent -= new MessageBusClientRemovedDelegate(_messageBus_ClientRemovedEvent); _messageBus.ClientUpdateEvent -= new MessageBusClientUpdateDelegate(_messageBus_ClientUpdateEvent); _messageBus = null; } return false; } return true; } protected virtual bool HandleClientAdded(IMessageBus messageBus, ClientId clientId) { Type clientType = messageBus.GetClientType(clientId); if (clientType == null) { #if Matrix_Diagnostics InstanceMonitor.OperationError("Failed to establish client type."); #endif return false; } if (clientType != typeof(SuperPoolClient) && clientType.IsSubclassOf(typeof(SuperPoolClient)) == false) {// Client not a super pool client. return false; } RegisterClientSourceTypes(clientId); return true; } protected virtual bool HandleClientRemoved(IMessageBus messageBus, ClientId clientId, bool isPermanent) { Type clientType = messageBus.GetClientType(clientId); if (clientType == null) { #if Matrix_Diagnostics InstanceMonitor.OperationError("Failed to establish client type."); #endif return false; } if (clientType != typeof(SuperPoolClient) && clientType.IsSubclassOf(typeof(SuperPoolClient)) == false) {// Client not a super pool client. return false; } UnRegisterClientSourceTypes(clientId); return true; } void _messageBus_ClientAddedEvent(IMessageBus messageBus, ClientId clientId) { HandleClientAdded(messageBus, clientId); } protected virtual void _messageBus_ClientRemovedEvent(IMessageBus messageBus, ClientId clientId, bool isPermanent) { HandleClientRemoved(messageBus, clientId, isPermanent); } void _messageBus_ClientUpdateEvent(IMessageBus messageBus, ClientId clientId) { UnRegisterClientSourceTypes(clientId); RegisterClientSourceTypes(clientId); } /// <summary> /// Obtain a collection of the Ids of all clients that implement the interface. /// </summary> /// <param name="interfaceType"></param> /// <returns>The actual hot swap instance, of the collection with the interfaces, thus making it an ultra-fast (instant) result.</returns> public ClientId GetFirstInterfaceImplementor(Type interfaceType) { HotSwapList<ClientId> result = null; if (_clientsInterfaces.TryGetValue(interfaceType, out result) == false) { return null; } if (result.Count > 0) { return result[0]; } return null; } /// <summary> /// Obtain a collection of the Ids of all clients that implement the interface. /// </summary> /// <param name="interfaceType"></param> /// <returns>The actual hot swap instance, of the collection with the interfaces, thus making it an ultra-fast (instant) result.</returns> public IEnumerable<ClientId> GetInterfaceImplementors(Type interfaceType) { HotSwapList<ClientId> result = null; if (_clientsInterfaces.TryGetValue(interfaceType, out result) == false) { return new ClientId[] { }; } return result; } /// <summary> /// Add a client to the pool. /// </summary> public virtual bool AddClient(SuperPoolClient client) { IMessageBus messageBus = _messageBus; if (messageBus == null) { return false; } if (client.Source == null) {// TODO: clear this scenario. //System.Diagnostics.Debug.Fail("Warning, adding a client with no source assigned. Make sure to assign source prior to adding client."); } bool result = messageBus.AddClient(client); if (result) { client.AssignSuperPool((SuperPool)this); } return result; } /// <summary> /// Remove a client from the pool. /// </summary> public virtual bool RemoveClient(SuperPoolClient client, bool isPermanent) { IMessageBus messageBus = _messageBus; if (messageBus == null) { return false; } bool result = messageBus.RemoveClient(client, isPermanent); if (result) { client.ReleaseSuperPool(); } return result; } /// <summary> /// /// </summary> bool RegisterClientSourceTypes(ClientId clientId) { IMessageBus messageBus = _messageBus; if (messageBus == null) { Console.WriteLine("Failed to register client source type, message bus not found."); #if Matrix_Diagnostics InstanceMonitor.OperationError("Failed to register client source type, message bus not found."); #endif return false; } List<string> sourceTypes = messageBus.GetClientSourceTypes(clientId); if (sourceTypes == null) { Console.WriteLine("Failed to register client source type, source type not found."); #if Matrix_Diagnostics InstanceMonitor.OperationError("Failed to register client source type, source type not found."); #endif return false; } foreach (Type superType in ReflectionHelper.GetKnownTypes(sourceTypes)) { if (superType.IsInterface == false || ReflectionHelper.TypeHasCustomAttribute(superType, typeof(SuperPoolInterfaceAttribute), false) == false) { continue; } HotSwapList<ClientId> clientList = null; if (_clientsInterfaces.TryGetValue(superType, out clientList) == false) { clientList = _clientsInterfaces.GetOrAdd(superType, new HotSwapList<ClientId>()); } clientList.AddUnique(clientId); if (ReflectionHelper.TypeHasCustomAttribute(superType, typeof(SuperPoolInterfaceAttribute), false) == false) {// Register this type as well. _proxyTypeManager.ObtainInterfaceProxy(superType); } } return true; } /// <summary> /// Will unregister all _clientInterfaces associations with this client. /// </summary> /// <param name="clientId"></param> void UnRegisterClientSourceTypes(ClientId clientId) { foreach (KeyValuePair<Type, HotSwapList<ClientId>> pair in _clientsInterfaces) { pair.Value.Remove(clientId); } } } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- //============================================================================================= // Event Handlers. //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiEditCanvas::onAdd( %this ) { // %this.setWindowTitle("Torque Gui Editor"); %this.onCreateMenu(); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::onRemove( %this ) { if( isObject( GuiEditorGui.menuGroup ) ) GuiEditorGui.delete(); // cleanup %this.onDestroyMenu(); } //--------------------------------------------------------------------------------------------- /// Create the Gui Editor menu bar. function GuiEditCanvas::onCreateMenu(%this) { if(isObject(%this.menuBar)) return; //set up %cmdctrl variable so that it matches OS standards if( $platform $= "macos" ) { %cmdCtrl = "cmd"; %redoShortcut = "Cmd-Shift Z"; } else { %cmdCtrl = "Ctrl"; %redoShort = "Ctrl Y"; } // Menu bar %this.menuBar = new MenuBar() { dynamicItemInsertPos = 3; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "File"; internalName = "FileMenu"; item[0] = "New Gui..." TAB %cmdCtrl SPC "N" TAB %this @ ".create();"; item[1] = "Open..." TAB %cmdCtrl SPC "O" TAB %this @ ".open();"; item[2] = "Save" TAB %cmdCtrl SPC "S" TAB %this @ ".save( false, true );"; item[3] = "Save As..." TAB %cmdCtrl @ "-Shift S" TAB %this @ ".save( false );"; item[4] = "Save Selected As..." TAB %cmdCtrl @ "-Alt S" TAB %this @ ".save( true );"; item[5] = "-"; item[6] = "Revert Gui" TAB "" TAB %this @ ".revert();"; item[7] = "Add Gui From File..." TAB "" TAB %this @ ".append();"; item[8] = "-"; item[9] = "Open Gui File in Torsion" TAB "" TAB %this @".openInTorsion();"; item[10] = "-"; item[11] = "Close Editor" TAB "F10" TAB %this @ ".quit();"; item[12] = "Quit" TAB %cmdCtrl SPC "Q" TAB "quit();"; }; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "Edit"; internalName = "EditMenu"; item[0] = "Undo" TAB %cmdCtrl SPC "Z" TAB "GuiEditor.undo();"; item[1] = "Redo" TAB %redoShortcut TAB "GuiEditor.redo();"; item[2] = "-"; item[3] = "Cut" TAB %cmdCtrl SPC "X" TAB "GuiEditor.saveSelection(); GuiEditor.deleteSelection();"; item[4] = "Copy" TAB %cmdCtrl SPC "C" TAB "GuiEditor.saveSelection();"; item[5] = "Paste" TAB %cmdCtrl SPC "V" TAB "GuiEditor.loadSelection();"; item[6] = "-"; item[7] = "Select All" TAB %cmdCtrl SPC "A" TAB "GuiEditor.selectAll();"; item[8] = "Deselect All" TAB %cmdCtrl SPC "D" TAB "GuiEditor.clearSelection();"; item[9] = "Select Parent(s)" TAB %cmdCtrl @ "-Alt Up" TAB "GuiEditor.selectParents();"; item[10] = "Select Children" TAB %cmdCtrl @ "-Alt Down" TAB "GuiEditor.selectChildren();"; item[11] = "Add Parent(s) to Selection" TAB %cmdCtrl @ "-Alt-Shift Up" TAB "GuiEditor.selectParents( true );"; item[12] = "Add Children to Selection" TAB %cmdCtrl @ "-Alt-Shift Down" TAB "GuiEditor.selectChildren( true );"; item[13] = "Select..." TAB "" TAB "GuiEditorSelectDlg.toggleVisibility();"; item[14] = "-"; item[15] = "Lock/Unlock Selection" TAB %cmdCtrl SPC "L" TAB "GuiEditor.toggleLockSelection();"; item[16] = "Hide/Unhide Selection" TAB %cmdCtrl SPC "H" TAB "GuiEditor.toggleHideSelection();"; item[17] = "-"; item[18] = "Group Selection" TAB %cmdCtrl SPC "G" TAB "GuiEditor.groupSelected();"; item[19] = "Ungroup Selection" TAB %cmdCtrl @ "-Shift G" TAB "GuiEditor.ungroupSelected();"; item[20] = "-"; item[21] = "Full Box Selection" TAB "" TAB "GuiEditor.toggleFullBoxSelection();"; item[22] = "-"; item[23] = "Grid Size" TAB %cmdCtrl SPC "," TAB "GuiEditor.showPrefsDialog();"; }; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "Layout"; internalName = "LayoutMenu"; item[0] = "Align Left" TAB %cmdCtrl SPC "Left" TAB "GuiEditor.Justify(0);"; item[1] = "Center Horizontally" TAB "" TAB "GuiEditor.Justify(1);"; item[2] = "Align Right" TAB %cmdCtrl SPC "Right" TAB "GuiEditor.Justify(2);"; item[3] = "-"; item[4] = "Align Top" TAB %cmdCtrl SPC "Up" TAB "GuiEditor.Justify(3);"; item[5] = "Center Vertically" TAB "" TAB "GuiEditor.Justify(7);"; item[6] = "Align Bottom" TAB %cmdCtrl SPC "Down" TAB "GuiEditor.Justify(4);"; item[7] = "-"; item[8] = "Space Vertically" TAB "" TAB "GuiEditor.Justify(5);"; item[9] = "Space Horizontally" TAB "" TAB "GuiEditor.Justify(6);"; item[10] = "-"; item[11] = "Fit into Parent(s)" TAB "" TAB "GuiEditor.fitIntoParents();"; item[12] = "Fit Width to Parent(s)" TAB "" TAB "GuiEditor.fitIntoParents( true, false );"; item[13] = "Fit Height to Parent(s)" TAB "" TAB "GuiEditor.fitIntoParents( false, true );"; item[14] = "-"; item[15] = "Bring to Front" TAB "" TAB "GuiEditor.BringToFront();"; item[16] = "Send to Back" TAB "" TAB "GuiEditor.PushToBack();"; }; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "Move"; internalName = "MoveMenu"; item[0] = "Nudge Left" TAB "Left" TAB "GuiEditor.moveSelection( -1, 0);"; item[1] = "Nudge Right" TAB "Right" TAB "GuiEditor.moveSelection( 1, 0);"; item[2] = "Nudge Up" TAB "Up" TAB "GuiEditor.moveSelection( 0, -1);"; item[3] = "Nudge Down" TAB "Down" TAB "GuiEditor.moveSelection( 0, 1 );"; item[4] = "-"; item[5] = "Big Nudge Left" TAB "Shift Left" TAB "GuiEditor.moveSelection( - GuiEditor.snap2gridsize, 0 );"; item[6] = "Big Nudge Right" TAB "Shift Right" TAB "GuiEditor.moveSelection( GuiEditor.snap2gridsize, 0 );"; item[7] = "Big Nudge Up" TAB "Shift Up" TAB "GuiEditor.moveSelection( 0, - GuiEditor.snap2gridsize );"; item[8] = "Big Nudge Down" TAB "Shift Down" TAB "GuiEditor.moveSelection( 0, GuiEditor.snap2gridsize );"; }; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "Snap"; internalName = "SnapMenu"; item[0] = "Snap Edges" TAB "Alt-Shift E" TAB "GuiEditor.toggleEdgeSnap();"; item[1] = "Snap Centers" TAB "Alt-Shift C" TAB "GuiEditor.toggleCenterSnap();"; item[2] = "-"; item[3] = "Snap to Guides" TAB "Alt-Shift G" TAB "GuiEditor.toggleGuideSnap();"; item[4] = "Snap to Controls" TAB "Alt-Shift T" TAB "GuiEditor.toggleControlSnap();"; item[5] = "Snap to Canvas" TAB "" TAB "GuiEditor.toggleCanvasSnap();"; item[6] = "Snap to Grid" TAB "" TAB "GuiEditor.toggleGridSnap();"; item[7] = "-"; item[8] = "Show Guides" TAB "" TAB "GuiEditor.toggleDrawGuides();"; item[9] = "Clear Guides" TAB "" TAB "GuiEditor.clearGuides();"; }; new PopupMenu() { superClass = "MenuBuilder"; internalName = "HelpMenu"; barTitle = "Help"; item[0] = "Online Documentation..." TAB "Alt F1" TAB "gotoWebPage( GuiEditor.documentationURL );"; item[1] = "Offline User Guid..." TAB "" TAB "gotoWebPage( GuiEditor.documentationLocal );"; item[2] = "Offline Reference Guide..." TAB "" TAB "shellExecute( GuiEditor.documentationReference );"; item[3] = "-"; item[4] = "Torque 3D Public Forums..." TAB "" TAB "gotoWebPage( \"http://www.garagegames.com/community/forums/73\" );"; item[5] = "Torque 3D Private Forums..." TAB "" TAB "gotoWebPage( \"http://www.garagegames.com/community/forums/63\" );"; }; }; %this.menuBar.attachToCanvas( Canvas, 0 ); } $GUI_EDITOR_MENU_EDGESNAP_INDEX = 0; $GUI_EDITOR_MENU_CENTERSNAP_INDEX = 1; $GUI_EDITOR_MENU_GUIDESNAP_INDEX = 3; $GUI_EDITOR_MENU_CONTROLSNAP_INDEX = 4; $GUI_EDITOR_MENU_CANVASSNAP_INDEX = 5; $GUI_EDITOR_MENU_GRIDSNAP_INDEX = 6; $GUI_EDITOR_MENU_DRAWGUIDES_INDEX = 8; $GUI_EDITOR_MENU_FULLBOXSELECT_INDEX = 21; //--------------------------------------------------------------------------------------------- /// Called before onSleep when the canvas content is changed function GuiEditCanvas::onDestroyMenu(%this) { if( !isObject( %this.menuBar ) ) return; // Destroy menus while( %this.menuBar.getCount() != 0 ) %this.menuBar.getObject( 0 ).delete(); %this.menuBar.removeFromCanvas(); %this.menuBar.delete(); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::onWindowClose(%this) { %this.quit(); } //============================================================================================= // Menu Commands. //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiEditCanvas::create( %this ) { GuiEditorNewGuiDialog.init( "NewGui", "GuiControl" ); Canvas.pushDialog( GuiEditorNewGuiDialog ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::load( %this, %filename ) { %newRedefineBehavior = "replaceExisting"; if( isDefined( "$GuiEditor::loadRedefineBehavior" ) ) { // This trick allows to choose different redefineBehaviors when loading // GUIs. This is useful, for example, when loading GUIs that would lead to // problems when loading with their correct names because script behavior // would immediately attach. // // This allows to also edit the GUI editor's own GUI inside itself. %newRedefineBehavior = $GuiEditor::loadRedefineBehavior; } // Allow stomping objects while exec'ing the GUI file as we want to // pull the file's objects even if we have another version of the GUI // already loaded. %oldRedefineBehavior = $Con::redefineBehavior; $Con::redefineBehavior = %newRedefineBehavior; // Load up the gui. exec( %fileName ); $Con::redefineBehavior = %oldRedefineBehavior; // The GUI file should have contained a GUIControl which should now be in the instant // group. And, it should be the only thing in the group. if( !isObject( %guiContent ) ) { MessageBox( getEngineName(), "You have loaded a Gui file that was created before this version. It has been loaded but you must open it manually from the content list dropdown", "Ok", "Information" ); return 0; } GuiEditor.openForEditing( %guiContent ); GuiEditorStatusBar.print( "Loaded '" @ %filename @ "'" ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::openInTorsion( %this ) { if( !GuiEditorContent.getCount() ) return; %guiObject = GuiEditorContent.getObject( 0 ); EditorOpenDeclarationInTorsion( %guiObject ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::open( %this ) { %openFileName = GuiBuilder::getOpenName(); if( %openFileName $= "" ) return; // Make sure the file is valid. if ((!isFile(%openFileName)) && (!isFile(%openFileName @ ".dso"))) return; %this.load( %openFileName ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::save( %this, %selectedOnly, %noPrompt ) { // Get the control we should save. if( %selectedOnly ) { %selected = GuiEditor.getSelection(); if( !%selected.getCount() ) return; else if( %selected.getCount() > 1 ) { MessageBox( "Invalid selection", "Only a single control hierarchy can be saved to a file. Make sure you have selected only one control in the tree view." ); return; } %currentObject = %selected.getObject( 0 ); } else if( GuiEditorContent.getCount() > 0 ) %currentObject = GuiEditorContent.getObject( 0 ); else return; // Store the current guide set on the control. GuiEditor.writeGuides( %currentObject ); %currentObject.canSaveDynamicFields = true; // Make sure the guides get saved out. // Construct a base filename. if( %currentObject.getName() !$= "" ) %name = %currentObject.getName() @ ".gui"; else %name = "Untitled.gui"; // Construct a path. if( %selectedOnly && %currentObject != GuiEditorContent.getObject( 0 ) && %currentObject.getFileName() $= GuiEditorContent.getObject( 0 ).getFileName() ) { // Selected child control that hasn't been yet saved to its own file. %currentFile = GuiEditor.LastPath @ "/" @ %name; %currentFile = makeRelativePath( %currentFile, getMainDotCsDir() ); } else { %currentFile = %currentObject.getFileName(); if( %currentFile $= "") { // No file name set on control. Force a prompt. %noPrompt = false; if( GuiEditor.LastPath !$= "" ) { %currentFile = GuiEditor.LastPath @ "/" @ %name; %currentFile = makeRelativePath( %currentFile, getMainDotCsDir() ); } else %currentFile = expandFileName( %name ); } else %currentFile = expandFileName( %currentFile ); } // Get the filename. if( !%noPrompt ) { %filename = GuiBuilder::getSaveName( %currentFile ); if( %filename $= "" ) return; } else %filename = %currentFile; // Save the Gui. if( isWriteableFileName( %filename ) ) { // // Extract any existent TorqueScript before writing out to disk // %fileObject = new FileObject(); %fileObject.openForRead( %filename ); %skipLines = true; %beforeObject = true; // %var++ does not post-increment %var, in torquescript, it pre-increments it, // because ++%var is illegal. %lines = -1; %beforeLines = -1; %skipLines = false; while( !%fileObject.isEOF() ) { %line = %fileObject.readLine(); if( %line $= "//--- OBJECT WRITE BEGIN ---" ) %skipLines = true; else if( %line $= "//--- OBJECT WRITE END ---" ) { %skipLines = false; %beforeObject = false; } else if( %skipLines == false ) { if(%beforeObject) %beforeNewFileLines[ %beforeLines++ ] = %line; else %newFileLines[ %lines++ ] = %line; } } %fileObject.close(); %fileObject.delete(); %fo = new FileObject(); %fo.openForWrite(%filename); // Write out the captured TorqueScript that was before the object before the object for( %i = 0; %i <= %beforeLines; %i++) %fo.writeLine( %beforeNewFileLines[ %i ] ); %fo.writeLine("//--- OBJECT WRITE BEGIN ---"); %fo.writeObject(%currentObject, "%guiContent = "); %fo.writeLine("//--- OBJECT WRITE END ---"); // Write out captured TorqueScript below Gui object for( %i = 0; %i <= %lines; %i++ ) %fo.writeLine( %newFileLines[ %i ] ); %fo.close(); %fo.delete(); %currentObject.setFileName( makeRelativePath( %filename, getMainDotCsDir() ) ); GuiEditorStatusBar.print( "Saved file '" @ %currentObject.getFileName() @ "'" ); } else MessageBox( "Error writing to file", "There was an error writing to file '" @ %currentFile @ "'. The file may be read-only.", "Ok", "Error" ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::append( %this ) { // Get filename. %openFileName = GuiBuilder::getOpenName(); if( %openFileName $= "" || ( !isFile( %openFileName ) && !isFile( %openFileName @ ".dso" ) ) ) return; // Exec file. %oldRedefineBehavior = $Con::redefineBehavior; $Con::redefineBehavior = "renameNew"; exec( %openFileName ); $Con::redefineBehavior = %oldRedefineBehavior; // Find guiContent. if( !isObject( %guiContent ) ) { MessageBox( "Error loading GUI file", "The GUI content controls could not be found. This function can only be used with files saved by the GUI editor.", "Ok", "Error" ); return; } if( !GuiEditorContent.getCount() ) GuiEditor.openForEditing( %guiContent ); else { GuiEditor.getCurrentAddSet().add( %guiContent ); GuiEditor.readGuides( %guiContent ); GuiEditor.onAddNewCtrl( %guiContent ); GuiEditor.onHierarchyChanged(); } GuiEditorStatusBar.print( "Appended controls from '" @ %openFileName @ "'" ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::revert( %this ) { if( !GuiEditorContent.getCount() ) return; %gui = GuiEditorContent.getObject( 0 ); %filename = %gui.getFileName(); if( %filename $= "" ) return; if( MessageBox( "Revert Gui", "Really revert the current Gui? This cannot be undone.", "OkCancel", "Question" ) == $MROk ) %this.load( %filename ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::close( %this ) { } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::quit( %this ) { %this.close(); GuiGroup.add(GuiEditorGui); // we must not delete a window while in its event handler, or we foul the event dispatch mechanism %this.schedule(10, delete); Canvas.setContent(GuiEditor.lastContent); $InGuiEditor = false; //Temp fix to disable MLAA when in GUI editor if( isObject(MLAAFx) && $MLAAFxGuiEditorTemp==true ) { MLAAFx.isEnabled = true; $MLAAFxGuiEditorTemp = false; } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. 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 additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Xml; using System.Collections; using System.Reflection; namespace fyiReporting.RdlDesktop { class RdlDesktop { private TcpListener myListener ; // These parameters are usually override in the config.xml file private int port = 8080 ; // port private bool bLocalOnly = true; // restrict access to the machine it's running on private string wd = "tempreports"; // subdirectory name under server root to place generated reports private string sr = null; private int maxReadCache=100; private int maxReadCacheEntrySize=50000; private int _TraceLevel=0; // Controls level of messages to console private bool _continue=true; private FileCache _cache; private FileReadCache _readCache; private Hashtable _mimes; private string _dsrPassword; // data source resource password public RdlDesktop() { GetConfigInfo(); // obtain the configuation information _cache = new FileCache(); _readCache = new FileReadCache(maxReadCache, maxReadCacheEntrySize); } public FileCache Cache { get { return _cache; } } public string DataSourceReferencePassword { get { return _dsrPassword; } set { _dsrPassword = value; } } public FileReadCache ReadCache { get { return _readCache; } } public Hashtable Mimes { get { return _mimes; } } public bool Continue { get { return _continue; } set { _continue = value; } } public int TraceLevel { get { return _TraceLevel; } set { _TraceLevel = value; } } // RunServer makes TcpListener start listening on the // given port. It also calls a Thread on the method StartListen(). public void RunServer() { // main server loop try { //start listing on the given port if (this.bLocalOnly) { IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0]; myListener = new TcpListener(ipAddress, port) ; } else myListener = new TcpListener(port); myListener.Start(); // int maxThreads; // worker threads in the thread pool // int completionPortThreads; // asynchronous I/O threads in the thread pool // ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads); Console.WriteLine(string.Format("RDL Desktop version {0}, Copyright (C) 2005 fyiReporting Software, LLC", Assembly.GetExecutingAssembly().GetName().Version.ToString())); Console.WriteLine(""); Console.WriteLine("RDL Desktop comes with ABSOLUTELY NO WARRANTY. This is free software,"); Console.WriteLine("and you are welcome to redistribute it under certain conditions."); Console.WriteLine("Type 'license' for details."); Console.WriteLine(""); Console.WriteLine("RDL Desktop running on port {0}", port); Console.WriteLine("Type '?' for list of console commands."); Console.Write(">"); while(_continue) { while(!myListener.Pending() && _continue) { Thread.Sleep(100); } if (_continue) { ConnectionThread c = new ConnectionThread(this, myListener, sr, wd); ThreadPool.QueueUserWorkItem(new WaitCallback(c.HandleConnection)); } } } catch(Exception e) { if (this._TraceLevel >= 0) Console.WriteLine("An Exception Occurred while Listening :" +e.ToString()); } } // Application Starts Here.. public static void Main(string[] args) { RdlDesktop server = new RdlDesktop(); server.HandleArguments(args); // start up the background thread to handle additional work BackgroundThread bk = new BackgroundThread(server, 60 * 5, 60 * 5, 60 * 5); Thread bThread = new Thread(new ThreadStart(bk.HandleBackground)); bThread.Name = "background"; bThread.Start(); // start up the console thread so user can see what's going on ConsoleThread ct = new ConsoleThread(server, bk); Thread cThread = new Thread(new ThreadStart(ct.HandleConsole)); cThread.Name = "console"; cThread.Start(); // Run the server server.RunServer(); server.Cache.ClearAll(); // clean up the report file cache when done } private void GetConfigInfo() { _mimes = new Hashtable(); string optFileName = AppDomain.CurrentDomain.BaseDirectory + "config.xml"; try { XmlDocument xDoc = new XmlDocument(); xDoc.PreserveWhitespace = false; xDoc.Load(optFileName); XmlNode xNode; xNode = xDoc.SelectSingleNode("//config"); // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name.ToLower()) { case "port": try { port = Convert.ToInt32(xNodeLoop.InnerText); } catch { port = 8080; Console.WriteLine("config.xml file: port value is not a valid number. Defaulting to {0}", port); } break; case "localhostonly": string tf = xNodeLoop.InnerText.ToLower(); if (tf == "false") this.bLocalOnly = false; break; case "serverroot": sr = xNodeLoop.InnerText; break; case "cachedirectory": wd = xNodeLoop.InnerText; break; case "tracelevel": try { _TraceLevel = Convert.ToInt32(xNodeLoop.InnerText); } catch { _TraceLevel = 0; Console.WriteLine("config.xml file: tracelevel value is not a valid number. Defaulting to {0}", _TraceLevel); } break; case "maxreadcache": try { maxReadCache = Convert.ToInt32(xNodeLoop.InnerText); } catch { maxReadCache = 100; Console.WriteLine("config.xml file: maxreadcache value is not a valid number. Defaulting to {0}", maxReadCache); } break; case "maxreadcacheentrysize": try { maxReadCacheEntrySize = Convert.ToInt32(xNodeLoop.InnerText); } catch { maxReadCacheEntrySize = 50000; Console.WriteLine("config.xml file: maxReadCacheEntrySize value is not a valid number. Defaulting to {0}", maxReadCacheEntrySize); } break; case "mimetypes": GetConfigInfoMimes(xNodeLoop); break; default: Console.WriteLine("config.xml file: {0} is unknown and will be ignored.", xNodeLoop.Name); break; } } if (sr == null) // no server root specified? throw new Exception("'serverroot' must be specified in the config.xml file."); } catch (Exception ex) { // Didn't sucessfully get the startup state don't use Console.WriteLine("Error processing config.xml. {0}", ex.Message); throw ex; } return; } private void HandleArguments(string[] args) { // Handle command line arguments if (args == null || args.Length==0) return; foreach(string s in args) { string t = s.Substring(0,2); switch (t) { case "/p": this._dsrPassword = s.Substring(2); break; case "/t": try { _TraceLevel = Convert.ToInt32(s.Substring(2)); } catch { Console.WriteLine("/t value is not a valid number. Using {0}", _TraceLevel); } break; default: Console.WriteLine("Unknown command line argument '{0}' ignored.", s); break; } } } private void GetConfigInfoMimes(XmlNode xNode) { foreach(XmlNode xN in xNode.ChildNodes) { if (xN.NodeType != XmlNodeType.Element) continue; switch (xN.Name.ToLower()) { case "mimetype": string extension=null; string type=null; foreach(XmlNode xN2 in xN.ChildNodes) { switch (xN2.Name.ToLower()) { case "extension": extension = xN2.InnerText.ToLower(); break; case "type": type = xN2.InnerText.ToLower(); break; default: Console.WriteLine("config.xml file: {0} is unknown and will be ignored.", xN.Name); break; } } if (extension != null && type != null) { if (_mimes[extension] == null) _mimes.Add(extension, type); } break; default: Console.WriteLine("config.xml file: {0} is unknown and will be ignored.", xN.Name); break; } } return; } } }
// Copyright (c) .NET Foundation. 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; using System.Collections.Generic; using System.Linq; namespace Microsoft.Owin.Infrastructure { [System.CodeDom.Compiler.GeneratedCode("App_Packages", "")] internal struct HeaderSegment : IEquatable<HeaderSegment> { private readonly StringSegment _formatting; private readonly StringSegment _data; // <summary> // Initializes a new instance of the <see cref="T:System.Object"/> class. // </summary> public HeaderSegment(StringSegment formatting, StringSegment data) { _formatting = formatting; _data = data; } public StringSegment Formatting => _formatting; public StringSegment Data => _data; #region Equality members public bool Equals(HeaderSegment other) => _formatting.Equals(other._formatting) && _data.Equals(other._data); public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is HeaderSegment && Equals((HeaderSegment)obj); } public override int GetHashCode() { unchecked { return (_formatting.GetHashCode() * 397) ^ _data.GetHashCode(); } } public static bool operator ==(HeaderSegment left, HeaderSegment right) => left.Equals(right); public static bool operator !=(HeaderSegment left, HeaderSegment right) => !left.Equals(right); #endregion } [System.CodeDom.Compiler.GeneratedCode("App_Packages", "")] internal struct HeaderSegmentCollection : IEnumerable<HeaderSegment>, IEquatable<HeaderSegmentCollection> { private readonly string[] _headers; public HeaderSegmentCollection(string[] headers) { _headers = headers; } #region Equality members public bool Equals(HeaderSegmentCollection other) => Equals(_headers, other._headers); public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is HeaderSegmentCollection && Equals((HeaderSegmentCollection)obj); } public override int GetHashCode() => (_headers != null ? _headers.GetHashCode() : 0); public static bool operator ==(HeaderSegmentCollection left, HeaderSegmentCollection right) => left.Equals(right); public static bool operator !=(HeaderSegmentCollection left, HeaderSegmentCollection right) => !left.Equals(right); #endregion public Enumerator GetEnumerator() => new Enumerator(_headers); IEnumerator<HeaderSegment> IEnumerable<HeaderSegment>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); internal struct Enumerator : IEnumerator<HeaderSegment> { private readonly string[] _headers; private int _index; private string _header; private int _headerLength; private int _offset; private int _leadingStart; private int _leadingEnd; private int _valueStart; private int _valueEnd; private int _trailingStart; private Mode _mode; private static readonly string[] NoHeaders = new string[0]; public Enumerator(string[] headers) { _headers = headers ?? NoHeaders; _header = string.Empty; _headerLength = -1; _index = -1; _offset = -1; _leadingStart = -1; _leadingEnd = -1; _valueStart = -1; _valueEnd = -1; _trailingStart = -1; _mode = Mode.Leading; } private enum Mode { Leading, Value, ValueQuoted, Trailing, Produce, } private enum Attr { Value, Quote, Delimiter, Whitespace } public HeaderSegment Current { get { return new HeaderSegment( new StringSegment(_header, _leadingStart, _leadingEnd - _leadingStart), new StringSegment(_header, _valueStart, _valueEnd - _valueStart)); } } object IEnumerator.Current { get { return Current; } } public void Dispose() { } public bool MoveNext() { while (true) { if (_mode == Mode.Produce) { _leadingStart = _trailingStart; _leadingEnd = -1; _valueStart = -1; _valueEnd = -1; _trailingStart = -1; if (_offset == _headerLength && _leadingStart != -1 && _leadingStart != _offset) { // Also produce trailing whitespace _leadingEnd = _offset; return true; } _mode = Mode.Leading; } // if end of a string if (_offset == _headerLength) { ++_index; _offset = -1; _leadingStart = 0; _leadingEnd = -1; _valueStart = -1; _valueEnd = -1; _trailingStart = -1; // if that was the last string if (_index == _headers.Length) { // no more move nexts return false; } // grab the next string _header = _headers[_index] ?? string.Empty; _headerLength = _header.Length; } while (true) { ++_offset; char ch = _offset == _headerLength ? (char)0 : _header[_offset]; // todo - array of attrs Attr attr = char.IsWhiteSpace(ch) ? Attr.Whitespace : ch == '\"' ? Attr.Quote : (ch == ',' || ch == (char)0) ? Attr.Delimiter : Attr.Value; switch (_mode) { case Mode.Leading: switch (attr) { case Attr.Delimiter: _leadingEnd = _offset; _mode = Mode.Produce; break; case Attr.Quote: _leadingEnd = _offset; _valueStart = _offset; _mode = Mode.ValueQuoted; break; case Attr.Value: _leadingEnd = _offset; _valueStart = _offset; _mode = Mode.Value; break; case Attr.Whitespace: // more break; } break; case Mode.Value: switch (attr) { case Attr.Quote: _mode = Mode.ValueQuoted; break; case Attr.Delimiter: _valueEnd = _offset; _trailingStart = _offset; _mode = Mode.Produce; break; case Attr.Value: // more break; case Attr.Whitespace: _valueEnd = _offset; _trailingStart = _offset; _mode = Mode.Trailing; break; } break; case Mode.ValueQuoted: switch (attr) { case Attr.Quote: _mode = Mode.Value; break; case Attr.Delimiter: if (ch == (char)0) { _valueEnd = _offset; _trailingStart = _offset; _mode = Mode.Produce; } break; case Attr.Value: case Attr.Whitespace: // more break; } break; case Mode.Trailing: switch (attr) { case Attr.Delimiter: _mode = Mode.Produce; break; case Attr.Quote: // back into value _trailingStart = -1; _valueEnd = -1; _mode = Mode.ValueQuoted; break; case Attr.Value: // back into value _trailingStart = -1; _valueEnd = -1; _mode = Mode.Value; break; case Attr.Whitespace: // more break; } break; } if (_mode == Mode.Produce) { return true; } } } } public void Reset() { _index = 0; _offset = 0; _leadingStart = 0; _leadingEnd = 0; _valueStart = 0; _valueEnd = 0; } } } [System.CodeDom.Compiler.GeneratedCode("App_Packages", "")] internal struct StringSegment : IEquatable<StringSegment> { private readonly string _buffer; private readonly int _offset; private readonly int _count; // <summary> // Initializes a new instance of the <see cref="T:System.Object"/> class. // </summary> public StringSegment(string buffer, int offset, int count) { _buffer = buffer; _offset = offset; _count = count; } public string Buffer => _buffer; public int Offset => _offset; public int Count => _count; public string Value => _offset == -1 ? null : _buffer.Substring(_offset, _count); public bool HasValue => _offset != -1 && _count != 0 && _buffer != null; #region Equality members public bool Equals(StringSegment other) => string.Equals(_buffer, other._buffer) && _offset == other._offset && _count == other._count; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is StringSegment && Equals((StringSegment)obj); } public override int GetHashCode() { unchecked { int hashCode = (_buffer != null ? _buffer.GetHashCode() : 0); hashCode = (hashCode * 397) ^ _offset; hashCode = (hashCode * 397) ^ _count; return hashCode; } } public static bool operator ==(StringSegment left, StringSegment right) => left.Equals(right); public static bool operator !=(StringSegment left, StringSegment right) => !left.Equals(right); #endregion public bool StartsWith(string text, StringComparison comparisonType) { if (text == null) { throw new ArgumentNullException("text"); } int textLength = text.Length; if (!HasValue || _count < textLength) { return false; } return string.Compare(_buffer, _offset, text, 0, textLength, comparisonType) == 0; } public bool EndsWith(string text, StringComparison comparisonType) { if (text == null) { throw new ArgumentNullException("text"); } int textLength = text.Length; if (!HasValue || _count < textLength) { return false; } return string.Compare(_buffer, _offset + _count - textLength, text, 0, textLength, comparisonType) == 0; } public bool Equals(string text, StringComparison comparisonType) { if (text == null) { throw new ArgumentNullException("text"); } int textLength = text.Length; if (!HasValue || _count != textLength) { return false; } return string.Compare(_buffer, _offset, text, 0, textLength, comparisonType) == 0; } public string Substring(int offset, int length) => _buffer.Substring(_offset + offset, length); public StringSegment Subsegment(int offset, int length) => new StringSegment(_buffer, _offset + offset, length); public override string ToString() => Value ?? string.Empty; } internal static class OwinHelpers { internal static void ParseDelimited(string text, char[] delimiters, Action<string, string, object> callback, object state) { int textLength = text.Length; int equalIndex = text.IndexOf('='); if (equalIndex == -1) { equalIndex = textLength; } int scanIndex = 0; while (scanIndex < textLength) { int delimiterIndex = text.IndexOfAny(delimiters, scanIndex); if (delimiterIndex == -1) { delimiterIndex = textLength; } if (equalIndex < delimiterIndex) { while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex])) { ++scanIndex; } string name = text.Substring(scanIndex, equalIndex - scanIndex); string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1); callback( Uri.UnescapeDataString(name.Replace('+', ' ')), Uri.UnescapeDataString(value.Replace('+', ' ')), state); equalIndex = text.IndexOf('=', delimiterIndex); if (equalIndex == -1) { equalIndex = textLength; } } scanIndex = delimiterIndex + 1; } } public static string GetHeader(IDictionary<string, string[]> headers, string key) { string[] values = GetHeaderUnmodified(headers, key); return values == null ? null : string.Join(",", values); } public static IEnumerable<string> GetHeaderSplit(IDictionary<string, string[]> headers, string key) { string[] values = GetHeaderUnmodified(headers, key); return values == null ? null : GetHeaderSplitImplementation(values); } private static IEnumerable<string> GetHeaderSplitImplementation(string[] values) { foreach (var segment in new HeaderSegmentCollection(values)) { if (segment.Data.HasValue) { yield return DeQuote(segment.Data.Value); } } } public static string[] GetHeaderUnmodified(IDictionary<string, string[]> headers, string key) { if (headers == null) { throw new ArgumentNullException("headers"); } string[] values; return headers.TryGetValue(key, out values) ? values : null; } public static void SetHeader(IDictionary<string, string[]> headers, string key, string value) { if (headers == null) { throw new ArgumentNullException("headers"); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException("key"); } if (string.IsNullOrWhiteSpace(value)) { headers.Remove(key); } else { headers[key] = new[] { value }; } } public static void SetHeaderJoined(IDictionary<string, string[]> headers, string key, params string[] values) { if (headers == null) { throw new ArgumentNullException("headers"); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException("key"); } if (values == null || values.Length == 0) { headers.Remove(key); } else { headers[key] = new[] { string.Join(",", values.Select(value => QuoteIfNeeded(value))) }; } } // Quote items that contain comas and are not already quoted. private static string QuoteIfNeeded(string value) { if (string.IsNullOrWhiteSpace(value)) { // Ignore } else if (value.Contains(',')) { if (value[0] != '"' || value[value.Length - 1] != '"') { value = '"' + value + '"'; } } return value; } private static string DeQuote(string value) { if (string.IsNullOrWhiteSpace(value)) { // Ignore } else if (value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"') { value = value.Substring(1, value.Length - 2); } return value; } public static void SetHeaderUnmodified(IDictionary<string, string[]> headers, string key, params string[] values) { if (headers == null) { throw new ArgumentNullException("headers"); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException("key"); } if (values == null || values.Length == 0) { headers.Remove(key); } else { headers[key] = values; } } public static void SetHeaderUnmodified(IDictionary<string, string[]> headers, string key, IEnumerable<string> values) { if (headers == null) { throw new ArgumentNullException("headers"); } headers[key] = values.ToArray(); } public static void AppendHeader(IDictionary<string, string[]> headers, string key, string values) { if (string.IsNullOrWhiteSpace(values)) { return; } string existing = GetHeader(headers, key); if (existing == null) { SetHeader(headers, key, values); } else { headers[key] = new[] { existing + "," + values }; } } public static void AppendHeaderJoined(IDictionary<string, string[]> headers, string key, params string[] values) { if (values == null || values.Length == 0) { return; } string existing = GetHeader(headers, key); if (existing == null) { SetHeaderJoined(headers, key, values); } else { headers[key] = new[] { existing + "," + string.Join(",", values.Select(value => QuoteIfNeeded(value))) }; } } public static void AppendHeaderUnmodified(IDictionary<string, string[]> headers, string key, params string[] values) { if (values == null || values.Length == 0) { return; } string[] existing = GetHeaderUnmodified(headers, key); if (existing == null) { SetHeaderUnmodified(headers, key, values); } else { SetHeaderUnmodified(headers, key, existing.Concat(values)); } } private static readonly Action<string, string, object> AppendItemCallback = (name, value, state) => { var dictionary = (IDictionary<string, List<String>>)state; List<string> existing; if (!dictionary.TryGetValue(name, out existing)) { dictionary.Add(name, new List<string>(1) { value }); } else { existing.Add(value); } }; private static readonly char[] AmpersandAndSemicolon = new[] { '&', ';' }; internal static IDictionary<string, string[]> GetQuery(OwinRequest request) { var query = request.Get<IDictionary<string, string[]>>("Microsoft.Owin.Query#dictionary"); if (query == null) { query = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); request.Set("Microsoft.Owin.Query#dictionary", query); } string text = request.QueryString.Value; if (request.Get<string>("Microsoft.Owin.Query#text") != text) { query.Clear(); var accumulator = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); ParseDelimited(text, AmpersandAndSemicolon, AppendItemCallback, accumulator); foreach (var kv in accumulator) { query.Add(kv.Key, kv.Value.ToArray()); } request.Set("Microsoft.Owin.Query#text", text); } return query; } internal static string GetJoinedValue(IDictionary<string, string[]> store, string key) { string[] values = GetUnmodifiedValues(store, key); return values == null ? null : string.Join(",", values); } internal static string[] GetUnmodifiedValues(IDictionary<string, string[]> store, string key) { if (store == null) { throw new ArgumentNullException("store"); } string[] values; return store.TryGetValue(key, out values) ? values : null; } internal static string GetHost(OwinRequest request) { var headers = request.Headers; string host = GetHeader(headers, "Host"); if (!string.IsNullOrWhiteSpace(host)) { return host; } string localIpAddress = request.LocalIpAddress ?? "localhost"; var localPort = request.Get<string>(OwinConstants.CommonKeys.LocalPort); return string.IsNullOrWhiteSpace(localPort) ? localIpAddress : (localIpAddress + ":" + localPort); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using AutoMapper; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; using Microsoft.Rest.Azure.OData; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Recovery services convenience client. /// </summary> public partial class PSRecoveryServicesClient { /// <summary> /// Removes Replicated Protected Item. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container ID</param> /// <param name="replicationProtectedItemName">Virtual Machine ID or Replication group Id</param> /// <param name="input">Disable protection input.</param> /// <returns>Job response</returns> public PSSiteRecoveryLongRunningOperation DisableProtection( string fabricName, string protectionContainerName, string replicationProtectedItemName, DisableProtectionInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginDeleteWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Creates Replicated Protected Item. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container ID</param> /// <param name="replicationProtectedItemName">Virtual Machine ID or Replication group Id</param> /// <param name="input">Enable protection input.</param> /// <returns>Job response</returns> public PSSiteRecoveryLongRunningOperation EnableProtection( string fabricName, string protectionContainerName, string replicationProtectedItemName, EnableProtectionInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginCreateWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Retrieves Replicated Protected Item. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Name</param> /// <returns>Protection entity list response</returns> public List<ReplicationProtectedItem> GetAzureSiteRecoveryReplicationProtectedItem( string fabricName, string protectionContainerName) { var firstPage = this.GetSiteRecoveryClient() .ReplicationProtectedItems .ListByReplicationProtectionContainersWithHttpMessagesAsync( fabricName, protectionContainerName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult() .Body; var pages = Utilities.GetAllFurtherPages( this.GetSiteRecoveryClient() .ReplicationProtectedItems .ListByReplicationProtectionContainersNextWithHttpMessagesAsync, firstPage.NextPageLink, this.GetRequestHeaders(true)); pages.Insert(0, firstPage); return Utilities.IpageToList(pages); } /// <summary> /// Retrieves Replicated Protected Item. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Name</param> /// <param name="replicatedProtectedItemName">Virtual Machine Name</param> /// <returns>Replicated Protected Item response</returns> public ReplicationProtectedItem GetAzureSiteRecoveryReplicationProtectedItem( string fabricName, string protectionContainerName, string replicatedProtectedItemName) { return this.GetSiteRecoveryClient() .ReplicationProtectedItems.GetWithHttpMessagesAsync( fabricName, protectionContainerName, replicatedProtectedItemName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult() .Body; } /// <summary> /// Retrieves Protected Items. /// </summary> /// <param name="recoveryPlanName">Recovery Plan Name</param> /// <returns>Protection entity list response</returns> public List<ReplicationProtectedItem> GetAzureSiteRecoveryReplicationProtectedItemInRP( string recoveryPlanName) { var protectedItemsQueryParameter = new ProtectedItemsQueryParameter { RecoveryPlanName = recoveryPlanName }; var odataQuery = new ODataQuery<ProtectedItemsQueryParameter>( protectedItemsQueryParameter.ToQueryString()); var firstPage = this.GetSiteRecoveryClient() .ReplicationProtectedItems.ListWithHttpMessagesAsync( odataQuery, null, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult() .Body; var pages = Utilities.GetAllFurtherPages( this.GetSiteRecoveryClient() .ReplicationProtectedItems.ListNextWithHttpMessagesAsync, firstPage.NextPageLink, this.GetRequestHeaders(true)); pages.Insert(0, firstPage); return Utilities.IpageToList(pages); } /// <summary> /// Purges Replicated Protected Item. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container ID</param> /// <param name="replicationProtectedItemName">Virtual Machine ID or Replication group Id</param> /// <returns>Job response</returns> public PSSiteRecoveryLongRunningOperation PurgeProtection( string fabricName, string protectionContainerName, string replicationProtectedItemName) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginPurgeWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Start applying Recovery Point. /// </summary> /// <param name="fabricName">Fabric Name.</param> /// <param name="protectionContainerName">Protection Conatiner Name.</param> /// <param name="replicationProtectedItemName">Replication Protected Item.</param> /// <param name="input">Input for applying recovery point.</param> /// <returns>Job Response</returns> public PSSiteRecoveryLongRunningOperation StartAzureSiteRecoveryApplyRecoveryPoint( string fabricName, string protectionContainerName, string replicationProtectedItemName, ApplyRecoveryPointInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginApplyRecoveryPointWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Starts Commit Failover /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Conatiner Name</param> /// <param name="replicationProtectedItemName">Replication Protected Item</param> /// <returns>Job Response</returns> public PSSiteRecoveryLongRunningOperation StartAzureSiteRecoveryCommitFailover( string fabricName, string protectionContainerName, string replicationProtectedItemName) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginFailoverCommitWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Starts Planned Failover /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Name</param> /// <param name="replicationProtectedItemName">Replication Protected Itenm</param> /// <param name="input">Input for Planned Failover</param> /// <returns>Job Response</returns> public PSSiteRecoveryLongRunningOperation StartAzureSiteRecoveryPlannedFailover( string fabricName, string protectionContainerName, string replicationProtectedItemName, PlannedFailoverInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginPlannedFailoverWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Re-protects the Azure Site Recovery protection entity. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Conatiner Name</param> /// <param name="replicationProtectedItemName">Replication Protected Item</param> /// <param name="input">Input for Reprotect</param> /// <returns>Job Response</returns> public PSSiteRecoveryLongRunningOperation StartAzureSiteRecoveryReprotection( string fabricName, string protectionContainerName, string replicationProtectedItemName, ReverseReplicationInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginReprotectWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Starts Test Failover /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Conatiner Name</param> /// <param name="replicationProtectedItemName">Replication Protected Item</param> /// <param name="input">Input for Test failover</param> /// <returns>Job Response</returns> public PSSiteRecoveryLongRunningOperation StartAzureSiteRecoveryTestFailover( string fabricName, string protectionContainerName, string replicationProtectedItemName, TestFailoverInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginTestFailoverWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Starts Test Failover Cleanup. /// </summary> /// <param name="fabricName">Fabric Name.</param> /// <param name="protectionContainerName">Protection Conatiner Name.</param> /// <param name="replicationProtectedItemName">Replication Protected Item.</param> /// <param name="input">Input for Test failover cleanup.</param> /// <returns>Job Response.</returns> public PSSiteRecoveryLongRunningOperation StartAzureSiteRecoveryTestFailoverCleanup( string fabricName, string protectionContainerName, string replicationProtectedItemName, TestFailoverCleanupInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginTestFailoverCleanupWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Starts Unplanned Failover /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Conatiner Name</param> /// <param name="replicationProtectedItemName">Replication Protected Item</param> /// <param name="input">Input for Unplanned failover</param> /// <returns>Job Response</returns> public PSSiteRecoveryLongRunningOperation StartAzureSiteRecoveryUnplannedFailover( string fabricName, string protectionContainerName, string replicationProtectedItemName, UnplannedFailoverInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginUnplannedFailoverWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Resyncs / Repairs Replication. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Conatiner Name</param> /// <param name="replicationProtectedItemName">Replication Protected Item</param> /// <returns>Job Response</returns> public PSSiteRecoveryLongRunningOperation StartAzureSiteRecoveryResynchronizeReplication( string fabricName, string protectionContainerName, string replicationProtectedItemName) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginRepairReplicationWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Updates Mobility Service. /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Conatiner Name</param> /// <param name="replicationProtectedItemName">Replication Protected Item</param> /// <param name="input">Update Mobility Service Request</param> /// <returns>Job Response</returns> public PSSiteRecoveryLongRunningOperation UpdateAzureSiteRecoveryMobilityService( string fabricName, string protectionContainerName, string replicationProtectedItemName, UpdateMobilityServiceRequest input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginUpdateMobilityServiceWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } /// <summary> /// Update Azure VM Properties /// </summary> /// <param name="fabricName">Fabric Name</param> /// <param name="protectionContainerName">Protection Container Name</param> /// <param name="replicationProtectedItemName">Replication Protected Item</param> /// <param name="input">Update Replication Protected Item Input</param> /// <returns></returns> public PSSiteRecoveryLongRunningOperation UpdateVmProperties( string fabricName, string protectionContainerName, string replicationProtectedItemName, UpdateReplicationProtectedItemInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginUpdateWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op); return result; } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.IO; using System.Reflection; using NUnit.Framework.Constraints; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Execution; namespace NUnit.Framework { /// <summary> /// Provide the context information of the current test. /// This is an adapter for the internal ExecutionContext /// class, hiding the internals from the user test. /// </summary> public class TestContext { private readonly TestExecutionContext _testExecutionContext; private TestAdapter _test; private ResultAdapter _result; #region Constructor /// <summary> /// Construct a TestContext for an ExecutionContext /// </summary> /// <param name="testExecutionContext">The ExecutionContext to adapt</param> public TestContext(TestExecutionContext testExecutionContext) { _testExecutionContext = testExecutionContext; } #endregion #region Properties /// <summary> /// Get the current test context. This is created /// as needed. The user may save the context for /// use within a test, but it should not be used /// outside the test for which it is created. /// </summary> public static TestContext CurrentContext { get { return new TestContext(TestExecutionContext.CurrentContext); } } /// <summary> /// Gets a TextWriter that will send output to the current test result. /// </summary> public static TextWriter Out { get { return TestExecutionContext.CurrentContext.OutWriter; } } /// <summary> /// Gets a TextWriter that will send output directly to Console.Error /// </summary> public static TextWriter Error = new EventListenerTextWriter("Error", Console.Error); /// <summary> /// Gets a TextWriter for use in displaying immediate progress messages /// </summary> public static readonly TextWriter Progress = new EventListenerTextWriter("Progress", Console.Error); /// <summary> /// TestParameters object holds parameters for the test run, if any are specified /// </summary> public static readonly TestParameters Parameters = new TestParameters(); /// <summary> /// Static DefaultWorkDirectory is now used as the source /// of the public instance property WorkDirectory. This is /// a bit odd but necessary to avoid breaking user tests. /// </summary> internal static string DefaultWorkDirectory; /// <summary> /// Get a representation of the current test. /// </summary> public TestAdapter Test { get { return _test ?? (_test = new TestAdapter(_testExecutionContext.CurrentTest)); } } /// <summary> /// Gets a Representation of the TestResult for the current test. /// </summary> public ResultAdapter Result { get { return _result ?? (_result = new ResultAdapter(_testExecutionContext.CurrentResult)); } } #if PARALLEL /// <summary> /// Gets the unique name of the Worker that is executing this test. /// </summary> public string WorkerId { get { return _testExecutionContext.TestWorker?.Name; } } #endif /// <summary> /// Gets the directory containing the current test assembly. /// </summary> public string TestDirectory { get { Assembly assembly = _testExecutionContext?.CurrentTest?.TypeInfo?.Assembly; if (assembly != null) return AssemblyHelper.GetDirectoryName(assembly); #if NETSTANDARD1_4 // Test is null, we may be loading tests rather than executing. // Assume that the NUnit framework is in the same directory as the tests return AssemblyHelper.GetDirectoryName(typeof(TestContext).GetTypeInfo().Assembly); #else // Test is null, we may be loading tests rather than executing. // Assume that calling assembly is the test assembly. return AssemblyHelper.GetDirectoryName(Assembly.GetCallingAssembly()); #endif } } /// <summary> /// Gets the directory to be used for outputting files created /// by this test run. /// </summary> public string WorkDirectory { get { return DefaultWorkDirectory; } } /// <summary> /// Gets the random generator. /// </summary> /// <value> /// The random generator. /// </value> public Randomizer Random { get { return _testExecutionContext.RandomGenerator; } } /// <summary> /// Gets the number of assertions executed /// up to this point in the test. /// </summary> public int AssertCount { get { return _testExecutionContext.AssertCount; } } /// <summary> /// Get the number of times the current Test has been repeated. This is currently only /// set when using the <see cref="RetryAttribute"/>. /// TODO: add this to the RepeatAttribute as well /// </summary> public int CurrentRepeatCount { get { return _testExecutionContext.CurrentRepeatCount; } } #endregion #region Static Methods /// <summary>Write the string representation of a boolean value to the current result</summary> public static void Write(bool value) { Out.Write(value); } /// <summary>Write a char to the current result</summary> public static void Write(char value) { Out.Write(value); } /// <summary>Write a char array to the current result</summary> public static void Write(char[] value) { Out.Write(value); } /// <summary>Write the string representation of a double to the current result</summary> public static void Write(double value) { Out.Write(value); } /// <summary>Write the string representation of an Int32 value to the current result</summary> public static void Write(Int32 value) { Out.Write(value); } /// <summary>Write the string representation of an Int64 value to the current result</summary> public static void Write(Int64 value) { Out.Write(value); } /// <summary>Write the string representation of a decimal value to the current result</summary> public static void Write(decimal value) { Out.Write(value); } /// <summary>Write the string representation of an object to the current result</summary> public static void Write(object value) { Out.Write(value); } /// <summary>Write the string representation of a Single value to the current result</summary> public static void Write(Single value) { Out.Write(value); } /// <summary>Write a string to the current result</summary> public static void Write(string value) { Out.Write(value); } /// <summary>Write the string representation of a UInt32 value to the current result</summary> [CLSCompliant(false)] public static void Write(UInt32 value) { Out.Write(value); } /// <summary>Write the string representation of a UInt64 value to the current result</summary> [CLSCompliant(false)] public static void Write(UInt64 value) { Out.Write(value); } /// <summary>Write a formatted string to the current result</summary> public static void Write(string format, object arg1) { Out.Write(format, arg1); } /// <summary>Write a formatted string to the current result</summary> public static void Write(string format, object arg1, object arg2) { Out.Write(format, arg1, arg2); } /// <summary>Write a formatted string to the current result</summary> public static void Write(string format, object arg1, object arg2, object arg3) { Out.Write(format, arg1, arg2, arg3); } /// <summary>Write a formatted string to the current result</summary> public static void Write(string format, params object[] args) { Out.Write(format, args); } /// <summary>Write a line terminator to the current result</summary> public static void WriteLine() { Out.WriteLine(); } /// <summary>Write the string representation of a boolean value to the current result followed by a line terminator</summary> public static void WriteLine(bool value) { Out.WriteLine(value); } /// <summary>Write a char to the current result followed by a line terminator</summary> public static void WriteLine(char value) { Out.WriteLine(value); } /// <summary>Write a char array to the current result followed by a line terminator</summary> public static void WriteLine(char[] value) { Out.WriteLine(value); } /// <summary>Write the string representation of a double to the current result followed by a line terminator</summary> public static void WriteLine(double value) { Out.WriteLine(value); } /// <summary>Write the string representation of an Int32 value to the current result followed by a line terminator</summary> public static void WriteLine(Int32 value) { Out.WriteLine(value); } /// <summary>Write the string representation of an Int64 value to the current result followed by a line terminator</summary> public static void WriteLine(Int64 value) { Out.WriteLine(value); } /// <summary>Write the string representation of a decimal value to the current result followed by a line terminator</summary> public static void WriteLine(decimal value) { Out.WriteLine(value); } /// <summary>Write the string representation of an object to the current result followed by a line terminator</summary> public static void WriteLine(object value) { Out.WriteLine(value); } /// <summary>Write the string representation of a Single value to the current result followed by a line terminator</summary> public static void WriteLine(Single value) { Out.WriteLine(value); } /// <summary>Write a string to the current result followed by a line terminator</summary> public static void WriteLine(string value) { Out.WriteLine(value); } /// <summary>Write the string representation of a UInt32 value to the current result followed by a line terminator</summary> [CLSCompliant(false)] public static void WriteLine(UInt32 value) { Out.WriteLine(value); } /// <summary>Write the string representation of a UInt64 value to the current result followed by a line terminator</summary> [CLSCompliant(false)] public static void WriteLine(UInt64 value) { Out.WriteLine(value); } /// <summary>Write a formatted string to the current result followed by a line terminator</summary> public static void WriteLine(string format, object arg1) { Out.WriteLine(format, arg1); } /// <summary>Write a formatted string to the current result followed by a line terminator</summary> public static void WriteLine(string format, object arg1, object arg2) { Out.WriteLine(format, arg1, arg2); } /// <summary>Write a formatted string to the current result followed by a line terminator</summary> public static void WriteLine(string format, object arg1, object arg2, object arg3) { Out.WriteLine(format, arg1, arg2, arg3); } /// <summary>Write a formatted string to the current result followed by a line terminator</summary> public static void WriteLine(string format, params object[] args) { Out.WriteLine(format, args); } /// <summary> /// This method adds the a new ValueFormatterFactory to the /// chain of responsibility used for formatting values in messages. /// The scope of the change is the current TestContext. /// </summary> /// <param name="formatterFactory">The factory delegate</param> public static void AddFormatter(ValueFormatterFactory formatterFactory) { TestExecutionContext.CurrentContext.AddFormatter(formatterFactory); } /// <summary> /// Attach a file to the current test result /// </summary> /// <param name="filePath">Relative or absolute file path to attachment</param> /// <param name="description">Optional description of attachment</param> public static void AddTestAttachment(string filePath, string description = null) { Guard.ArgumentNotNull(filePath, nameof(filePath)); Guard.ArgumentValid(filePath.IndexOfAny(Path.GetInvalidPathChars()) == -1, $"Test attachment file path contains invalid path characters. {filePath}", nameof(filePath)); if (!Path.IsPathRooted(filePath)) filePath = Path.Combine(TestContext.CurrentContext.WorkDirectory, filePath); if (!File.Exists(filePath)) throw new FileNotFoundException("Test attachment file path could not be found.", filePath); var result = TestExecutionContext.CurrentContext.CurrentResult; result.AddTestAttachment(new TestAttachment(filePath, description)); } /// <summary> /// This method provides a simplified way to add a ValueFormatter /// delegate to the chain of responsibility, creating the factory /// delegate internally. It is useful when the Type of the object /// is the only criterion for selection of the formatter, since /// it can be used without getting involved with a compound function. /// </summary> /// <typeparam name="TSupported">The type supported by this formatter</typeparam> /// <param name="formatter">The ValueFormatter delegate</param> public static void AddFormatter<TSupported>(ValueFormatter formatter) { AddFormatter(next => val => (val is TSupported) ? formatter(val) : next(val)); } #endregion #region Nested TestAdapter Class /// <summary> /// TestAdapter adapts a Test for consumption by /// the user test code. /// </summary> public class TestAdapter { private readonly Test _test; #region Constructor /// <summary> /// Construct a TestAdapter for a Test /// </summary> /// <param name="test">The Test to be adapted</param> public TestAdapter(Test test) { _test = test; } #endregion #region Properties /// <summary> /// Gets the unique Id of a test /// </summary> public String ID { get { return _test.Id; } } /// <summary> /// The name of the test, which may or may not be /// the same as the method name. /// </summary> public string Name { get { return _test.Name; } } /// <summary> /// The name of the method representing the test. /// </summary> public string MethodName { get { return _test is TestMethod ? _test.Method.Name : null; } } /// <summary> /// The FullName of the test /// </summary> public string FullName { get { return _test.FullName; } } /// <summary> /// The ClassName of the test /// </summary> public string ClassName { get { return _test.ClassName; } } /// <summary> /// A shallow copy of the properties of the test. /// </summary> public PropertyBagAdapter Properties { get { return new PropertyBagAdapter(_test.Properties); } } /// <summary> /// The arguments to use in creating the test or empty array if none are required. /// </summary> public object[] Arguments { get { return _test.Arguments; } } #endregion } #endregion #region Nested ResultAdapter Class /// <summary> /// ResultAdapter adapts a TestResult for consumption by /// the user test code. /// </summary> public class ResultAdapter { private readonly TestResult _result; #region Constructor /// <summary> /// Construct a ResultAdapter for a TestResult /// </summary> /// <param name="result">The TestResult to be adapted</param> public ResultAdapter(TestResult result) { _result = result; } #endregion #region Properties /// <summary> /// Gets a ResultState representing the outcome of the test /// up to this point in its execution. /// </summary> public ResultState Outcome { get { return _result.ResultState; } } /// <summary> /// Gets a list of the assertion results generated /// up to this point in the test. /// </summary> public IEnumerable<AssertionResult> Assertions { get { return _result.AssertionResults; } } /// <summary> /// Gets the message associated with a test /// failure or with not running the test /// </summary> public string Message { get { return _result.Message; } } /// <summary> /// Gets any stack trace associated with an /// error or failure. /// </summary> public virtual string StackTrace { get { return _result.StackTrace; } } /// <summary> /// Gets the number of test cases that failed /// when running the test and all its children. /// </summary> public int FailCount { get { return _result.FailCount; } } /// <summary> /// Gets the number of test cases that had warnings /// when running the test and all its children. /// </summary> public int WarningCount { get { return _result.WarningCount; } } /// <summary> /// Gets the number of test cases that passed /// when running the test and all its children. /// </summary> public int PassCount { get { return _result.PassCount; } } /// <summary> /// Gets the number of test cases that were skipped /// when running the test and all its children. /// </summary> public int SkipCount { get { return _result.SkipCount; } } /// <summary> /// Gets the number of test cases that were inconclusive /// when running the test and all its children. /// </summary> public int InconclusiveCount { get { return _result.InconclusiveCount; } } #endregion } #endregion #region Nested PropertyBagAdapter Class /// <summary> /// <see cref="PropertyBagAdapter"/> adapts an <see cref="IPropertyBag"/> /// for consumption by the user. /// </summary> public class PropertyBagAdapter { private readonly IPropertyBag _source; /// <summary> /// Construct a <see cref="PropertyBagAdapter"/> from a source /// <see cref="IPropertyBag"/>. /// </summary> public PropertyBagAdapter(IPropertyBag source) { _source = source; } /// <summary> /// Get the first property with the given <paramref name="key"/>, if it can be found, otherwise /// returns null. /// </summary> public object Get(string key) { return _source.Get(key); } /// <summary> /// Indicates whether <paramref name="key"/> is found in this /// <see cref="PropertyBagAdapter"/>. /// </summary> public bool ContainsKey(string key) { return _source.ContainsKey(key); } /// <summary> /// Returns a collection of properties /// with the given <paramref name="key"/>. /// </summary> public IEnumerable<object> this[string key] { get { var list = new List<object>(); foreach(var item in _source[key]) { list.Add(item); } return list; } } /// <summary> /// Returns the count of elements with the given <paramref name="key"/>. /// </summary> public int Count(string key) { return _source[key].Count; } /// <summary> /// Returns a collection of the property keys. /// </summary> public ICollection<string> Keys { get { return _source.Keys; } } } #endregion } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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; namespace SharpDX.DirectInput { /// <summary> /// Properties for a <see cref="Device"/>. /// </summary> public partial class DeviceProperties : PropertyAccessor { internal DeviceProperties(Device device) : base(device, 0, PropertyHowType.Device) { } /// <summary> /// Gets the key code for a keyboard key. An exception is raised if the property cannot resolve specialized keys on USB keyboards because they do not exist in scan code form. For all other failures, an exception is also returned. /// </summary> /// <param name="key">The key id.</param> /// <returns>The key code</returns> public int GetKeyCode(Key key) { // TODO check BYid return GetInt(PropertyGuids.Scancode, (int) key); } /// <summary> /// Gets the localized key name for a keyboard key. Using this property on devices other than a keyboard will return unexpected names. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public string GetKeyName(Key key) { // TODO check BYid return GetString(PropertyGuids.Keyname, (int)key); } // ApplicationData are not working, seems to be a bug in DirectInput ///// <summary> ///// Gets or sets the application-defined value associated with an in-game action. ///// </summary> ///// <value>The application data.</value> //public object ApplicationData //{ // get { return GetObject(PropertyGuids.Appdata); } // set { SetObject(PropertyGuids.Appdata, value); } //} /// <summary> /// Gets or sets a value indicating whether device objects are self centering. /// </summary> /// <value><c>true</c> if device objects are self centering; otherwise, <c>false</c>.</value> public bool AutoCenter { get { return GetInt(PropertyGuids.Autocenter) != 0; } set { Set(PropertyGuids.Autocenter, value ? 1 : 0); } } /// <summary> /// Gets or sets the axis mode. /// </summary> /// <value>The axis mode.</value> public DeviceAxisMode AxisMode { get { return (DeviceAxisMode) GetInt(PropertyGuids.Axismode); } set { Set(PropertyGuids.Axismode, (int) value); } } /// <summary> /// Gets or sets the input buffer size. The buffer size determines the amount of data that the buffer can hold between calls to the <see cref="Device.GetDeviceData"/> method before data is lost. You can set this value to 0 to indicate that the application does not read buffered data from the device. If the buffer size is too large for the device to support it, then the largest possible buffer size is set. However, this property always returns the buffer size set using the <see cref="BufferSize"/> property, even if the buffer cannot be supported because it is too large. /// </summary> /// <value>The size of the buffer.</value> public int BufferSize { get { return GetInt(PropertyGuids.BufferSize); } set { Set(PropertyGuids.BufferSize, value); } } /// <summary> /// Gets the class GUID for the device. This property lets advanced applications perform operations on a human interface device that are not supported by DirectInput. /// </summary> /// <value>The class GUID.</value> public Guid ClassGuid { get { return GetGuid(PropertyGuids.Guidandpath); } } /// <summary> /// Gets or sets the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range. /// </summary> /// <value>The dead zone.</value> public int DeadZone { get { return GetInt(PropertyGuids.Deadzone); } set { Set(PropertyGuids.Deadzone, value); } } /// <summary> /// Gets or sets the force feedback gain of the device. /// The gain value is applied to all effects created on the device. The value is an integer in the range from 0 through 10,000, specifying the amount by which effect magnitudes should be scaled for the device. For example, a value of 10,000 indicates that all effect magnitudes are to be taken at face value. A value of 9,000 indicates that all effect magnitudes are to be reduced to 90 percent of their nominal magnitudes. /// DirectInput always checks the gain value before setting the gain property. If the gain is outside of the range (less than zero or greater than 10,000), setting this property will raise an exception. Otherwise, no exception if successful, even if the device does not support force feedback. /// Setting a gain value is useful when an application wants to scale down the strength of all force-feedback effects uniformly, based on user preferences. /// Unlike other properties, the gain can be set when the device is in an acquired state. /// </summary> /// <value>The force feedback gain.</value> public int ForceFeedbackGain { get { return GetInt(PropertyGuids.Ffgain); } set { Set(PropertyGuids.Ffgain, value); } } /// <summary> /// Gets the input granularity. Granularity represents the smallest distance over which the object reports movement. Most axis objects have a granularity of one; that is, all values are possible. Some axes have a larger granularity. For example, the wheel axis on a mouse can have a granularity of 20; that is, all reported changes in position are multiples of 20. In other words, when the user turns the wheel slowly, the device reports a position of 0, then 20, then 40, and so on. This is a read-only property. /// </summary> /// <value>The granularity.</value> public int Granularity { get { return GetInt(PropertyGuids.Granularity); } } /// <summary> /// Gets or sets the friendly instance name of the device. /// This property exists for advanced applications that want to change the friendly instance name of a device (as returned in the tszInstanceName member of the <see cref="DeviceInstance"/> structure) to distinguish it from similar devices that are plugged in simultaneously. Most applications should have no need to change the friendly name. /// </summary> /// <value>The name of the instance.</value> public string InstanceName { get { return GetString(PropertyGuids.InstanceName); } set { Set(PropertyGuids.InstanceName, value); } } /// <summary> /// Gets the device interface path for the device. This property lets advanced applications perform operations on a human interface device that are not supported by DirectInput. /// </summary> /// <value>The interface path.</value> public string InterfacePath { get { return GetPath(PropertyGuids.Guidandpath); } } /// <summary> /// Gets the instance number of a joystick. This property is not implemented for the mouse or keyboard. /// </summary> /// <value>The joystick id.</value> public int JoystickId { get { return GetInt(PropertyGuids.Joystickid); } } /// <summary> /// Gets the memory load for the device. This setting applies to the entire device, rather than to any particular object. The retrieved value is in the range from 0 through 100, indicating the percentage of device memory in use. The device must be acquired in exclusive mode. If it is not, the method will fail with an exception. /// </summary> /// <value>The memory load.</value> public int MemoryLoad { get { return GetInt(PropertyGuids.Ffload); } } /// <summary> /// Gets the human-readable display name of the port to which this device is connected. Not generally used by applications. /// </summary> /// <value>The human-readable display name of the port to which this device is connected.</value> public string PortDisplayName { get { return GetPath(PropertyGuids.GetPortdisplayname); } } /// <summary> /// Gets the vendor identity (ID) and product ID of a HID device. This property is of type int and contains both values. These two short values are combined. This property applies to the entire device, rather than to any particular object. /// </summary> /// <value>The product id.</value> public int ProductId { get { return (GetInt(PropertyGuids.Vidpid) >> 16) & 0xFFFF; } } /// <summary> /// Gets or sets the friendly product name of the device. /// This property exists for advanced applications that want to change the friendly product name of a device (as returned in the tszProductName member of the <see cref="DeviceInstance"/> structure) to distinguish it from similar devices which are plugged in simultaneously. Most applications should have no need to change the friendly name. /// This setting applies to the entire device. /// Setting the product name is only useful for changing the user-defined name of an analog joystick on Microsoft Windows 98, Windows 2000, and Windows Millennium Edition (Windows Me) computers. In other cases, attempting to set this property will still return ok. However, the name is not stored in a location used by the getter of this property. /// </summary> /// <value>The name of the product.</value> public string ProductName { get { return GetString(PropertyGuids.Productname); } set { Set(PropertyGuids.Productname, value); } } /// <summary> /// Gets the range of values an object can possibly report. /// </summary> /// <value>The range.</value> public InputRange Range { get { return GetRange(PropertyGuids.Range); } } /// <summary> /// Gets or sets the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone). /// </summary> /// <value>The saturation.</value> public int Saturation { get { return GetInt(PropertyGuids.Saturation); } set { Set(PropertyGuids.Saturation, value); } } /// <summary> /// Gets the type name of a device. For most game controllers, this is the registry key name under REGSTR_PATH_JOYOEM from which static device settings can be retrieved, but predefined joystick types have special names consisting of a number sign (&Sharp;) followed by a character dependent on the type. This value might not be available for all devices. /// </summary> /// <value>The name of the type.</value> public string TypeName { get { return GetPath(PropertyGuids.Typename); } } /// <summary> /// Gets the user name for a user currently assigned to a device. User names are set by calling <see cref="Device.SetActionMap"/>. If no user name is set, the method throws an exception. /// </summary> /// <value>The name of the user.</value> public string UserName { get { return GetPath(PropertyGuids.Username); } } /// <summary> /// Gets the vendor identity (ID) and product ID of a HID device. This property is of type int and contains both values. These two short values are combined. This property applies to the entire device, rather than to any particular object. /// </summary> /// <value>The product id.</value> public int VendorId { get { return GetInt(PropertyGuids.Vidpid) & 0xFFFF; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; public class MyCqListener2<TKey, TResult> : ICqListener<TKey, TResult> { private int m_create = 0; private int m_update = 0; private int m_id = 0; public MyCqListener2(int id) { this.m_id = id; } public int Creates { get { return m_create; } } public int Updates { get { return m_update; } } #region ICqListener Members void ICqListener<TKey, TResult>.Close() { Util.Log("CqListener closed with ID = " + m_id); } void ICqListener<TKey, TResult>.OnError(CqEvent<TKey, TResult> ev) { Util.Log("CqListener OnError called "); } void ICqListener<TKey, TResult>.OnEvent(CqEvent<TKey, TResult> ev) { Util.Log("CqListener OnEvent ops = " + ev.getBaseOperation()); if (ev.getBaseOperation() == CqOperation.OP_TYPE_CREATE) m_create++; else if (ev.getBaseOperation() == CqOperation.OP_TYPE_UPDATE) m_update++; } #endregion } [TestFixture] [Category("group4")] [Category("unicast_only")] [Category("generics")] public class ThinClientSecurityAuthzTestsMU : ThinClientSecurityAuthzTestBase { #region Private members IRegion<object, object> region; IRegion<object, object> region1; private UnitProcess m_client1; private UnitProcess m_client2; private UnitProcess m_client3; private TallyListener<object, object> m_listener; private TallyWriter<object, object> m_writer; private string/*<object>*/ keys = "Key"; private string value = "Value"; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); m_client3 = new UnitProcess(); return new ClientBase[] { m_client1, m_client2, m_client3 }; } public void CreateRegion(string locators, bool caching, bool listener, bool writer) { Util.Log(" in CreateRegion " + listener + " : " + writer); if (listener) { m_listener = new TallyListener<object, object>(); } else { m_listener = null; } IRegion<object, object> region = null; region = CacheHelper.CreateTCRegion_Pool<object, object>(RegionName, true, caching, m_listener, locators, "__TESTPOOL1_", true); if (writer) { m_writer = new TallyWriter<object, object>(); } else { m_writer = null; } Util.Log("region created "); AttributesMutator<object, object> at = region.AttributesMutator; at.SetCacheWriter(m_writer); } public void DoPut() { region = CacheHelper.GetRegion<object, object>(RegionName); region[keys.ToString()] = value; } public void CheckAssert() { Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer Should be invoked"); Assert.AreEqual(false, m_listener.IsListenerInvoked, "Listener Should not be invoked"); Assert.IsFalse(region.ContainsKey(keys.ToString()), "Key should have been found in the region"); } public void DoLocalPut() { region1 = CacheHelper.GetRegion<object, object>(RegionName); region1.GetLocalView()[m_keys[2]] = m_vals[2]; //this check is no loger valid as ContainsKey goes on server //Assert.IsTrue(region1.ContainsKey(m_keys[2]), "Key should have been found in the region"); Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer Should be invoked"); Assert.AreEqual(true, m_listener.IsListenerInvoked, "Listener Should be invoked"); //try Update try { Util.Log("Trying UpdateEntry"); m_listener.ResetListenerInvokation(); UpdateEntry(RegionName, m_keys[2], m_nvals[2], false); Assert.Fail("Should have got NotAuthorizedException during updateEntry"); } catch (NotAuthorizedException) { Util.Log("NotAuthorizedException Caught"); Util.Log("Success"); } catch (Exception other) { Util.Log("Stack trace: {0} ", other.StackTrace); Util.Log("Got exception : {0}", other.Message); } Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer should be invoked"); Assert.AreEqual(false, m_listener.IsListenerInvoked, "Listener should not be invoked"); //Assert.IsTrue(region1.ContainsKey(m_keys[2]), "Key should have been found in the region"); VerifyEntry(RegionName, m_keys[2], m_vals[2]); m_writer.SetWriterFailed(); //test CacheWriter try { Util.Log("Testing CacheWriterException"); UpdateEntry(RegionName, m_keys[2], m_nvals[2], false); Assert.Fail("Should have got NotAuthorizedException during updateEntry"); } catch (CacheWriterException) { Util.Log("CacheWriterException Caught"); Util.Log("Success"); } } [TestFixtureTearDown] public override void EndTests() { CacheHelper.StopJavaServers(); base.EndTests(); } [TearDown] public override void EndTest() { try { if (m_clients != null) { foreach (ClientBase client in m_clients) { client.Call(CacheHelper.Close); } } CacheHelper.Close(); CacheHelper.ClearEndpoints(); } finally { CacheHelper.StopJavaServers(); } base.EndTest(); } protected const string RegionName_CQ = "Portfolios"; static QueryService gQueryService = null; static string [] QueryStrings = { "select * from /Portfolios p where p.ID < 1", "select * from /Portfolios p where p.ID < 2", "select * from /Portfolios p where p.ID = 2", "select * from /Portfolios p where p.ID >= 3",//this should pass "select * from /Portfolios p where p.ID = 4",//this should pass "select * from /Portfolios p where p.ID = 5", "select * from /Portfolios p where p.ID = 6", "select * from /Portfolios p where p.ID = 7" }; public void registerCQ(Properties<string, string> credentials, bool durableCQ) { Util.Log("registerCQ"); try { CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Portfolio.CreateDeserializable); CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Position.CreateDeserializable); Util.Log("registerCQ portfolio registered"); } catch (IllegalStateException) { Util.Log("registerCQ portfolio NOT registered"); // ignore since we run multiple iterations for pool and non pool configs } // VJR: TODO fix cache.GetQueryService to also be generic gQueryService = CacheHelper.getMultiuserCache(credentials).GetQueryService(); for (int i = 0; i < QueryStrings.Length; i++) { CqAttributesFactory<object, object> cqAttrFact = new CqAttributesFactory<object, object>(); cqAttrFact.AddCqListener(new MyCqListener2<object, object>(i)); CqQuery<object, object> cq = gQueryService.NewCq("cq_" + i, QueryStrings[i], cqAttrFact.Create(), durableCQ); cq.Execute(); } Util.Log("registerCQ Done."); } public void doCQPut(Properties<string, string> credentials) { Util.Log("doCQPut"); try { CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Portfolio.CreateDeserializable); CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Position.CreateDeserializable); Util.Log("doCQPut portfolio registered"); } catch (IllegalStateException) { Util.Log("doCQPut portfolio NOT registered"); // ignore since we run multiple iterations for pool and non pool configs } //IRegion<object, object> region = CacheHelper.GetVerifyRegion(RegionName_CQ, credentials); IRegionService userRegionService = CacheHelper.getMultiuserCache(credentials); IRegion<object, object>[] regions = userRegionService.RootRegions<object, object>(); IRegion<object, object> region = null; Console.Out.WriteLine("Number of regions " + regions.Length); for (int i = 0; i < regions.Length; i++) { if (regions[i].Name.Equals(RegionName_CQ)) { region = regions[i]; break; } } for (int i = 0; i < QueryStrings.Length; i++) { string key = "port1-" + i; Portfolio p = new Portfolio(i); region[key] = p; } IRegionService rgServ = region.RegionService; Cache cache = rgServ as Cache; Assert.IsNull(cache); Thread.Sleep(20000); Util.Log("doCQPut Done."); } public void verifyCQEvents(bool whetherResult, CqOperation opType ) { Util.Log("verifyCQEvents " + gQueryService); Assert.IsNotNull(gQueryService); CqQuery<object, object> cq = gQueryService.GetCq<object, object>("cq_" + 3); ICqListener<object, object>[] cqL = cq.GetCqAttributes().getCqListeners(); MyCqListener2<object, object> mcqL = (MyCqListener2<object, object>)cqL[0]; Util.Log("got result for cq listener3 " + cq.Name + " : " + mcqL.Creates); if (opType == CqOperation.OP_TYPE_CREATE) { if (whetherResult) Assert.AreEqual(1, mcqL.Creates, "CQ listener 3 should get one create event "); else Assert.AreEqual(0, mcqL.Creates, "CQ listener 3 should not get any create event "); } else if (opType == CqOperation.OP_TYPE_UPDATE) { if (whetherResult) Assert.AreEqual(1, mcqL.Updates, "CQ listener 3 should get one update event "); else Assert.AreEqual(0, mcqL.Updates, "CQ listener 3 should not get any update event "); } cq = gQueryService.GetCq<object, object>("cq_" + 4); cqL = cq.GetCqAttributes().getCqListeners(); mcqL = (MyCqListener2<object, object>)cqL[0]; Util.Log("got result for cq listener4 " + cq.Name + " : " + mcqL.Creates); if (opType == CqOperation.OP_TYPE_CREATE) { if (whetherResult) Assert.AreEqual(1, mcqL.Creates, "CQ listener 4 should get one create event "); else Assert.AreEqual(0, mcqL.Creates, "CQ listener 4 should not get any create event "); } else if (opType == CqOperation.OP_TYPE_UPDATE) { if (whetherResult) Assert.AreEqual(1, mcqL.Updates, "CQ listener 4 should get one update event "); else Assert.AreEqual(0, mcqL.Updates, "CQ listener 4 should not get any update event "); } cq = gQueryService.GetCq<object, object>("cq_" + 0); cqL = cq.GetCqAttributes().getCqListeners(); mcqL = (MyCqListener2<object, object>)cqL[0]; Util.Log("got result for cq listener0 " + cq.Name + " : " + mcqL.Creates); Assert.AreEqual(0, mcqL.Creates, "CQ listener 0 should get one create event "); // CacheHelper.getMultiuserCache(null).Close(); gQueryService = null; } void runCQTest() { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); DummyAuthorization3 da = new DummyAuthorization3(); string authenticator = da.Authenticator; string authInit = da.AuthInit; string accessorPP = da.AuthenticatorPP; Util.Log("testAllowPutsGets: Using authinit: " + authInit); Util.Log("testAllowPutsGets: Using authenticator: " + authenticator); Util.Log("testAllowPutsGets: Using accessorPP: " + accessorPP); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, null, accessorPP, null, null); // Start the two servers. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); // Start client1 with valid CREATE credentials, this index will be used to authorzie the user Properties<string, string> createCredentials = da.GetValidCredentials(4); Util.Log("runCQTest: "); m_client1.Call(SecurityTestUtil.CreateClientMU2, RegionName_CQ, CacheHelper.Locators, authInit, (Properties<string, string>)null, true, true); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName_CQ, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Perform some put operations from client1 m_client1.Call(registerCQ, createCredentials, false); // Verify that the gets succeed m_client2.Call(doCQPut, createCredentials); m_client1.Call(verifyCQEvents, true, CqOperation.OP_TYPE_CREATE); m_client1.Call(CloseUserCache, false); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); // CacheHelper.StopJavaServer(2); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } public void CloseUserCache(bool keepAlive) { Util.Log("CloseUserCache keepAlive: " + keepAlive); CacheHelper.CloseUserCache(keepAlive); } private static string DurableClientId1 = "DurableClientId1"; //private static string DurableClientId2 = "DurableClientId2"; void runDurableCQTest(bool logicalCacheClose, bool durableCQ, bool whetherResult) { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); DummyAuthorization3 da = new DummyAuthorization3(); string authenticator = da.Authenticator; string authInit = da.AuthInit; string accessorPP = da.AuthenticatorPP; Util.Log("testAllowPutsGets: Using authinit: " + authInit); Util.Log("testAllowPutsGets: Using authenticator: " + authenticator); Util.Log("testAllowPutsGets: Using accessorPP: " + accessorPP); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, null, accessorPP, null, null); // Start the two servers. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); // Start client1 with valid CREATE credentials, this index will be used to authorzie the user Properties<string, string> createCredentials = da.GetValidCredentials(4); Util.Log("runCQTest: "); /* regionName, string endpoints, string locators, authInit, Properties credentials, bool pool, bool locator, bool isMultiuser, bool notificationEnabled, string durableClientId) */ m_client1.Call(SecurityTestUtil.CreateMUDurableClient, RegionName_CQ, CacheHelper.Locators, authInit, DurableClientId1, true, true ); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName_CQ, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); m_client1.Call(ReadyForEvents2); // Perform some put operations from client1 m_client1.Call(registerCQ, createCredentials, durableCQ); Properties<string, string> createCredentials2 = da.GetValidCredentials(3); // Verify that the gets succeed m_client2.Call(doCQPut, createCredentials2); //close cache client-1 m_client1.Call(verifyCQEvents, true, CqOperation.OP_TYPE_CREATE); Thread.Sleep(10000); Util.Log("Before calling CloseUserCache: " + logicalCacheClose); if (logicalCacheClose) m_client1.Call(CloseUserCache, logicalCacheClose); m_client1.Call(CloseKeepAlive); //put again from other client m_client2.Call(doCQPut, createCredentials2); //client-1 will up again m_client1.Call(SecurityTestUtil.CreateMUDurableClient, RegionName_CQ, CacheHelper.Locators, authInit, DurableClientId1, true, true); // Perform some put operations from client1 m_client1.Call(registerCQ, createCredentials, durableCQ); m_client1.Call(ReadyForEvents2); Thread.Sleep(20000); m_client1.Call(verifyCQEvents, whetherResult, CqOperation.OP_TYPE_UPDATE); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); // CacheHelper.StopJavaServer(2); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runAllowPutsGets() { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(true)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; Util.Log("testAllowPutsGets: Using authinit: " + authInit); Util.Log("testAllowPutsGets: Using authenticator: " + authenticator); Util.Log("testAllowPutsGets: Using accessor: " + accessor); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Start the two servers. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); // Start client1 with valid CREATE credentials Properties<string, string> createCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 1); javaProps = cGen.JavaProperties; Util.Log("AllowPutsGets: For first client PUT credentials: " + createCredentials); m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Start client2 with valid GET credentials Properties<string, string> getCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 2); javaProps = cGen.JavaProperties; Util.Log("AllowPutsGets: For second client GET credentials: " + getCredentials); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Perform some put operations from client1 m_client1.Call(DoPutsMU, 10 , createCredentials, true); // Verify that the gets succeed m_client2.Call(DoGetsMU, 10, getCredentials, true); m_client1.Call(DoPutsTx, 10, true, ExpectedResult.Success, getCredentials, true); m_client2.Call(DoGets, 10, true, ExpectedResult.Success, getCredentials, true); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaServer(2); } CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runDisallowPutsGets() { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(true)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; Util.Log("DisallowPutsGets: Using authinit: " + authInit); Util.Log("DisallowPutsGets: Using authenticator: " + authenticator); Util.Log("DisallowPutsGets: Using accessor: " + accessor); // Check that we indeed can obtain valid credentials not allowed to do // gets Properties<string, string> createCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 1); Properties<string, string> createJavaProps = cGen.JavaProperties; Properties<string, string> getCredentials = authzGen.GetDisallowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 2); Properties<string, string> getJavaProps = cGen.JavaProperties; if (getCredentials == null || getCredentials.Size == 0) { Util.Log("DisallowPutsGets: Unable to obtain valid credentials " + "with no GET permission; skipping this combination."); continue; } // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Start the two servers. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); // Start client1 with valid CREATE credentials createCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 1); javaProps = cGen.JavaProperties; Util.Log("DisallowPutsGets: For first client PUT credentials: " + createCredentials); m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Start client2 with invalid GET credentials getCredentials = authzGen.GetDisallowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 2); javaProps = cGen.JavaProperties; Util.Log("DisallowPutsGets: For second client invalid GET " + "credentials: " + getCredentials); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Perform some put operations from client1 m_client1.Call(DoPutsMU, 10, createCredentials, true); // Verify that the gets throw exception m_client2.Call(DoGetsMU, 10, getCredentials, true, ExpectedResult.NotAuthorizedException); // Try to connect client2 with reader credentials getCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 5); javaProps = cGen.JavaProperties; Util.Log("DisallowPutsGets: For second client valid GET " + "credentials: " + getCredentials); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Verify that the gets succeed m_client2.Call(DoGetsMU, 10, getCredentials, true); // Verify that the puts throw exception m_client2.Call(DoPutsMU, 10, getCredentials, true, ExpectedResult.NotAuthorizedException); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaServer(2); } CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runInvalidAccessor() { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(true)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Util.Log("NIl:792:Current credential is = {0}", cGen); //if (cGen.GetClassCode() == CredentialGenerator.ClassCode.LDAP) // continue; Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; Util.Log("InvalidAccessor: Using authinit: " + authInit); Util.Log("InvalidAccessor: Using authenticator: " + authenticator); // Start server1 with invalid accessor string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, "com.gemstone.none", null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); // Client creation should throw exceptions Properties<string, string> createCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 3); javaProps = cGen.JavaProperties; Util.Log("InvalidAccessor: For first client PUT credentials: " + createCredentials); m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Now perform some put operations from client1 m_client1.Call(DoPutsMU, 10, createCredentials, true, ExpectedResult.OtherException); Properties<string, string> getCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 7); javaProps = cGen.JavaProperties; Util.Log("InvalidAccessor: For second client GET credentials: " + getCredentials); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Now perform some put operations from client1 m_client2.Call(DoGetsMU, 10, getCredentials, true, ExpectedResult.OtherException); // Now start server2 that has valid accessor Util.Log("InvalidAccessor: Using accessor: " + accessor); serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); CacheHelper.StopJavaServer(1); // Client creation should be successful now m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Now perform some put operations from client1 m_client1.Call(DoPutsMU, 10, createCredentials, true); // Verify that the gets succeed m_client2.Call(DoGetsMU, 10, getCredentials, true); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(2); } CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runAllOpsWithFailover() { OperationWithAction[] allOps = { // Test CREATE and verify with a GET new OperationWithAction(OperationCode.Put, 3, OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Put), new OperationWithAction(OperationCode.Get, 3, OpFlags.CheckNoKey | OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Get, 2, OpFlags.CheckNoKey, 4), // OPBLOCK_END indicates end of an operation block; the above block of // three operations will be first executed on server1 and then on // server2 after failover OperationWithAction.OpBlockEnd, // Test GetServerKeys (KEY_SET) operation. new OperationWithAction(OperationCode.GetServerKeys), new OperationWithAction(OperationCode.GetServerKeys, 3, OpFlags.CheckNotAuthz, 4), OperationWithAction.OpBlockEnd, // Test UPDATE and verify with a GET new OperationWithAction(OperationCode.Put, 3, OpFlags.UseNewVal | OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Put, 1, OpFlags.UseNewVal, 4), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.UseNewVal, 4), OperationWithAction.OpBlockEnd, // Test DESTROY and verify with a GET and that key should not exist new OperationWithAction(OperationCode.Destroy, 3, OpFlags.UseNewVal | OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Destroy), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.CheckFail, 4), // Repopulate the region new OperationWithAction(OperationCode.Put, 1, OpFlags.UseNewVal, 4), OperationWithAction.OpBlockEnd, // Check QUERY new OperationWithAction(OperationCode.Put), new OperationWithAction(OperationCode.Query, 3, OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Query), OperationWithAction.OpBlockEnd, // UPDATE and test with GET new OperationWithAction(OperationCode.Put), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.LocalOp, 4), // UPDATE and test with GET for no updates new OperationWithAction(OperationCode.Put, 1, OpFlags.UseOldConn | OpFlags.UseNewVal, 4), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.LocalOp, 4), OperationWithAction.OpBlockEnd, /// PutAll, GetAll, ExecuteCQ and ExecuteFunction ops new OperationWithAction(OperationCode.PutAll), // NOTE: GetAll depends on previous PutAll so it should happen right after. new OperationWithAction(OperationCode.GetAll), new OperationWithAction(OperationCode.RemoveAll), //new OperationWithAction(OperationCode.ExecuteCQ), new OperationWithAction(OperationCode.ExecuteFunction), OperationWithAction.OpBlockEnd, // UPDATE and test with GET new OperationWithAction(OperationCode.Put, 2), new OperationWithAction(OperationCode.Get, 1, OpFlags.UseOldConn | OpFlags.LocalOp, 4), // UPDATE and test with GET for no updates new OperationWithAction(OperationCode.Put, 2, OpFlags.UseOldConn | OpFlags.UseNewVal, 4), new OperationWithAction(OperationCode.Get, 1, OpFlags.UseOldConn | OpFlags.LocalOp, 4), OperationWithAction.OpBlockEnd, // UPDATE and test with GET new OperationWithAction(OperationCode.Put), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.LocalOp, 4), // UPDATE and test with GET for no updates new OperationWithAction(OperationCode.Put, 1, OpFlags.UseOldConn | OpFlags.UseNewVal, 4), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.LocalOp, 4), OperationWithAction.OpBlockEnd, // Do REGION_DESTROY of the sub-region and check with GET new OperationWithAction(OperationCode.Put, 1, OpFlags.UseSubRegion, 8), new OperationWithAction(OperationCode.RegionDestroy, 3, OpFlags.UseSubRegion | OpFlags.CheckNotAuthz, 1), new OperationWithAction(OperationCode.RegionDestroy, 1, OpFlags.UseSubRegion, 1), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseSubRegion | OpFlags.CheckNoKey | OpFlags.CheckException, 8), // Do REGION_DESTROY of the region and check with GET new OperationWithAction(OperationCode.RegionDestroy, 3, OpFlags.CheckNotAuthz, 1), new OperationWithAction(OperationCode.RegionDestroy, 1, OpFlags.None, 1), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.CheckNoKey | OpFlags.CheckException, 8), // Skip failover for region destroy since it shall fail // without restarting the server OperationWithAction.OpBlockNoFailover }; RunOpsWithFailover(allOps, "AllOpsWithFailover", true); } void runThinClientWriterExceptionTest() { CacheHelper.SetupJavaServers(true, CacheXml1); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(true)) { for (int i = 1; i <= 2; ++i) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); //TODO: its not working for multiuser mode.. need to fix later if (cGen.GetClassCode() == CredentialGenerator.ClassCode.PKCS) continue; Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; Util.Log("ThinClientWriterException: Using authinit: " + authInit); Util.Log("ThinClientWriterException: Using authenticator: " + authenticator); Util.Log("ThinClientWriterException: Using accessor: " + accessor); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Start the server. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); // Start client1 with valid CREATE credentials Properties<string, string> createCredentials = authzGen.GetDisallowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 1); javaProps = cGen.JavaProperties; Util.Log("DisallowPuts: For first client PUT credentials: " + createCredentials); m_client1.Call(SecurityTestUtil.CreateClientR0, RegionName, CacheHelper.Locators, authInit, createCredentials); Util.Log("Creating region in client1 , no-ack, no-cache, with listener and writer"); m_client1.Call(CreateRegion, CacheHelper.Locators, true, true, true); m_client1.Call(RegisterAllKeys, new string[] { RegionName }); try { Util.Log("Trying put Operation"); m_client1.Call(DoPut); Util.Log(" Put Operation Successful"); Assert.Fail("Should have got NotAuthorizedException during put"); } catch (NotAuthorizedException) { Util.Log("NotAuthorizedException Caught"); Util.Log("Success"); } catch (Exception other) { Util.Log("Stack trace: {0} ", other.StackTrace); Util.Log("Got exception : {0}", other.Message); } m_client1.Call(CheckAssert); // Do LocalPut m_client1.Call(DoLocalPut); m_client1.Call(Close); CacheHelper.StopJavaServer(1); } } CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } #region Tests [Test] public void TestCQ() { runCQTest(); } [Test] public void TestDurableCQ() { //for all run real cache will be true //logical cache true/false and durable cq true/false combination.... //result..whether events should be there or not runDurableCQTest(false, true, true);//no usercache close as it will close user's durable cq runDurableCQTest(true, false, false); runDurableCQTest(false, true, true); runDurableCQTest(false, false, false); } [Test] public void AllowPutsGets() { runAllowPutsGets(); } [Test] public void DisallowPutsGets() { runDisallowPutsGets(); } [Test] public void AllOpsWithFailover() { runAllOpsWithFailover(); } [Test] public void ThinClientWriterExceptionTest() { runThinClientWriterExceptionTest(); } #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace DalSic { /// <summary> /// Strongly-typed collection for the PnTipoDePrestacion class. /// </summary> [Serializable] public partial class PnTipoDePrestacionCollection : ActiveList<PnTipoDePrestacion, PnTipoDePrestacionCollection> { public PnTipoDePrestacionCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnTipoDePrestacionCollection</returns> public PnTipoDePrestacionCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnTipoDePrestacion o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_TipoDePrestacion table. /// </summary> [Serializable] public partial class PnTipoDePrestacion : ActiveRecord<PnTipoDePrestacion>, IActiveRecord { #region .ctors and Default Settings public PnTipoDePrestacion() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnTipoDePrestacion(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnTipoDePrestacion(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnTipoDePrestacion(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_TipoDePrestacion", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdTipoDePrestacion = new TableSchema.TableColumn(schema); colvarIdTipoDePrestacion.ColumnName = "idTipoDePrestacion"; colvarIdTipoDePrestacion.DataType = DbType.Int32; colvarIdTipoDePrestacion.MaxLength = 0; colvarIdTipoDePrestacion.AutoIncrement = true; colvarIdTipoDePrestacion.IsNullable = false; colvarIdTipoDePrestacion.IsPrimaryKey = true; colvarIdTipoDePrestacion.IsForeignKey = false; colvarIdTipoDePrestacion.IsReadOnly = false; colvarIdTipoDePrestacion.DefaultSetting = @""; colvarIdTipoDePrestacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTipoDePrestacion); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = 100; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = true; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); TableSchema.TableColumn colvarIdNomencladorDetalle = new TableSchema.TableColumn(schema); colvarIdNomencladorDetalle.ColumnName = "idNomencladorDetalle"; colvarIdNomencladorDetalle.DataType = DbType.Int32; colvarIdNomencladorDetalle.MaxLength = 0; colvarIdNomencladorDetalle.AutoIncrement = false; colvarIdNomencladorDetalle.IsNullable = true; colvarIdNomencladorDetalle.IsPrimaryKey = false; colvarIdNomencladorDetalle.IsForeignKey = true; colvarIdNomencladorDetalle.IsReadOnly = false; colvarIdNomencladorDetalle.DefaultSetting = @""; colvarIdNomencladorDetalle.ForeignKeyTableName = "PN_nomenclador_detalle"; schema.Columns.Add(colvarIdNomencladorDetalle); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_TipoDePrestacion",schema); } } #endregion #region Props [XmlAttribute("IdTipoDePrestacion")] [Bindable(true)] public int IdTipoDePrestacion { get { return GetColumnValue<int>(Columns.IdTipoDePrestacion); } set { SetColumnValue(Columns.IdTipoDePrestacion, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } [XmlAttribute("IdNomencladorDetalle")] [Bindable(true)] public int? IdNomencladorDetalle { get { return GetColumnValue<int?>(Columns.IdNomencladorDetalle); } set { SetColumnValue(Columns.IdNomencladorDetalle, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.PnFacturaCollection colPnFacturaRecords; public DalSic.PnFacturaCollection PnFacturaRecords { get { if(colPnFacturaRecords == null) { colPnFacturaRecords = new DalSic.PnFacturaCollection().Where(PnFactura.Columns.IdTipoDePrestacion, IdTipoDePrestacion).Load(); colPnFacturaRecords.ListChanged += new ListChangedEventHandler(colPnFacturaRecords_ListChanged); } return colPnFacturaRecords; } set { colPnFacturaRecords = value; colPnFacturaRecords.ListChanged += new ListChangedEventHandler(colPnFacturaRecords_ListChanged); } } void colPnFacturaRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnFacturaRecords[e.NewIndex].IdTipoDePrestacion = IdTipoDePrestacion; } } private DalSic.PnComprobanteCollection colPnComprobanteRecords; public DalSic.PnComprobanteCollection PnComprobanteRecords { get { if(colPnComprobanteRecords == null) { colPnComprobanteRecords = new DalSic.PnComprobanteCollection().Where(PnComprobante.Columns.IdTipoDePrestacion, IdTipoDePrestacion).Load(); colPnComprobanteRecords.ListChanged += new ListChangedEventHandler(colPnComprobanteRecords_ListChanged); } return colPnComprobanteRecords; } set { colPnComprobanteRecords = value; colPnComprobanteRecords.ListChanged += new ListChangedEventHandler(colPnComprobanteRecords_ListChanged); } } void colPnComprobanteRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnComprobanteRecords[e.NewIndex].IdTipoDePrestacion = IdTipoDePrestacion; } } #endregion #region ForeignKey Properties /// <summary> /// Returns a PnNomencladorDetalle ActiveRecord object related to this PnTipoDePrestacion /// /// </summary> public DalSic.PnNomencladorDetalle PnNomencladorDetalle { get { return DalSic.PnNomencladorDetalle.FetchByID(this.IdNomencladorDetalle); } set { SetColumnValue("idNomencladorDetalle", value.IdNomencladorDetalle); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varDescripcion,int? varIdNomencladorDetalle) { PnTipoDePrestacion item = new PnTipoDePrestacion(); item.Descripcion = varDescripcion; item.IdNomencladorDetalle = varIdNomencladorDetalle; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdTipoDePrestacion,string varDescripcion,int? varIdNomencladorDetalle) { PnTipoDePrestacion item = new PnTipoDePrestacion(); item.IdTipoDePrestacion = varIdTipoDePrestacion; item.Descripcion = varDescripcion; item.IdNomencladorDetalle = varIdNomencladorDetalle; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdTipoDePrestacionColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdNomencladorDetalleColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdTipoDePrestacion = @"idTipoDePrestacion"; public static string Descripcion = @"descripcion"; public static string IdNomencladorDetalle = @"idNomencladorDetalle"; } #endregion #region Update PK Collections public void SetPKValues() { if (colPnFacturaRecords != null) { foreach (DalSic.PnFactura item in colPnFacturaRecords) { if (item.IdTipoDePrestacion == null ||item.IdTipoDePrestacion != IdTipoDePrestacion) { item.IdTipoDePrestacion = IdTipoDePrestacion; } } } if (colPnComprobanteRecords != null) { foreach (DalSic.PnComprobante item in colPnComprobanteRecords) { if (item.IdTipoDePrestacion == null ||item.IdTipoDePrestacion != IdTipoDePrestacion) { item.IdTipoDePrestacion = IdTipoDePrestacion; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colPnFacturaRecords != null) { colPnFacturaRecords.SaveAll(); } if (colPnComprobanteRecords != null) { colPnComprobanteRecords.SaveAll(); } } #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.Diagnostics; using System.IO; using System.Runtime.InteropServices; using Xunit; using Xunit.NetCore.Extensions; public class WindowAndCursorProps : RemoteExecutorTestBase { [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void BufferSize_SettingNotSupported() { Assert.Throws<PlatformNotSupportedException>(() => Console.BufferWidth = 1); Assert.Throws<PlatformNotSupportedException>(() => Console.BufferHeight = 1); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void BufferSize_GettingSameAsWindowSize() { Assert.Throws<PlatformNotSupportedException>(() => Console.BufferWidth = 1); Assert.Throws<PlatformNotSupportedException>(() => Console.BufferHeight = 1); Assert.Equal(Console.WindowWidth, Console.BufferWidth); Assert.Equal(Console.WindowHeight, Console.BufferHeight); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows public static void WindowWidth_WindowHeight_InvalidSize() { if (Console.IsOutputRedirected) { Assert.Throws<IOException>(() => Console.WindowWidth = 0); Assert.Throws<IOException>(() => Console.WindowHeight = 0); } else { AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.WindowWidth = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.WindowHeight = 0); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void WindowWidth() { Assert.Throws<PlatformNotSupportedException>(() => Console.WindowWidth = 100); // Validate that Console.WindowWidth returns some value in a non-redirected o/p. Helpers.RunInNonRedirectedOutput((data) => Console.WriteLine(Console.WindowWidth)); Helpers.RunInRedirectedOutput((data) => Console.WriteLine(Console.WindowWidth)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void WindowHeight() { Assert.Throws<PlatformNotSupportedException>(() => Console.WindowHeight = 100); // Validate that Console.WindowHeight returns some value in a non-redirected o/p. Helpers.RunInNonRedirectedOutput((data) => Console.WriteLine(Console.WindowHeight)); Helpers.RunInRedirectedOutput((data) => Console.WriteLine(Console.WindowHeight)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void WindowLeftTop_AnyUnix() { Assert.Equal(0, Console.WindowLeft); Assert.Equal(0, Console.WindowTop); Assert.Throws<PlatformNotSupportedException>(() => Console.WindowLeft = 0); Assert.Throws<PlatformNotSupportedException>(() => Console.WindowTop = 0); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows public static void WindowLeftTop_Windows() { if (Console.IsOutputRedirected) { Assert.Throws<IOException>(() => Console.WindowLeft); Assert.Throws<IOException>(() => Console.WindowTop); } else { Console.WriteLine(Console.WindowLeft); Console.WriteLine(Console.WindowTop); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] //CI system makes it difficult to run things in a non-redirected environments. public static void NonRedirectedCursorVisible() { if (!Console.IsOutputRedirected) { // Validate that Console.CursorVisible adds something to the stream when in a non-redirected environment. Helpers.RunInNonRedirectedOutput((data) => { Console.CursorVisible = false; Assert.True(data.ToArray().Length > 0); }); Helpers.RunInNonRedirectedOutput((data) => { Console.CursorVisible = true; Assert.True(data.ToArray().Length > 0); }); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void CursorVisible() { Assert.Throws<PlatformNotSupportedException>(() => { bool unused = Console.CursorVisible; }); // Validate that the Console.CursorVisible does nothing in a redirected stream. Helpers.RunInRedirectedOutput((data) => { Console.CursorVisible = false; Assert.Equal(0, data.ToArray().Length); }); Helpers.RunInRedirectedOutput((data) => { Console.CursorVisible = true; Assert.Equal(0, data.ToArray().Length); }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void Title_GetSet_Unix() { Assert.Throws<PlatformNotSupportedException>(() => Console.Title); RemoteInvoke(() => { Console.Title = "Title set by unit test"; return SuccessExitCode; }).Dispose(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, the stream cannot be opened: there is no Console public static void Title_Get_Windows() { Assert.NotNull(Console.Title); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // Nano currently ignores set title [InlineData(0)] [InlineData(1)] [InlineData(255)] [InlineData(256)] [InlineData(1024)] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, the stream cannot be opened: there is no Console public static void Title_Set_Windows(int lengthOfTitle) { // Try to set the title to some other value. RemoteInvoke(lengthOfTitleString => { string newTitle = new string('a', int.Parse(lengthOfTitleString)); Console.Title = newTitle; if (newTitle.Length > 513 && PlatformDetection.IsWindows10Version1703OrGreater) { // RS2 has a bug when getting the window title when the title length is longer than 513 character Assert.Throws<IOException>(() => Console.Title); } else { Assert.Equal(newTitle, Console.Title); } return SuccessExitCode; }, lengthOfTitle.ToString()).Dispose(); } [SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)] // In appcontainer, the stream cannot be opened: there is no Console public static void Title_Get_Windows_Uap() { Assert.Throws<IOException>(() => Console.Title); } [SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)] // In appcontainer, the stream cannot be opened: there is no Console public static void Title_Set_Windows_Uap(int lengthOfTitle) { Assert.Throws<IOException>(() => Console.Title = "x"); } [Fact] public static void Title_Set_Windows_Null_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => Console.Title = null); } [Fact] public static void Title_Set_Windows_GreaterThan24500Chars_ThrowsArgumentOutOfRangeException() { string newTitle = new string('a', 24501); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => Console.Title = newTitle); } [Fact] [OuterLoop] // makes noise, not very inner-loop friendly public static void Beep() { // Nothing to verify; just run the code. Console.Beep(); } [Fact] [OuterLoop] // makes noise, not very inner-loop friendly [PlatformSpecific(TestPlatforms.Windows)] public static void BeepWithFrequency() { // Nothing to verify; just run the code. Console.Beep(800, 200); } [Theory] [PlatformSpecific(TestPlatforms.Windows)] [InlineData(36)] [InlineData(32768)] public void BeepWithFrequency_InvalidFrequency_ThrowsArgumentOutOfRangeException(int frequency) { AssertExtensions.Throws<ArgumentOutOfRangeException>("frequency", () => Console.Beep(frequency, 200)); } [Theory] [PlatformSpecific(TestPlatforms.Windows)] [InlineData(0)] [InlineData(-1)] public void BeepWithFrequency_InvalidDuration_ThrowsArgumentOutOfRangeException(int duration) { AssertExtensions.Throws<ArgumentOutOfRangeException>("duration", () => Console.Beep(800, duration)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void BeepWithFrequency_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Console.Beep(800, 200)); } [Fact] [OuterLoop] // clears the screen, not very inner-loop friendly public static void Clear() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (!Console.IsInputRedirected && !Console.IsOutputRedirected)) { // Nothing to verify; just run the code. Console.Clear(); } } [Fact] public static void SetCursorPosition() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (!Console.IsInputRedirected && !Console.IsOutputRedirected)) { int origLeft = Console.CursorLeft; int origTop = Console.CursorTop; // Nothing to verify; just run the code. // On windows, we might end of throwing IOException, since the handles are redirected. Console.SetCursorPosition(0, 0); Console.SetCursorPosition(1, 2); Console.SetCursorPosition(origLeft, origTop); } } [Theory] [InlineData(-1)] [InlineData(short.MaxValue + 1)] public void SetCursorPosition_InvalidPosition_ThrowsArgumentOutOfRangeException(int value) { AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetCursorPosition(value, 100)); AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetCursorPosition(100, value)); } [Fact] public static void GetCursorPosition() { if (!Console.IsInputRedirected && !Console.IsOutputRedirected) { int origLeft = Console.CursorLeft, origTop = Console.CursorTop; Console.SetCursorPosition(10, 12); Assert.Equal(10, Console.CursorLeft); Assert.Equal(12, Console.CursorTop); Console.SetCursorPosition(origLeft, origTop); Assert.Equal(origLeft, Console.CursorLeft); Assert.Equal(origTop, Console.CursorTop); } else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(0, Console.CursorLeft); Assert.Equal(0, Console.CursorTop); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void CursorSize_SetGet_ReturnsExpected() { if (!Console.IsInputRedirected && !Console.IsOutputRedirected) { int orig = Console.CursorSize; try { Console.CursorSize = 50; Assert.Equal(50, Console.CursorSize); } finally { Console.CursorSize = orig; } } } [Theory] [InlineData(0)] [InlineData(101)] [PlatformSpecific(TestPlatforms.Windows)] public void CursorSize_SetInvalidValue_ThrowsArgumentOutOfRangeException(int value) { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => Console.CursorSize = value); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void CursorSize_SetUnix_ThrowsPlatformNotSupportedException() { Assert.Equal(100, Console.CursorSize); Assert.Throws<PlatformNotSupportedException>(() => Console.CursorSize = 1); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void SetWindowPosition_GetWindowPosition_ReturnsExpected() { if (!Console.IsInputRedirected && !Console.IsOutputRedirected) { AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(-1, Console.WindowTop)); AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetWindowPosition(Console.WindowLeft, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(Console.BufferWidth - Console.WindowWidth + 2, Console.WindowTop)); AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetWindowPosition(Console.WindowHeight, Console.BufferHeight - Console.WindowHeight + 2)); int origTop = Console.WindowTop; int origLeft = Console.WindowLeft; try { Console.SetWindowPosition(0, 0); Assert.Equal(0, Console.WindowTop); Assert.Equal(0, Console.WindowLeft); } finally { Console.WindowTop = origTop; Console.WindowLeft = origLeft; } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void SetWindowPosition_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Console.SetWindowPosition(50, 50)); } [PlatformSpecific(TestPlatforms.Windows)] [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public void SetWindowSize_GetWindowSize_ReturnsExpected() { if (!Console.IsInputRedirected && !Console.IsOutputRedirected) { AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(-1, Console.WindowHeight)); AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowHeight, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(short.MaxValue - Console.WindowLeft, Console.WindowHeight)); AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowWidth, short.MaxValue - Console.WindowTop)); AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(Console.LargestWindowWidth + 1, Console.WindowHeight)); AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowWidth, Console.LargestWindowHeight + 1)); int origWidth = Console.WindowWidth; int origHeight = Console.WindowHeight; try { Console.SetWindowSize(10, 10); Assert.Equal(10, Console.WindowWidth); Assert.Equal(10, Console.WindowHeight); } finally { Console.WindowWidth = origWidth; Console.WindowHeight = origHeight; } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void SetWindowSize_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Console.SetWindowSize(50, 50)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void MoveBufferArea_DefaultChar() { if (!Console.IsInputRedirected && !Console.IsOutputRedirected) { AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceLeft", () => Console.MoveBufferArea(-1, 0, 0, 0, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceTop", () => Console.MoveBufferArea(0, -1, 0, 0, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceWidth", () => Console.MoveBufferArea(0, 0, -1, 0, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceHeight", () => Console.MoveBufferArea(0, 0, 0, -1, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("targetLeft", () => Console.MoveBufferArea(0, 0, 0, 0, -1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("targetTop", () => Console.MoveBufferArea(0, 0, 0, 0, 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceLeft", () => Console.MoveBufferArea(Console.BufferWidth + 1, 0, 0, 0, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("targetLeft", () => Console.MoveBufferArea(0, 0, 0, 0, Console.BufferWidth + 1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceTop", () => Console.MoveBufferArea(0, Console.BufferHeight + 1, 0, 0, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("targetTop", () => Console.MoveBufferArea(0, 0, 0, 0, 0, Console.BufferHeight + 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceHeight", () => Console.MoveBufferArea(0, 1, 0, Console.BufferHeight, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceWidth", () => Console.MoveBufferArea(1, 0, Console.BufferWidth, 0, 0, 0)); // Nothing to verify; just run the code. Console.MoveBufferArea(0, 0, 1, 1, 2, 2); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void MoveBufferArea() { if (!Console.IsInputRedirected && !Console.IsOutputRedirected) { Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(-1, 0, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, -1, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, -1, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, -1, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, -1, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, -1, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(Console.BufferWidth + 1, 0, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, Console.BufferWidth + 1, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, Console.BufferHeight + 1, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, Console.BufferHeight + 1, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 1, 0, Console.BufferHeight, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White)); Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(1, 0, Console.BufferWidth, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White)); // Nothing to verify; just run the code. Console.MoveBufferArea(0, 0, 1, 1, 2, 2, 'a', ConsoleColor.Black, ConsoleColor.White); } } [Theory] [InlineData(ConsoleColor.Black - 1)] [InlineData(ConsoleColor.White + 1)] [PlatformSpecific(TestPlatforms.Windows)] public void MoveBufferArea_InvalidColor_ThrowsException(ConsoleColor color) { AssertExtensions.Throws<ArgumentException>("sourceForeColor", () => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'a', color, ConsoleColor.Black)); AssertExtensions.Throws<ArgumentException>("sourceBackColor", () => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'a', ConsoleColor.Black, color)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void MoveBufferArea_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, 0)); Assert.Throws<PlatformNotSupportedException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'c', ConsoleColor.White, ConsoleColor.Black)); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Microsoft.Win32; using PermissionSet = System.Security.PermissionSet; using System.Security.Permissions; /*=================================JapaneseCalendar========================== ** ** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as ** Gregorian calendar. However, the year value is an offset to the Gregorian ** year based on the era. ** ** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor, ** and the era begins on the day an emperor ascends the throne and continues until his death. ** The era changes at 12:00AM. ** ** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st. ** 1989/1/8 A.D. is also Heisei 1st 1/8. ** ** Any date in the year during which era is changed can be reckoned in either era. For example, ** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year. ** ** Note: ** The DateTime can be represented by the JapaneseCalendar are limited to two factors: ** 1. The min value and max value of DateTime class. ** 2. The available era information. ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1868/09/08 9999/12/31 ** Japanese Meiji 01/01 Heisei 8011/12/31 ============================================================================*/ [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class JapaneseCalendar : Calendar { internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8); [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Japanese calendar. // [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } // // Using a field initializer rather than a static constructor so that the whole class can be lazy // init. static internal volatile EraInfo[] japaneseEraInfo; private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras"; private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive; // // Read our era info // // m_EraInfo must be listed in reverse chronological order. The most recent era // should be the first element. // That is, m_EraInfo[0] contains the most recent era. // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. // internal static EraInfo[] GetEraInfo() { // See if we need to build it if (japaneseEraInfo == null) { // See if we have any eras from the registry japaneseEraInfo = GetErasFromRegistry(); // See if we have to use the built-in eras if (japaneseEraInfo == null) { // We know about some built-in ranges EraInfo[] defaultEraRanges = new EraInfo[4]; defaultEraRanges[0] = new EraInfo( 4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988, "\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear defaultEraRanges[1] = new EraInfo( 3, 1926, 12, 25, 1925, 1, 1989-1925, "\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear defaultEraRanges[2] = new EraInfo( 2, 1912, 7, 30, 1911, 1, 1926-1911, "\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear defaultEraRanges[3] = new EraInfo( 1, 1868, 1, 1, 1867, 1, 1912-1867, "\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear // Remember the ranges we built japaneseEraInfo = defaultEraRanges; } } // return the era we found/made return japaneseEraInfo; } // // GetErasFromRegistry() // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. [System.Security.SecuritySafeCritical] // auto-generated private static EraInfo[] GetErasFromRegistry() { // Look in the registry key and see if we can find any ranges int iFoundEras = 0; EraInfo[] registryEraRanges = null; try { // Need to access registry PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_japaneseErasHivePermissionList)); permSet.Assert(); RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false); // Abort if we didn't find anything if (key == null) return null; // Look up the values in our reg key String[] valueNames = key.GetValueNames(); if (valueNames != null && valueNames.Length > 0) { registryEraRanges = new EraInfo[valueNames.Length]; // Loop through the registry and read in all the values for (int i = 0; i < valueNames.Length; i++) { // See if the era is a valid date EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString()); // continue if not valid if (era == null) continue; // Remember we found one. registryEraRanges[iFoundEras] = era; iFoundEras++; } } } catch (System.Security.SecurityException) { // If we weren't allowed to read, then just ignore the error return null; } catch (System.IO.IOException) { // If key is being deleted just ignore the error return null; } catch (System.UnauthorizedAccessException) { // Registry access rights permissions, just ignore the error return null; } // // If we didn't have valid eras, then fail // should have at least 4 eras // if (iFoundEras < 4) return null; // // Now we have eras, clean them up. // // Clean up array length Array.Resize(ref registryEraRanges, iFoundEras); // Sort them Array.Sort(registryEraRanges, CompareEraRanges); // Clean up era information for (int i = 0; i < registryEraRanges.Length; i++) { // eras count backwards from length to 1 (and are 1 based indexes into string arrays) registryEraRanges[i].era = registryEraRanges.Length - i; // update max era year if (i == 0) { // First range is 'til the end of the calendar registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset; } else { // Rest are until the next era (remember most recent era is first in array) registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset; } } // Return our ranges return registryEraRanges; } // // Compare two era ranges, eg just the ticks // Remember the era array is supposed to be in reverse chronological order // private static int CompareEraRanges(EraInfo a, EraInfo b) { return b.ticks.CompareTo(a.ticks); } // // GetEraFromValue // // Parse the registry value name/data pair into an era // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. private static EraInfo GetEraFromValue(String value, String data) { // Need inputs if (value == null || data == null) return null; // // Get Date // // Need exactly 10 characters in name for date // yyyy.mm.dd although the . can be any character if (value.Length != 10) return null; int year; int month; int day; if (!Number.TryParseInt32(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) || !Number.TryParseInt32(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) || !Number.TryParseInt32(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day)) { // Couldn't convert integer, fail return null; } // // Get Strings // // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups) String[] names = data.Split(new char[] {'_'}); // Should have exactly 4 parts // 0 - Era Name // 1 - Abbreviated Era Name // 2 - English Era Name // 3 - Abbreviated English Era Name if (names.Length != 4) return null; // Each part should have data in it if (names[0].Length == 0 || names[1].Length == 0 || names[2].Length == 0 || names[3].Length == 0) return null; // // Now we have an era we can build // Note that the era # and max era year need cleaned up after sorting // Don't use the full English Era Name (names[2]) // return new EraInfo( 0, year, month, day, year - 1, 1, 0, names[0], names[1], names[3]); } internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new JapaneseCalendar(); } return (s_defaultInstance); } public JapaneseCalendar() { try { new CultureInfo("ja-JP"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().FullName, e); } helper = new GregorianCalendarHelper(this, GetEraInfo()); } internal override int ID { get { return (CAL_JAPAN); } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } /*=================================GetDaysInMonth========================== **Action: Returns the number of days in the month given by the year and month arguments. **Returns: The number of days in the given month. **Arguments: ** year The year in Japanese calendar. ** month The month ** era The Japanese era value. **Exceptions ** ArgumentException If month is less than 1 or greater * than 12. ============================================================================*/ public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [System.Runtime.InteropServices.ComVisible(false)] public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } /*=================================GetEra========================== **Action: Get the era value of the specified time. **Returns: The era value for the specified time. **Arguments: ** time the specified date time. **Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges. ============================================================================*/ public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } // For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, helper.MaxYear)); } return (year); } public override int[] Eras { get { return (helper.Eras); } } // // Return the various era strings // Note: The arrays are backwards of the eras // internal static String[] EraNames() { EraInfo[] eras = GetEraInfo(); String[] eraNames = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. eraNames[i] = eras[eras.Length - i - 1].eraName; } return eraNames; } internal static String[] AbbrevEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasAbbrev = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName; } return erasAbbrev; } internal static String[] EnglishEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasEnglish = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasEnglish[i] = eras[eras.Length - i - 1].englishEraName; } return erasEnglish; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; internal override bool IsValidYear(int year, int era) { return helper.IsValidYear(year, era); } public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 99, helper.MaxYear)); } twoDigitYearMax = value; } } } }
#region Copyright // // This framework is based on log4j see http://jakarta.apache.org/log4j // Copyright (C) The Apache Software Foundation. All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.txt file. // #endregion using System; using System.Text; using log4net.helpers; namespace log4net.ObjectRenderer { /// <summary> /// The default Renderer renders objects by calling their <see cref="Object.ToString"/> method. /// </summary> /// <remarks> /// <para>The default renderer supports rendering objects to strings as follows:</para> /// /// <list type="table"> /// <listheader> /// <term>Value</term> /// <description>Rendered String</description> /// </listheader> /// <item> /// <term><c>null</c></term> /// <description><para>"(null)"</para></description> /// </item> /// <item> /// <term><see cref="Array"/></term> /// <description> /// <para>For a one dimensional array this is the /// array type name, an open brace, followed by a comma /// separated list of the elements (using the appropriate /// renderer), followed by a close brace. For example: /// <c>int[] {1, 2, 3}</c>.</para> /// <para>If the array is not one dimensional the /// <c>Array.ToString()</c> is returned.</para> /// </description> /// </item> /// <item> /// <term><see cref="Exception"/></term> /// <description> /// <para>Renders the exception type, message /// and stack trace. Any nested exception is also rendered.</para> /// </description> /// </item> /// <item> /// <term>other</term> /// <description> /// <para><c>Object.ToString()</c></para> /// </description> /// </item> /// </list> /// /// <para>The <see cref="DefaultRenderer"/> serves as a good base class /// for renderers that need to provide special handling of exception /// types. The <see cref="RenderException"/> method is used to render /// the exception and its nested exceptions, however the <see cref="RenderExceptionMessage"/> /// method is called just to render the exceptions message. This method /// can be overridden is a subclass to provide additional information /// for some exception types. See <see cref="RenderException"/> for /// more information.</para> /// </remarks> public class DefaultRenderer : IObjectRenderer { private static readonly string NewLine = SystemInfo.NewLine; #region Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// Default constructor /// </remarks> public DefaultRenderer() { } #endregion #region Implementation of IObjectRenderer /// <summary> /// Render the object <paramref name="obj"/> to a string /// </summary> /// <param name="rendererMap">The map used to lookup renderers</param> /// <param name="obj">The object to render</param> /// <returns>the object rendered as a string</returns> /// <remarks> /// <para>Render the object <paramref name="obj"/> to a /// string.</para> /// /// <para>The <paramref name="rendererMap"/> parameter is /// provided to lookup and render other objects. This is /// very useful where <paramref name="obj"/> contains /// nested objects of unknown type. The <see cref="RendererMap.FindAndRender"/> /// method can be used to render these objects.</para> /// /// <para>The default renderer supports rendering objects to strings as follows:</para> /// /// <list type="table"> /// <listheader> /// <term>Value</term> /// <description>Rendered String</description> /// </listheader> /// <item> /// <term><c>null</c></term> /// <description> /// <para>"(null)"</para> /// </description> /// </item> /// <item> /// <term><see cref="Array"/></term> /// <description> /// <para>For a one dimensional array this is the /// array type name, an open brace, followed by a comma /// separated list of the elements (using the appropriate /// renderer), followed by a close brace. For example: /// <c>int[] {1, 2, 3}</c>.</para> /// <para>If the array is not one dimensional the /// <c>Array.ToString()</c> is returned.</para> /// /// <para>The <see cref="RenderArray"/> method is called /// to do the actual array rendering. This method can be /// overridden in a subclass to provide different array /// rendering.</para> /// </description> /// </item> /// <item> /// <term><see cref="Exception"/></term> /// <description> /// <para>Renders the exception type, message /// and stack trace. Any nested exception is also rendered.</para> /// /// <para>The <see cref="RenderException"/> method is called /// to do the actual exception rendering. This method can be /// overridden in a subclass to provide different exception /// rendering.</para> /// </description> /// </item> /// <item> /// <term>other</term> /// <description> /// <para><c>Object.ToString()</c></para> /// </description> /// </item> /// </list> /// </remarks> virtual public string DoRender(RendererMap rendererMap, object obj) { if (rendererMap == null) { throw new ArgumentNullException("rendererMap"); } if (obj == null) { return "(null)"; } if (obj is Array) { return RenderArray(rendererMap, (Array)obj); } else if (obj is Exception) { return RenderException(rendererMap, (Exception)obj); } else { return obj.ToString(); } } #endregion /// <summary> /// Render the array argument into a string /// </summary> /// <param name="rendererMap">The map used to lookup renderers</param> /// <param name="array">the array to render</param> /// <returns>the string representation of the array</returns> /// <remarks> /// <para>For a one dimensional array this is the /// array type name, an open brace, followed by a comma /// separated list of the elements (using the appropriate /// renderer), followed by a close brace. For example: /// <c>int[] {1, 2, 3}</c>.</para> /// <para>If the array is not one dimensional the /// <c>Array.ToString()</c> is returned.</para> /// </remarks> virtual protected string RenderArray(RendererMap rendererMap, Array array) { if (array.Rank != 1) { return array.ToString(); } else { StringBuilder buffer = new StringBuilder(array.GetType().Name + " {"); int len = array.Length; if (len > 0) { buffer.Append(rendererMap.FindAndRender(array.GetValue(0))); for(int i=1; i<len; i++) { buffer.Append(", ").Append(rendererMap.FindAndRender(array.GetValue(i))); } } return buffer.Append("}").ToString(); } } /// <summary> /// Render the exception into a string /// </summary> /// <param name="rendererMap">The map used to lookup renderers</param> /// <param name="ex">the exception to render</param> /// <returns>the string representation of the exception</returns> /// <remarks> /// <para>Renders the exception type, message, and stack trace. Any nested /// exceptions are also rendered.</para> /// /// <para>The <see cref="RenderExceptionMessage(RendererMap,Exception)"/> /// method is called to render the Exception's message into a string. This method /// can be overridden to change the behaviour when rendering /// exceptions. To change or extend only the message that is /// displayed override the <see cref="RenderExceptionMessage(RendererMap,Exception)"/> /// method instead.</para> /// </remarks> virtual protected string RenderException(RendererMap rendererMap, Exception ex) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("Exception: ") .Append(ex.GetType().FullName) .Append(NewLine) .Append("Message: ") .Append(RenderExceptionMessage(rendererMap, ex)) .Append(NewLine); #if !NETCF if (ex.Source != null && ex.Source.Length > 0) { sb.Append("Source: ").Append(ex.Source).Append(NewLine); } if (ex.StackTrace != null && ex.StackTrace.Length > 0) { sb.Append(ex.StackTrace).Append(NewLine); } #endif if (ex.InnerException != null) { sb.Append(NewLine) .Append("Nested Exception") .Append(NewLine) .Append(NewLine) .Append(RenderException(rendererMap, ex.InnerException)) .Append(NewLine); } return sb.ToString(); } /// <summary> /// Render the exception message into a string /// </summary> /// <param name="rendererMap">The map used to lookup renderers</param> /// <param name="ex">the exception to get the message from and render</param> /// <returns>the string representation of the exception message</returns> /// <remarks> /// <para>This method is called to render the exception's message into /// a string. This method should be overridden to extend the information /// that is rendered for a specific exception.</para> /// /// <para>See <see cref="RenderException"/> for more information.</para> /// </remarks> virtual protected string RenderExceptionMessage(RendererMap rendererMap, Exception ex) { return ex.Message; } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.Admin.DS { public class Sys_Role_ControlGroupDS { public Sys_Role_ControlGroupDS() { } private const string THIS = "PCSComUtils.Admin.DS.Sys_Role_ControlGroupDS"; /// <summary> /// This method uses to add data to Sys_Role_ControlGroup /// </summary> /// <Inputs> /// Sys_Role_ControlGroupVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { Sys_Role_ControlGroupVO objObject = (Sys_Role_ControlGroupVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO Sys_Role_ControlGroup(" + Sys_Role_ControlGroupTable.ROLEID_FLD + "," + Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD + ")" + "VALUES(?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_Role_ControlGroupTable.ROLEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_Role_ControlGroupTable.ROLEID_FLD].Value = objObject.RoleID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD].Value = objObject.ControlGroupID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_Role_ControlGroup /// </summary> /// <Inputs> /// Sys_Role_ControlGroupVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + Sys_Role_ControlGroupTable.TABLE_NAME + " WHERE " + "Role_ControlGroupID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_Role_ControlGroup /// </summary> /// <Inputs> /// Sys_Role_ControlGroupVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_Role_ControlGroupTable.ROLE_CONTROLGROUPID_FLD + "," + Sys_Role_ControlGroupTable.ROLEID_FLD + "," + Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD + " FROM " + Sys_Role_ControlGroupTable.TABLE_NAME +" WHERE " + Sys_Role_ControlGroupTable.ROLE_CONTROLGROUPID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); Sys_Role_ControlGroupVO objObject = new Sys_Role_ControlGroupVO(); while (odrPCS.Read()) { objObject.Role_ControlGroupID = int.Parse(odrPCS[Sys_Role_ControlGroupTable.ROLE_CONTROLGROUPID_FLD].ToString().Trim()); objObject.RoleID = int.Parse(odrPCS[Sys_Role_ControlGroupTable.ROLEID_FLD].ToString().Trim()); objObject.ControlGroupID = int.Parse(odrPCS[Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD].ToString().Trim()); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_Role_ControlGroup /// </summary> /// <Inputs> /// Sys_Role_ControlGroupVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; Sys_Role_ControlGroupVO objObject = (Sys_Role_ControlGroupVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE Sys_Role_ControlGroup SET " + Sys_Role_ControlGroupTable.ROLEID_FLD + "= ?" + "," + Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD + "= ?" +" WHERE " + Sys_Role_ControlGroupTable.ROLE_CONTROLGROUPID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_Role_ControlGroupTable.ROLEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_Role_ControlGroupTable.ROLEID_FLD].Value = objObject.RoleID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD].Value = objObject.ControlGroupID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_Role_ControlGroupTable.ROLE_CONTROLGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_Role_ControlGroupTable.ROLE_CONTROLGROUPID_FLD].Value = objObject.Role_ControlGroupID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_Role_ControlGroup /// </summary> /// <Inputs> /// Sys_Role_ControlGroupVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_Role_ControlGroupTable.ROLE_CONTROLGROUPID_FLD + "," + Sys_Role_ControlGroupTable.ROLEID_FLD + "," + Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD + " FROM " + Sys_Role_ControlGroupTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,Sys_Role_ControlGroupTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_Role_ControlGroup /// </summary> /// <Inputs> /// Sys_Role_ControlGroupVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public void UpdateDataSet(DataSet pdstData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + Sys_Role_ControlGroupTable.ROLE_CONTROLGROUPID_FLD + "," + Sys_Role_ControlGroupTable.ROLEID_FLD + "," + Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD + " FROM " + Sys_Role_ControlGroupTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pdstData.EnforceConstraints = false; odadPCS.Update(pdstData,Sys_Role_ControlGroupTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from Sys_HiddenControls_Role /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, April 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public string ListVisibleControlForRole(int pintRoleID) { const string METHOD_NAME = THIS + ".ListHiddenControlForRole()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "Declare @S varchar(4000) Set @S = '' Select @S = @S + convert(varchar, ControlGroupID) + ';' From Sys_Role_ControlGroup Where RoleID " + " = " + pintRoleID.ToString() + " Select @S"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); return ocmdPCS.ExecuteScalar().ToString(); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from Sys_HiddenControls_Role /// </Description> /// <Inputs> /// RoleID, HiddenControlsID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// TuanDM /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintRoleID, int pintControlGroupID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = "DELETE " + Sys_Role_ControlGroupTable.TABLE_NAME + " WHERE " + "ControlGroupID = " + pintControlGroupID.ToString() + " and RoleID = " + pintRoleID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.AzureUtils.Utilities; using Orleans.Configuration; namespace Orleans.Runtime.ReminderService { public class AzureBasedReminderTable : IReminderTable { private readonly IGrainReferenceConverter grainReferenceConverter; private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; private readonly ClusterOptions clusterOptions; private readonly AzureTableReminderStorageOptions storageOptions; private RemindersTableManager remTableManager; public AzureBasedReminderTable( IGrainReferenceConverter grainReferenceConverter, ILoggerFactory loggerFactory, IOptions<ClusterOptions> clusterOptions, IOptions<AzureTableReminderStorageOptions> storageOptions) { this.grainReferenceConverter = grainReferenceConverter; this.logger = loggerFactory.CreateLogger<AzureBasedReminderTable>(); this.loggerFactory = loggerFactory; this.clusterOptions = clusterOptions.Value; this.storageOptions = storageOptions.Value; } public async Task Init() { this.remTableManager = await RemindersTableManager.GetManager( this.clusterOptions.ServiceId, this.clusterOptions.ClusterId, this.storageOptions.ConnectionString, this.storageOptions.TableName, this.loggerFactory); } private ReminderTableData ConvertFromTableEntryList(IEnumerable<Tuple<ReminderTableEntry, string>> entries) { var remEntries = new List<ReminderEntry>(); foreach (var entry in entries) { try { ReminderEntry converted = ConvertFromTableEntry(entry.Item1, entry.Item2); remEntries.Add(converted); } catch (Exception) { // Ignoring... } } return new ReminderTableData(remEntries); } private ReminderEntry ConvertFromTableEntry(ReminderTableEntry tableEntry, string eTag) { try { return new ReminderEntry { GrainRef = this.grainReferenceConverter.GetGrainFromKeyString(tableEntry.GrainReference), ReminderName = tableEntry.ReminderName, StartAt = LogFormatter.ParseDate(tableEntry.StartAt), Period = TimeSpan.Parse(tableEntry.Period), ETag = eTag, }; } catch (Exception exc) { var error = $"Failed to parse ReminderTableEntry: {tableEntry}. This entry is corrupt, going to ignore it."; this.logger.Error((int)AzureReminderErrorCode.AzureTable_49, error, exc); throw; } finally { string serviceIdStr = this.remTableManager.ServiceId; if (!tableEntry.ServiceId.Equals(serviceIdStr)) { var error = $"Read a reminder entry for wrong Service id. Read {tableEntry}, but my service id is {serviceIdStr}. Going to discard it."; this.logger.Warn((int)AzureReminderErrorCode.AzureTable_ReadWrongReminder, error); throw new OrleansException(error); } } } private static ReminderTableEntry ConvertToTableEntry(ReminderEntry remEntry, string serviceId, string deploymentId) { string partitionKey = ReminderTableEntry.ConstructPartitionKey(serviceId, remEntry.GrainRef); string rowKey = ReminderTableEntry.ConstructRowKey(remEntry.GrainRef, remEntry.ReminderName); var consistentHash = remEntry.GrainRef.GetUniformHashCode(); return new ReminderTableEntry { PartitionKey = partitionKey, RowKey = rowKey, ServiceId = serviceId, DeploymentId = deploymentId, GrainReference = remEntry.GrainRef.ToKeyString(), ReminderName = remEntry.ReminderName, StartAt = LogFormatter.PrintDate(remEntry.StartAt), Period = remEntry.Period.ToString(), GrainRefConsistentHash = string.Format("{0:X8}", consistentHash), ETag = remEntry.ETag, }; } public Task TestOnlyClearTable() { return this.remTableManager.DeleteTableEntries(); } public async Task<ReminderTableData> ReadRows(GrainReference key) { try { var entries = await this.remTableManager.FindReminderEntries(key); ReminderTableData data = ConvertFromTableEntryList(entries); if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("Read for grain {0} Table=" + Environment.NewLine + "{1}", key, data.ToString()); return data; } catch (Exception exc) { this.logger.Warn((int)AzureReminderErrorCode.AzureTable_47, $"Intermediate error reading reminders for grain {key} in table {this.remTableManager.TableName}.", exc); throw; } } public async Task<ReminderTableData> ReadRows(uint begin, uint end) { try { var entries = await this.remTableManager.FindReminderEntries(begin, end); ReminderTableData data = ConvertFromTableEntryList(entries); if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("Read in {0} Table=" + Environment.NewLine + "{1}", RangeFactory.CreateRange(begin, end), data); return data; } catch (Exception exc) { this.logger.Warn((int)AzureReminderErrorCode.AzureTable_40, $"Intermediate error reading reminders in range {RangeFactory.CreateRange(begin, end)} for table {this.remTableManager.TableName}.", exc); throw; } } public async Task<ReminderEntry> ReadRow(GrainReference grainRef, string reminderName) { try { if (this.logger.IsEnabled(LogLevel.Debug)) this.logger.Debug("ReadRow grainRef = {0} reminderName = {1}", grainRef, reminderName); var result = await this.remTableManager.FindReminderEntry(grainRef, reminderName); return result == null ? null : ConvertFromTableEntry(result.Item1, result.Item2); } catch (Exception exc) { this.logger.Warn((int)AzureReminderErrorCode.AzureTable_46, $"Intermediate error reading row with grainId = {grainRef} reminderName = {reminderName} from table {this.remTableManager.TableName}.", exc); throw; } } public async Task<string> UpsertRow(ReminderEntry entry) { try { if (this.logger.IsEnabled(LogLevel.Debug)) this.logger.Debug("UpsertRow entry = {0}", entry.ToString()); ReminderTableEntry remTableEntry = ConvertToTableEntry(entry, this.remTableManager.ServiceId, this.remTableManager.ClusterId); string result = await this.remTableManager.UpsertRow(remTableEntry); if (result == null) { this.logger.Warn((int)AzureReminderErrorCode.AzureTable_45, $"Upsert failed on the reminder table. Will retry. Entry = {entry.ToString()}"); } return result; } catch (Exception exc) { this.logger.Warn((int)AzureReminderErrorCode.AzureTable_42, $"Intermediate error upserting reminder entry {entry.ToString()} to the table {this.remTableManager.TableName}.", exc); throw; } } public async Task<bool> RemoveRow(GrainReference grainRef, string reminderName, string eTag) { var entry = new ReminderTableEntry { PartitionKey = ReminderTableEntry.ConstructPartitionKey(this.remTableManager.ServiceId, grainRef), RowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName), ETag = eTag, }; try { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("RemoveRow entry = {0}", entry.ToString()); bool result = await this.remTableManager.DeleteReminderEntryConditionally(entry, eTag); if (result == false) { this.logger.Warn((int)AzureReminderErrorCode.AzureTable_43, $"Delete failed on the reminder table. Will retry. Entry = {entry}"); } return result; } catch (Exception exc) { this.logger.Warn((int)AzureReminderErrorCode.AzureTable_44, $"Intermediate error when deleting reminder entry {entry} to the table {this.remTableManager.TableName}.", exc); throw; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Management.Automation.Runspaces; namespace System.Management.Automation { /// <summary> /// Class HelpProvider defines the interface to be implemented by help providers. /// /// Help Providers: /// The basic contract for help providers is to provide help based on the /// search target. /// /// The result of help provider invocation can be three things: /// a. Full help info. (in the case of exact-match and single search result) /// b. Short help info. (in the case of multiple search result) /// c. Partial help info. (in the case of some commandlet help info, which /// should be supplemented by provider help info) /// d. Help forwarding info. (in the case of alias, which will change the target /// for alias) /// /// Help providers may need to provide functionality in following two area, /// a. caching and indexing to boost performance /// b. localization /// /// Basic properties of a Help Provider /// 1. Name /// 2. Type /// 3. Assembly /// /// Help Provider Interface /// 1. Initialize: /// 2. ExactMatchHelp: /// 3. SearchHelp: /// 4. ProcessForwardedHelp. /// </summary> internal abstract class HelpProvider { /// <summary> /// Constructor for HelpProvider. /// </summary> internal HelpProvider(HelpSystem helpSystem) { _helpSystem = helpSystem; } private HelpSystem _helpSystem; internal HelpSystem HelpSystem { get { return _helpSystem; } } #region Common Properties /// <summary> /// Name for the help provider. /// </summary> /// <value>Name for the help provider</value> /// <remarks>Derived classes should set this.</remarks> internal abstract string Name { get; } /// <summary> /// Help category for the help provider. /// </summary> /// <value>Help category for the help provider</value> /// <remarks>Derived classes should set this.</remarks> internal abstract HelpCategory HelpCategory { get; } #if V2 /// <summary> /// Assembly that contains the help provider. /// </summary> /// <value>Assembly name</value> virtual internal string AssemblyName { get { return Assembly.GetExecutingAssembly().FullName; } } /// <summary> /// Class that implements the help provider. /// </summary> /// <value>Class name</value> virtual internal string ClassName { get { return this.GetType().FullName; } } /// <summary> /// Get an provider info object based on the basic information in this provider. /// </summary> /// <value>An mshObject that contains the providerInfo</value> internal PSObject ProviderInfo { get { PSObject result = new PSObject(); result.Properties.Add(new PSNoteProperty("Name", this.Name)); result.Properties.Add(new PSNoteProperty("Category", this.HelpCategory.ToString())); result.Properties.Add(new PSNoteProperty("ClassName", this.ClassName)); result.Properties.Add(new PSNoteProperty("AssemblyName", this.AssemblyName)); Collection<string> typeNames = new Collection<string>(); typeNames.Add("HelpProviderInfo"); result.TypeNames = typeNames; return result; } } #endif #endregion #region Help Provider Interface /// <summary> /// Retrieve help info that exactly match the target. /// </summary> /// <param name="helpRequest">Help request object.</param> /// <returns>List of HelpInfo objects retrieved.</returns> internal abstract IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest); /// <summary> /// Search help info that match the target search pattern. /// </summary> /// <param name="helpRequest">Help request object.</param> /// <param name="searchOnlyContent"> /// If true, searches for pattern in the help content. Individual /// provider can decide which content to search in. /// /// If false, searches for pattern in the command names. /// </param> /// <returns>A collection of help info objects.</returns> internal abstract IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent); /// <summary> /// Process a helpinfo forwarded over by another help provider. /// /// HelpProvider can choose to process the helpInfo or not, /// /// 1. If a HelpProvider chooses not to process the helpInfo, it can return null to indicate /// helpInfo is not processed. /// 2. If a HelpProvider indeed processes the helpInfo, it should create a new helpInfo /// object instead of modifying the passed-in helpInfo object. This is very important /// since the helpInfo object passed in is usually stored in cache, which can /// used in later queries. /// </summary> /// <param name="helpInfo">HelpInfo passed over by another HelpProvider.</param> /// <param name="helpRequest">Help request object.</param> /// <returns></returns> internal virtual IEnumerable<HelpInfo> ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { // Win8: 508648. Remove the current provides category for resolving forward help as the current // help provider already process it. helpInfo.ForwardHelpCategory = helpInfo.ForwardHelpCategory ^ this.HelpCategory; yield return helpInfo; } /// <summary> /// Reset help provider. /// /// Normally help provider are reset after a help culture change. /// </summary> internal virtual void Reset() { return; } #endregion #region Utility functions /// <summary> /// Report help file load errors. /// /// Currently three cases are handled, /// /// 1. IOException: not able to read the file /// 2. SecurityException: not authorized to read the file /// 3. XmlException: xml schema error. /// /// This will be called either from search help or exact match help /// to find the error. /// </summary> /// <param name="exception"></param> /// <param name="target"></param> /// <param name="helpFile"></param> internal void ReportHelpFileError(Exception exception, string target, string helpFile) { ErrorRecord errorRecord = new ErrorRecord(exception, "LoadHelpFileForTargetFailed", ErrorCategory.OpenError, null); errorRecord.ErrorDetails = new ErrorDetails(typeof(HelpProvider).Assembly, "HelpErrors", "LoadHelpFileForTargetFailed", target, helpFile, exception.Message); this.HelpSystem.LastErrors.Add(errorRecord); return; } /// <summary> /// Each Shell ( minishell ) will have its own path specified by the /// application base folder, which should be the same as $pshome. /// </summary> /// <returns>String representing base directory of the executing shell.</returns> internal string GetDefaultShellSearchPath() { string shellID = this.HelpSystem.ExecutionContext.ShellID; // Beginning in PowerShell 6.0.0.12, the $pshome is no longer registry specified, we search the application base instead. string returnValue = Utils.GetApplicationBase(shellID); if (returnValue == null) { // use executing assemblies location in case registry entry not found returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName); } return returnValue; } /// <summary> /// Gets the search paths. If the current shell is single-shell based, then the returned /// search path contains all the directories of currently active PSSnapIns. /// </summary> /// <returns>A collection of string representing locations.</returns> internal Collection<string> GetSearchPaths() { Collection<string> searchPaths = this.HelpSystem.GetSearchPaths(); Diagnostics.Assert(searchPaths != null, "HelpSystem returned an null search path"); string defaultShellSearchPath = GetDefaultShellSearchPath(); if (!searchPaths.Contains(defaultShellSearchPath)) { searchPaths.Add(defaultShellSearchPath); } return searchPaths; } #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.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace System.Globalization { internal partial class CultureData { // ICU constants const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name const string ICU_COLLATION_KEYWORD = "@collation="; /// <summary> /// This method uses the sRealName field (which is initialized by the constructor before this is called) to /// initialize the rest of the state of CultureData based on the underlying OS globalization library. /// </summary> [SecuritySafeCritical] private unsafe bool InitCultureData() { Contract.Assert(_sRealName != null); string alternateSortName = string.Empty; string realNameBuffer = _sRealName; // Basic validation if (realNameBuffer.Contains("@")) { return false; // don't allow ICU variants to come in directly } // Replace _ (alternate sort) with @collation= for ICU int index = realNameBuffer.IndexOf('_'); if (index > 0) { if (index >= (realNameBuffer.Length - 1) // must have characters after _ || realNameBuffer.Substring(index + 1).Contains("_")) // only one _ allowed { return false; // fail } alternateSortName = realNameBuffer.Substring(index + 1); realNameBuffer = realNameBuffer.Substring(0, index) + ICU_COLLATION_KEYWORD + alternateSortName; } // Get the locale name from ICU if (!GetLocaleName(realNameBuffer, out _sWindowsName)) { return false; // fail } // Replace the ICU collation keyword with an _ index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal); if (index >= 0) { _sName = _sWindowsName.Substring(0, index) + "_" + alternateSortName; } else { _sName = _sWindowsName; } _sRealName = _sName; _sSpecificCulture = _sRealName; // we don't attempt to find a non-neutral locale if a neutral is passed in (unlike win32) _iLanguage = this.ILANGUAGE; if (_iLanguage == 0) { _iLanguage = LOCALE_CUSTOM_UNSPECIFIED; } _bNeutral = (this.SISO3166CTRYNAME.Length == 0); // Remove the sort from sName unless custom culture if (!_bNeutral) { if (!IsCustomCultureId(_iLanguage)) { _sName = _sWindowsName.Substring(0, index); } } return true; } [SecuritySafeCritical] internal static bool GetLocaleName(string localeName, out string windowsName) { // Get the locale name from ICU StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); if (!Interop.GlobalizationInterop.GetLocaleName(localeName, sb, sb.Capacity)) { StringBuilderCache.Release(sb); windowsName = null; return false; // fail } // Success - use the locale name returned which may be different than realNameBuffer (casing) windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls return true; } [SecuritySafeCritical] internal static bool GetDefaultLocaleName(out string windowsName) { // Get the default (system) locale name from ICU StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); if (!Interop.GlobalizationInterop.GetDefaultLocaleName(sb, sb.Capacity)) { StringBuilderCache.Release(sb); windowsName = null; return false; // fail } // Success - use the locale name returned which may be different than realNameBuffer (casing) windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls return true; } private string GetLocaleInfo(LocaleStringData type) { Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already"); return GetLocaleInfo(_sWindowsName, type); } // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the // "windows" name, which can be specific for downlevel (< windows 7) os's. [SecuritySafeCritical] private string GetLocaleInfo(string localeName, LocaleStringData type) { Contract.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null"); switch (type) { case LocaleStringData.NegativeInfinitySymbol: // not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) + GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol); } StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY); bool result = Interop.GlobalizationInterop.GetLocaleInfoString(localeName, (uint)type, sb, sb.Capacity); if (!result) { // Failed, just use empty string StringBuilderCache.Release(sb); Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed"); return String.Empty; } return StringBuilderCache.GetStringAndRelease(sb); } [SecuritySafeCritical] private int GetLocaleInfo(LocaleNumberData type) { Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already"); switch (type) { case LocaleNumberData.CalendarType: // returning 0 will cause the first supported calendar to be returned, which is the preferred calendar return 0; } int value = 0; bool result = Interop.GlobalizationInterop.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value); if (!result) { // Failed, just use 0 Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed"); } return value; } [SecuritySafeCritical] private int[] GetLocaleInfo(LocaleGroupingData type) { Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already"); int primaryGroupingSize = 0; int secondaryGroupingSize = 0; bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize); if (!result) { Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed"); } if (secondaryGroupingSize == 0) { return new int[] { primaryGroupingSize }; } return new int[] { primaryGroupingSize, secondaryGroupingSize }; } private string GetTimeFormatString() { return GetTimeFormatString(false); } [SecuritySafeCritical] private string GetTimeFormatString(bool shortFormat) { Contract.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already"); StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY); bool result = Interop.GlobalizationInterop.GetLocaleTimeFormat(_sWindowsName, shortFormat, sb, sb.Capacity); if (!result) { // Failed, just use empty string StringBuilderCache.Release(sb); Contract.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed"); return String.Empty; } return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb)); } private int GetFirstDayOfWeek() { return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek); } private String[] GetTimeFormats() { string format = GetTimeFormatString(false); return new string[] { format }; } private String[] GetShortTimeFormats() { string format = GetTimeFormatString(true); return new string[] { format }; } private static CultureData GetCultureDataFromRegionName(String regionName) { // no support to lookup by region name, other than the hard-coded list in CultureData return null; } private static string GetLanguageDisplayName(string cultureName) { return new CultureInfo(cultureName).m_cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName); } private static string GetRegionDisplayName(string isoCountryCode) { // use the fallback which is to return NativeName return null; } private static CultureInfo GetUserDefaultCulture() { return CultureInfo.GetUserDefaultCulture(); } private static string ConvertIcuTimeFormatString(string icuFormatString) { StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); bool amPmAdded = false; for (int i = 0; i < icuFormatString.Length; i++) { switch(icuFormatString[i]) { case ':': case '.': case 'H': case 'h': case 'm': case 's': sb.Append(icuFormatString[i]); break; case ' ': case '\u00A0': // Convert nonbreaking spaces into regular spaces sb.Append(' '); break; case 'a': // AM/PM if (!amPmAdded) { amPmAdded = true; sb.Append("tt"); } break; } } return StringBuilderCache.GetStringAndRelease(sb); } } }
// *********************************************************************** // Copyright (c) 2012-2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Common; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework.Api { /// <summary> /// DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite /// containing test fixtures present in the assembly. /// </summary> public class DefaultTestAssemblyBuilder : ITestAssemblyBuilder { static Logger log = InternalTrace.GetLogger(typeof(DefaultTestAssemblyBuilder)); #region Instance Fields /// <summary> /// The default suite builder used by the test assembly builder. /// </summary> ISuiteBuilder _defaultSuiteBuilder; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DefaultTestAssemblyBuilder"/> class. /// </summary> public DefaultTestAssemblyBuilder() { _defaultSuiteBuilder = new DefaultSuiteBuilder(); } #endregion #region Build Methods /// <summary> /// Build a suite of tests from a provided assembly /// </summary> /// <param name="assembly">The assembly from which tests are to be built</param> /// <param name="options">A dictionary of options to use in building the suite</param> /// <returns> /// A TestSuite containing the tests found in the assembly /// </returns> public ITest Build(Assembly assembly, IDictionary<string, object> options) { #if PORTABLE log.Debug("Loading {0}", assembly.FullName); #else log.Debug("Loading {0} in AppDomain {1}", assembly.FullName, AppDomain.CurrentDomain.FriendlyName); #endif #if SILVERLIGHT string assemblyPath = AssemblyHelper.GetAssemblyName(assembly).Name; #elif PORTABLE string assemblyPath = AssemblyHelper.GetAssemblyName(assembly).FullName; #else string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly); #endif return Build(assembly, assemblyPath, options); } /// <summary> /// Build a suite of tests given the filename of an assembly /// </summary> /// <param name="assemblyName">The filename of the assembly from which tests are to be built</param> /// <param name="options">A dictionary of options to use in building the suite</param> /// <returns> /// A TestSuite containing the tests found in the assembly /// </returns> public ITest Build(string assemblyName, IDictionary<string, object> options) { #if PORTABLE log.Debug("Loading {0}", assemblyName); #else log.Debug("Loading {0} in AppDomain {1}", assemblyName, AppDomain.CurrentDomain.FriendlyName); #endif TestSuite testAssembly = null; try { var assembly = AssemblyHelper.Load(assemblyName); testAssembly = Build(assembly, assemblyName, options); } catch (Exception ex) { testAssembly = new TestAssembly(assemblyName); testAssembly.RunState = RunState.NotRunnable; testAssembly.Properties.Set(PropertyNames.SkipReason, ex.Message); } return testAssembly; } private TestSuite Build(Assembly assembly, string assemblyPath, IDictionary<string, object> options) { TestSuite testAssembly = null; try { if (options.ContainsKey(PackageSettings.DefaultTestNamePattern)) TestNameGenerator.DefaultTestNamePattern = options[PackageSettings.DefaultTestNamePattern] as string; if (options.ContainsKey(PackageSettings.TestParameters)) { string parameters = options[PackageSettings.TestParameters] as string; if (!string.IsNullOrEmpty(parameters)) foreach (string param in parameters.Split(new[] { ';' })) { int eq = param.IndexOf("="); if (eq > 0 && eq < param.Length - 1) { var name = param.Substring(0, eq); var val = param.Substring(eq + 1); TestContext.Parameters.Add(name, val); } } } IList fixtureNames = null; if (options.ContainsKey (PackageSettings.LOAD)) fixtureNames = options[PackageSettings.LOAD] as IList; var fixtures = GetFixtures(assembly, fixtureNames); testAssembly = BuildTestAssembly(assembly, assemblyPath, fixtures); } catch (Exception ex) { testAssembly = new TestAssembly(assemblyPath); testAssembly.RunState = RunState.NotRunnable; testAssembly.Properties.Set(PropertyNames.SkipReason, ex.Message); } return testAssembly; } #endregion #region Helper Methods private IList<Test> GetFixtures(Assembly assembly, IList names) { var fixtures = new List<Test>(); log.Debug("Examining assembly for test fixtures"); var testTypes = GetCandidateFixtureTypes(assembly, names); log.Debug("Found {0} classes to examine", testTypes.Count); #if LOAD_TIMING System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); timer.Start(); #endif int testcases = 0; foreach (Type testType in testTypes) { var typeInfo = new TypeWrapper(testType); try { if (_defaultSuiteBuilder.CanBuildFrom(typeInfo)) { Test fixture = _defaultSuiteBuilder.BuildFrom(typeInfo); fixtures.Add(fixture); testcases += fixture.TestCaseCount; } } catch (Exception ex) { log.Error(ex.ToString()); } } #if LOAD_TIMING log.Debug("Found {0} fixtures with {1} test cases in {2} seconds", fixtures.Count, testcases, timer.Elapsed); #else log.Debug("Found {0} fixtures with {1} test cases", fixtures.Count, testcases); #endif return fixtures; } private IList<Type> GetCandidateFixtureTypes(Assembly assembly, IList names) { var types = assembly.GetTypes(); if (names == null || names.Count == 0) return types; var result = new List<Type>(); foreach (string name in names) { Type fixtureType = assembly.GetType(name); if (fixtureType != null) result.Add(fixtureType); else { string prefix = name + "."; foreach (Type type in types) if (type.FullName.StartsWith(prefix)) result.Add(type); } } return result; } private TestSuite BuildTestAssembly(Assembly assembly, string assemblyName, IList<Test> fixtures) { TestSuite testAssembly = new TestAssembly(assembly, assemblyName); if (fixtures.Count == 0) { testAssembly.RunState = RunState.NotRunnable; testAssembly.Properties.Set(PropertyNames.SkipReason, "Has no TestFixtures"); } else { NamespaceTreeBuilder treeBuilder = new NamespaceTreeBuilder(testAssembly); treeBuilder.Add(fixtures); testAssembly = treeBuilder.RootSuite; } testAssembly.ApplyAttributesToTest(assembly); #if !PORTABLE #if !SILVERLIGHT testAssembly.Properties.Set(PropertyNames.ProcessID, System.Diagnostics.Process.GetCurrentProcess().Id); #endif testAssembly.Properties.Set(PropertyNames.AppDomain, AppDomain.CurrentDomain.FriendlyName); #endif // TODO: Make this an option? Add Option to sort assemblies as well? testAssembly.Sort(); return testAssembly; } #endregion } }
// // HyenaSqliteCommand.cs // // Authors: // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Threading; namespace Hyena.Data.Sqlite { public class CommandExecutedArgs : EventArgs { public CommandExecutedArgs (string sql, int ms) { Sql = sql; Ms = ms; } public string Sql; public int Ms; } public class HyenaSqliteCommand { private object result = null; private Exception execution_exception = null; private bool finished = false; private ManualResetEvent finished_event = new ManualResetEvent (true); private string command; private string command_format = null; private string command_formatted = null; private int parameter_count = 0; private object [] current_values; private int ticks; public string Text { get { return command; } } public bool ReaderDisposes { get; set; } internal HyenaCommandType CommandType; public HyenaSqliteCommand (string command) { this.command = command; } public HyenaSqliteCommand (string command, params object [] param_values) { this.command = command; ApplyValues (param_values); } internal void Execute (Connection connection) { if (finished) { throw new Exception ("Command is already set to finished; result needs to be claimed before command can be rerun"); } execution_exception = null; result = null; int execution_ms = 0; string command_text = null; try { command_text = CurrentSqlText; ticks = System.Environment.TickCount; switch (CommandType) { case HyenaCommandType.Reader: using (var reader = connection.Query (command_text)) { result = new ArrayDataReader (reader, command_text); } break; case HyenaCommandType.Scalar: result = connection.Query<object> (command_text); break; case HyenaCommandType.Execute: default: connection.Execute (command_text); result = connection.LastInsertRowId; break; } execution_ms = System.Environment.TickCount - ticks; if (log_all) { Log.DebugFormat ("Executed in {0}ms {1}", execution_ms, command_text); } else if (Log.Debugging && execution_ms > 500) { Log.WarningFormat ("Executed in {0}ms {1}", execution_ms, command_text); } } catch (Exception e) { Log.DebugFormat ("Exception executing command: {0}", command_text ?? command); Log.Error (e); execution_exception = e; } // capture the text string raise_text = null; if (raise_command_executed && execution_ms >= raise_command_executed_threshold_ms) { raise_text = Text; } finished_event.Reset (); finished = true; if (raise_command_executed && execution_ms >= raise_command_executed_threshold_ms) { var handler = CommandExecuted; if (handler != null) { // Don't raise this on this thread; this thread is dedicated for use by the db connection ThreadAssist.ProxyToMain (delegate { handler (this, new CommandExecutedArgs (raise_text, execution_ms)); }); } } } internal object WaitForResult (HyenaSqliteConnection conn) { while (!finished) { conn.ResultReadySignal.WaitOne (); } // Reference the results since they could be overwritten object ret = result; var exception = execution_exception; // Reset to false in case run again finished = false; conn.ClaimResult (); finished_event.Set (); if (exception != null) { throw exception; } return ret; } internal void WaitIfNotFinished () { finished_event.WaitOne (); } internal HyenaSqliteCommand ApplyValues (params object [] param_values) { if (command_format == null) { CreateParameters (); } // Special case for if a single null values is the paramter array if (parameter_count == 1 && param_values == null) { current_values = new object [] { "NULL" }; command_formatted = null; return this; } if (param_values.Length != parameter_count) { throw new ArgumentException (String.Format ( "Command {2} has {0} parameters, but {1} values given.", parameter_count, param_values.Length, command )); } // Transform values as necessary - not needed for numerical types for (int i = 0; i < parameter_count; i++) { param_values[i] = SqlifyObject (param_values[i]); } current_values = param_values; command_formatted = null; return this; } public static object SqlifyObject (object o) { if (o is string) { return String.Format ("'{0}'", (o as string).Replace ("'", "''")); } else if (o is DateTime) { return DateTimeUtil.FromDateTime ((DateTime) o); } else if (o is bool) { return ((bool)o) ? "1" : "0"; } else if (o == null) { return "NULL"; } else if (o is byte[]) { string hex = BitConverter.ToString (o as byte[]).Replace ("-", ""); return String.Format ("X'{0}'", hex); } else if (o is Array) { StringBuilder sb = new StringBuilder (); bool first = true; foreach (object i in (o as Array)) { if (!first) sb.Append (","); else first = false; sb.Append (SqlifyObject (i)); } return sb.ToString (); } else { return o; } } private string CurrentSqlText { get { if (command_format == null) { return command; } if (command_formatted == null) { command_formatted = String.Format (System.Globalization.CultureInfo.InvariantCulture, command_format, current_values); } return command_formatted; } } private void CreateParameters () { StringBuilder sb = new StringBuilder (); foreach (char c in command) { if (c == '?') { sb.Append ('{'); sb.Append (parameter_count++); sb.Append ('}'); } else { sb.Append (c); } } command_format = sb.ToString (); } #region Static Debugging Facilities private static bool log_all = false; public static bool LogAll { get { return log_all; } set { log_all = value; } } public delegate void CommandExecutedHandler (object o, CommandExecutedArgs args); public static event CommandExecutedHandler CommandExecuted; private static bool raise_command_executed = false; public static bool RaiseCommandExecuted { get { return raise_command_executed; } set { raise_command_executed = value; } } private static int raise_command_executed_threshold_ms = 400; public static int RaiseCommandExecutedThresholdMs { get { return raise_command_executed_threshold_ms; } set { raise_command_executed_threshold_ms = value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 SubtractDouble() { var test = new SimpleBinaryOpTest__SubtractDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.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 (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.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 (Avx.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 (Avx.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 (Avx.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 SimpleBinaryOpTest__SubtractDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = 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.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); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; 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<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractDouble testClass) { var result = Avx.Subtract(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractDouble testClass) { fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) { var result = Avx.Subtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public SimpleBinaryOpTest__SubtractDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.Subtract( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.Subtract( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.Subtract( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Double>* pClsVar1 = &_clsVar1) fixed (Vector256<Double>* pClsVar2 = &_clsVar2) { var result = Avx.Subtract( Avx.LoadVector256((Double*)(pClsVar1)), Avx.LoadVector256((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractDouble(); var result = Avx.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__SubtractDouble(); fixed (Vector256<Double>* pFld1 = &test._fld1) fixed (Vector256<Double>* pFld2 = &test._fld2) { var result = Avx.Subtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) { var result = Avx.Subtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.Subtract( Avx.LoadVector256((Double*)(&test._fld1)), Avx.LoadVector256((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _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(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; 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.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(left[0] - right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i] - right[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Subtract)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; namespace Trisoft.ISHRemote.Cmdlets.EDT { /// <summary> /// <para type="synopsis">The Set-IshEDT cmdlet updates the EDTs that are passed through the pipeline or determined via provided parameters</para> /// <para type="description">The Set-IshEDT cmdlet updates the EDTs that are passed through the pipeline or determined via provided parameters</para> /// </summary> /// <example> /// <code> /// $ishSession = New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -IshUserName "username" -IshUserPassword "userpassword" /// $edtName = "MYEDT" /// $metadata = Set-IshMetadataField -IshSession $ishSession -Name "EDT-CANDIDATE" -Level "none" -Value "XML" | /// Set-IshMetadataField -IshSession $ishSession -Name "EDT-FILE-EXTENSION" -Level "none" -Value "XML" | /// Set-IshMetadataField -IshSession $ishSession -Name "EDT-MIME-TYPE" -Level "none" -Value "text/xml" /// $edtAdd = Add-IshEDT -IshSession $ishSession -Name $edtName -Metadata $metadata /// $metadataUpdate = Set-IshMetadataField -IshSession $ishSession -Name "NAME" -Level "none" -Value ($edtName + " updated") /// $requiredCurrentMetadata = Set-IshRequiredCurrentMetadataField -IshSession $ishSession -Name "EDT-FILE-EXTENSION" -Level "none" -Value "XML" /// Set-IshEDT -RequiredCurrentMetadata $requiredCurrentMetadata -Metadata $metadataUpdate /// </code> /// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Add EDT and update name</para> /// </example> /// <example> /// <code> /// $ishSession = New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -IshUserName "username" -IshUserPassword "userpassword" /// Set-IshEDT -IshSession $ishSession -Id EDTXML -Metadata (Set-IshMetadataField -IshSession $ishSession -Name "EDT-CANDIDATE" -Level None -ValueType Value -Value "xml, dita, ditamap") /// </code> /// <para>Adding .map and .ditamap to the EDTXML object. By adding these, tools like Content-Importer/DITA2Trisoft can import .xml, .dita and .ditamap files and they will all be assigned EDTXML as Electronic Document Type.</para> /// </example> [Cmdlet(VerbsCommon.Set, "IshEDT", SupportsShouldProcess = true)] [OutputType(typeof(IshEDT))] public sealed class SetIshEdt : EDTCmdlet { /// <summary> /// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [ValidateNotNullOrEmpty] public IshSession IshSession { get; set; } /// <summary> /// <para type="description">EDT Element Name</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty] public string Id { get; set; } /// <summary> /// <para type="description">The metadata to set for the object</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [ValidateNotNull] public IshField[] Metadata { get; set; } /// <summary> /// <para type="description">The required current metadata of the object. This parameter can be used to avoid that users override changes done by other users. The cmdlet will check whether the fields provided in this parameter still have the same values in the repository:</para> /// <para type="description">If the metadata is still the same, the metadata will be set.</para> /// <para type="description">If the metadata is not the same anymore, an error is given and the metadata will be set.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [ValidateNotNullOrEmpty] public IshField[] RequiredCurrentMetadata { get; set; } /// <summary> /// <para type="description">Array with the objects for which to retrieve the metadata. This array can be passed through the pipeline or explicitly passed via the parameter.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshObjectsGroup")] [AllowEmptyCollection] public IshObject[] IshObject { get; set; } protected override void BeginProcessing() { if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); } if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); } WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}"); base.BeginProcessing(); } /// <summary> /// Process the Set-IshEDT commandlet. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> /// <remarks>Writes an <see cref="Objects.Public.IshObject"/> array to the pipeline.</remarks> protected override void ProcessRecord() { try { // 1. Validating the input WriteDebug("Validating"); List<IshObject> returnedObjects = new List<IshObject>(); if (IshObject != null && IshObject.Length == 0) { // Do nothing WriteVerbose("IshObject is empty, so nothing to update"); } else { IshFields requiredCurrentMetadata = new IshFields(RequiredCurrentMetadata); // Updated EDT Ids List<string> EDTIdsToRetrieve = new List<string>(); IshFields returnFields; // 2. Doing Set WriteDebug("Updating"); // 2a. Set using provided parameters (not piped IshObject) if (IshObject != null) { // 2b. Set using IshObject pipeline. IshObjects ishObjects = new IshObjects(IshObject); int current = 0; foreach (IshObject ishObject in ishObjects.Objects) { WriteDebug($"Id[{ishObject.IshRef}] {++current}/{IshObject.Length}"); var metadata = IshSession.IshTypeFieldSetup.ToIshMetadataFields(ISHType, ishObject.IshFields, Enumerations.ActionMode.Update); if (ShouldProcess(ishObject.IshRef)) { IshSession.EDT25.Update( ishObject.IshRef, metadata.ToXml(), requiredCurrentMetadata.ToXml()); EDTIdsToRetrieve.Add(ishObject.IshRef); } } returnFields = (IshObject[0] == null) ? new IshFields() : IshObject[0].IshFields; } else { var metadata = IshSession.IshTypeFieldSetup.ToIshMetadataFields(ISHType, new IshFields(Metadata), Enumerations.ActionMode.Update); if (ShouldProcess(Id)) { IshSession.EDT25.Update( Id, metadata.ToXml(), requiredCurrentMetadata.ToXml()); EDTIdsToRetrieve.Add(Id); } returnFields = metadata; } // 3a. Retrieve updated EDT(s) from the database and write them out WriteDebug("Retrieving"); // Add the required fields (needed for pipe operations) IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, returnFields, Enumerations.ActionMode.Read); string xmlIshObjects = IshSession.EDT25.RetrieveMetadata( EDTIdsToRetrieve.ToArray(), EDT25ServiceReference.ActivityFilter.None, "", requestedMetadata.ToXml()); returnedObjects.AddRange(new IshObjects(ISHType, xmlIshObjects).Objects); } // 3b. Write it WriteVerbose("returned object count[" + returnedObjects.Count + "]"); WriteObject(IshSession, ISHType, returnedObjects.ConvertAll(x => (IshBaseObject)x), true); } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } } }
using System; using System.Collections.Generic; using System.Globalization; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Web; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Routing { /// <summary> /// Provides urls. /// </summary> public class DefaultUrlProvider : IUrlProvider { private readonly ILocalizationService _localizationService; private readonly ILocalizedTextService _localizedTextService; private readonly ILogger<DefaultUrlProvider> _logger; private readonly RequestHandlerSettings _requestSettings; private readonly ISiteDomainMapper _siteDomainMapper; private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly UriUtility _uriUtility; [Obsolete("Use ctor with all parameters")] public DefaultUrlProvider(IOptions<RequestHandlerSettings> requestSettings, ILogger<DefaultUrlProvider> logger, ISiteDomainMapper siteDomainMapper, IUmbracoContextAccessor umbracoContextAccessor, UriUtility uriUtility) : this(requestSettings, logger, siteDomainMapper, umbracoContextAccessor, uriUtility, StaticServiceProvider.Instance.GetRequiredService<ILocalizationService>()) { } public DefaultUrlProvider( IOptions<RequestHandlerSettings> requestSettings, ILogger<DefaultUrlProvider> logger, ISiteDomainMapper siteDomainMapper, IUmbracoContextAccessor umbracoContextAccessor, UriUtility uriUtility, ILocalizationService localizationService) { _requestSettings = requestSettings.Value; _logger = logger; _siteDomainMapper = siteDomainMapper; _umbracoContextAccessor = umbracoContextAccessor; _uriUtility = uriUtility; _localizationService = localizationService; } #region GetOtherUrls /// <summary> /// Gets the other URLs of a published content. /// </summary> /// <param name="umbracoContextAccessor">The Umbraco context.</param> /// <param name="id">The published content id.</param> /// <param name="current">The current absolute URL.</param> /// <returns>The other URLs for the published content.</returns> /// <remarks> /// <para> /// Other URLs are those that <c>GetUrl</c> would not return in the current context, but would be valid /// URLs for the node in other contexts (different domain for current request, umbracoUrlAlias...). /// </para> /// </remarks> public virtual IEnumerable<UrlInfo> GetOtherUrls(int id, Uri current) { IUmbracoContext umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); IPublishedContent node = umbracoContext.Content.GetById(id); if (node == null) { yield break; } // look for domains, walking up the tree IPublishedContent n = node; IEnumerable<DomainAndUri> domainUris = DomainUtilities.DomainsForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, n.Id, current, false); while (domainUris == null && n != null) // n is null at root { n = n.Parent; // move to parent node domainUris = n == null ? null : DomainUtilities.DomainsForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, n.Id, current); } // no domains = exit if (domainUris == null) { yield break; } foreach (DomainAndUri d in domainUris) { var culture = d?.Culture; // although we are passing in culture here, if any node in this path is invariant, it ignores the culture anyways so this is ok var route = umbracoContext.Content.GetRouteById(id, culture); if (route == null) { continue; } // need to strip off the leading ID for the route if it exists (occurs if the route is for a node with a domain assigned) var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path)); uri = _uriUtility.UriFromUmbraco(uri, _requestSettings); yield return UrlInfo.Url(uri.ToString(), culture); } } #endregion #region GetUrl /// <inheritdoc /> public virtual UrlInfo GetUrl(IPublishedContent content, UrlMode mode, string culture, Uri current) { if (!current.IsAbsoluteUri) { throw new ArgumentException("Current URL must be absolute.", nameof(current)); } IUmbracoContext umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); // will not use cache if previewing var route = umbracoContext.Content.GetRouteById(content.Id, culture); return GetUrlFromRoute(route, umbracoContext, content.Id, current, mode, culture); } internal UrlInfo GetUrlFromRoute( string route, IUmbracoContext umbracoContext, int id, Uri current, UrlMode mode, string culture) { if (string.IsNullOrWhiteSpace(route)) { _logger.LogDebug( "Couldn't find any page with nodeId={NodeId}. This is most likely caused by the page not being published.", id); return null; } // extract domainUri and path // route is /<path> or <domainRootId>/<path> var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); DomainAndUri domainUri = pos == 0 ? null : DomainUtilities.DomainForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, int.Parse(route.Substring(0, pos), CultureInfo.InvariantCulture), current, culture); var defaultCulture = _localizationService.GetDefaultLanguageIsoCode(); if (domainUri is not null || culture is null || culture.Equals(defaultCulture, StringComparison.InvariantCultureIgnoreCase)) { var url = AssembleUrl(domainUri, path, current, mode).ToString(); return UrlInfo.Url(url, culture); } return null; } #endregion #region Utilities private Uri AssembleUrl(DomainAndUri domainUri, string path, Uri current, UrlMode mode) { Uri uri; // ignore vdir at that point, UriFromUmbraco will do it if (domainUri == null) // no domain was found { if (current == null) { mode = UrlMode.Relative; // best we can do } switch (mode) { case UrlMode.Absolute: uri = new Uri(current.GetLeftPart(UriPartial.Authority) + path); break; case UrlMode.Relative: case UrlMode.Auto: uri = new Uri(path, UriKind.Relative); break; default: throw new ArgumentOutOfRangeException(nameof(mode)); } } else // a domain was found { if (mode == UrlMode.Auto) { //this check is a little tricky, we can't just compare domains if (current != null && domainUri.Uri.GetLeftPart(UriPartial.Authority) == current.GetLeftPart(UriPartial.Authority)) { mode = UrlMode.Relative; } else { mode = UrlMode.Absolute; } } switch (mode) { case UrlMode.Absolute: uri = new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path)); break; case UrlMode.Relative: uri = new Uri(CombinePaths(domainUri.Uri.AbsolutePath, path), UriKind.Relative); break; default: throw new ArgumentOutOfRangeException(nameof(mode)); } } // UriFromUmbraco will handle vdir // meaning it will add vdir into domain URLs too! return _uriUtility.UriFromUmbraco(uri, _requestSettings); } private string CombinePaths(string path1, string path2) { var path = path1.TrimEnd(Constants.CharArrays.ForwardSlash) + path2; return path == "/" ? path : path.TrimEnd(Constants.CharArrays.ForwardSlash); } #endregion } }
using System; using System.Globalization; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// GData schema extension describing a period of time. /// </summary> public class When : IExtensionElementFactory { /// <summary> /// Event end time (optional). /// </summary> private DateTime endTime; /// <summary> /// reminder object to set reminder durations /// </summary> private ExtensionCollection<Reminder> reminders; /// <summary> /// Event start time (required). /// </summary> private DateTime startTime; /// <summary> /// Constructs a new instance of a When object. /// </summary> public When() { } /// <summary> /// Constructs a new instance of a When object with provided data. /// </summary> /// <param name="start">The beginning of the event.</param> /// <param name="end">The end of the event.</param> public When(DateTime start, DateTime end) : this() { StartTime = start; EndTime = end; } /// <summary> /// Constructs a new instance of a When object with provided data. /// </summary> /// <param name="start">The beginning of the event.</param> /// <param name="end">The end of the event.</param> /// <param name="allDay">A flag to indicate an all day event.</param> public When(DateTime start, DateTime end, bool allDay) : this(start, end) { AllDay = allDay; } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public DateTime StartTime</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public DateTime StartTime { get { return startTime; } set { startTime = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public DateTime EndTime</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public DateTime EndTime { get { return endTime; } set { endTime = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>reminder accessor</summary> ////////////////////////////////////////////////////////////////////// public ExtensionCollection<Reminder> Reminders { get { if (reminders == null) { reminders = new ExtensionCollection<Reminder>(null); } return reminders; } } /// <summary> /// accessor method public string ValueString /// </summary> /// <returns> </returns> public string ValueString { get; set; } /// <summary> /// accessor method to the allday event flag /// </summary> /// <returns>true if it's an all day event</returns> public bool AllDay { get; set; } #region overloaded for persistence /// <summary> /// Persistence method for the When object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (Utilities.IsPersistable(ValueString) || Utilities.IsPersistable(startTime) || Utilities.IsPersistable(endTime)) { writer.WriteStartElement(BaseNameTable.gDataPrefix, XmlName, BaseNameTable.gNamespace); if (startTime != new DateTime(1, 1, 1)) { string date = AllDay ? Utilities.LocalDateInUTC(startTime) : Utilities.LocalDateTimeInUTC(startTime); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeStartTime, date); } else { throw new ClientFeedException("g:when/@startTime is required."); } if (endTime != new DateTime(1, 1, 1)) { string date = AllDay ? Utilities.LocalDateInUTC(endTime) : Utilities.LocalDateTimeInUTC(endTime); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeEndTime, date); } if (Utilities.IsPersistable(ValueString)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeValueString, ValueString); } if (reminders != null) { foreach (Reminder r in Reminders) { r.Save(writer); } } writer.WriteEndElement(); } } #endregion #region overloaded from IExtensionElementFactory /// <summary>Parses an xml node to create a Where object.</summary> /// <param name="node">the node to parse node</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created Where object</returns> public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall(); When when = null; if (node != null) { object localname = node.LocalName; if (!localname.Equals(XmlName) || !node.NamespaceURI.Equals(XmlNameSpace)) { return null; } } bool startTimeFlag = false, endTimeFlag = false; when = new When(); if (node != null) { if (node.Attributes != null) { string value = node.Attributes[GDataParserNameTable.XmlAttributeStartTime] != null ? node.Attributes[GDataParserNameTable.XmlAttributeStartTime].Value : null; if (value != null) { startTimeFlag = true; when.startTime = DateTime.Parse(value); when.AllDay = (value.IndexOf('T') == -1); } value = node.Attributes[GDataParserNameTable.XmlAttributeEndTime] != null ? node.Attributes[GDataParserNameTable.XmlAttributeEndTime].Value : null; if (value != null) { endTimeFlag = true; when.endTime = DateTime.Parse(value); when.AllDay = when.AllDay && (value.IndexOf('T') == -1); } if (node.Attributes[GDataParserNameTable.XmlAttributeValueString] != null) { when.ValueString = node.Attributes[GDataParserNameTable.XmlAttributeValueString].Value; } } // single event, g:reminder is inside g:when if (node.HasChildNodes) { XmlNode whenChildNode = node.FirstChild; IExtensionElementFactory f = new Reminder(); while (whenChildNode != null) { if (whenChildNode is XmlElement) { if ( string.Compare(whenChildNode.NamespaceURI, f.XmlNameSpace, true, CultureInfo.InvariantCulture) == 0) { if ( string.Compare(whenChildNode.LocalName, f.XmlName, true, CultureInfo.InvariantCulture) == 0) { Reminder r = f.CreateInstance(whenChildNode, null) as Reminder; when.Reminders.Add(r); } } } whenChildNode = whenChildNode.NextSibling; } } } if (!startTimeFlag) { throw new ClientFeedException("g:when/@startTime is required."); } if (endTimeFlag && when.startTime.CompareTo(when.endTime) > 0) { throw new ClientFeedException("g:when/@startTime must be less than or equal to g:when/@endTime."); } return when; } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element. /// </summary> ////////////////////////////////////////////////////////////////////// public string XmlName { get { return GDataParserNameTable.XmlWhenElement; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlNameSpace { get { return BaseNameTable.gNamespace; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlPrefix { get { return BaseNameTable.gDataPrefix; } } #endregion } }
using Foundation; namespace Xamarin.iOS { [Preserve(AllMembers = true)] class iOSHardware { private readonly iOSChipTypeMap _chipTypeMap; public iOSHardware() { _chipTypeMap = new iOSChipTypeMap(); } public iOSChipType GetChipType(string hardware) => _chipTypeMap.GetChipType(hardware); public string GetModel(string hardware) { if (hardware.StartsWith("iPhone")) { switch (hardware) { case "iPhone13,1": return "iPhone 12 mini"; case "iPhone13,2": return "iPhone 12"; case "iPhone13,3": return "iPhone 12 Pro"; case "iPhone13,4": return "iPhone 12 Pro Max"; case "iPhone12,8": return "iPhone SE (2nd generation)"; case "iPhone12,5": return "iPhone 11 Pro Max"; case "iPhone12,3": return "iPhone 11 Pro"; case "iPhone12,1": return "iPhone 11"; case "iPhone11,2": return "iPhone XS"; case "iPhone11,4": case "iPhone11,6": return "iPhone XS Max"; case "iPhone11,8": return "iPhone XR"; case "iPhone10,3": case "iPhone10,6": return "iPhone X"; case "iPhone10,2": case "iPhone10,5": return "iPhone 8 Plus"; case "iPhone10,1": case "iPhone10,4": return "iPhone 8"; case "iPhone9,2": case "iPhone9,4": return "iPhone 7 Plus"; case "iPhone9,1": case "iPhone9,3": return "iPhone 7"; case "iPhone8,4": return "iPhone SE"; case "iPhone8,2": return "iPhone 6S Plus"; case "iPhone8,1": return "iPhone 6S"; case "iPhone7,1": return "iPhone 6 Plus"; case "iPhone7,2": return "iPhone 6"; case "iPhone6,2": return "iPhone 5S Global"; case "iPhone6,1": return "iPhone 5S GSM"; case "iPhone5,4": return "iPhone 5C Global"; case "iPhone5,3": return "iPhone 5C GSM"; case "iPhone5,2": return "iPhone 5 Global"; case "iPhone5,1": return "iPhone 5 GSM"; case "iPhone4,1": return "iPhone 4S"; case "iPhone3,3": return "iPhone 4 CDMA"; case "iPhone3,1": case "iPhone3,2": return "iPhone 4 GSM"; case "iPhone2,1": return "iPhone 3GS"; case "iPhone1,2": return "iPhone 3G"; case "iPhone1,1": return "iPhone"; } } if (hardware.StartsWith("iPod")) { switch (hardware) { case "iPod9,1": return "iPod touch 7G"; case "iPod7,1": return "iPod touch 6G"; case "iPod5,1": return "iPod touch 5G"; case "iPod4,1": return "iPod touch 4G"; case "iPod3,1": return "iPod touch 3G"; case "iPod2,1": return "iPod touch 2G"; case "iPod1,1": return "iPod touch"; } } if (hardware.StartsWith("iPad")) { switch (hardware) { case "iPad13,2": return "iPad Air (4th generation) Wi-Fi + Cellular"; case "iPad13,1": return "iPad Air (4th generation) Wi-Fi"; case "iPad11,7": return "iPad (8th Generation) Wi-Fi + Cellular"; case "iPad11,6": return "iPad (8th Generation) Wi-Fi"; case "iPad11,4": return "iPad Air (3rd generation) Wi-Fi + Cellular"; case "iPad11,3": return "iPad Air (3rd generation) Wi-Fi"; case "iPad11,2": return "iPad mini (5th generation) Wi-Fi + Cellular"; case "iPad11,1": return "iPad mini (5th generation) Wi-Fi"; case "iPad8,12": return "iPad Pro (12.9-inch) (4th generation) Wi-Fi + Cellular"; case "iPad8,11": return "iPad Pro (12.9-inch) (4th generation) Wi-Fi"; case "iPad8,10": return "iPad Pro (11-inch) (2nd generation) Wi-Fi + Cellular"; case "iPad8,9": return "iPad Pro (11-inch) (2nd generation) Wi-Fi"; case "iPad8,8": return "iPad Pro 12.9-inch (3rd Generation)"; case "iPad8,7": return "iPad Pro 12.9-inch (3rd generation) Wi-Fi + Cellular"; case "iPad8,6": return "iPad Pro 12.9-inch (3rd Generation)"; case "iPad8,5": return "iPad Pro 12.9-inch (3rd Generation)"; case "iPad8,4": return "iPad Pro 11-inch"; case "iPad8,3": return "iPad Pro 11-inch Wi-Fi + Cellular"; case "iPad8,2": return "iPad Pro 11-inch"; case "iPad8,1": return "iPad Pro 11-inch Wi-Fi"; case "iPad7,12": return "iPad (7th generation) Wi-Fi + Cellular"; case "iPad7,11": return "iPad (7th generation) Wi-Fi"; case "iPad7,6": return "iPad (6th generation) Wi-Fi + Cellular"; case "iPad7,5": return "iPad (6th generation) Wi-Fi"; case "iPad7,4": return "iPad Pro (10.5-inch) Wi-Fi + Cellular"; case "iPad7,3": return "iPad Pro (10.5-inch) Wi-Fi"; case "iPad7,2": return "iPad Pro 12.9-inch (2nd generation) Wi-Fi + Cellular"; case "iPad7,1": return "iPad Pro 12.9-inch (2nd generation) Wi-Fi"; case "iPad6,12": return "iPad (5th generation) Wi-Fi + Cellular"; case "iPad6,11": return "iPad (5th generation) Wi-Fi"; case "iPad6,8": return "iPad Pro 12.9-inch Wi-Fi + Cellular"; case "iPad6,7": return "iPad Pro 12.9-inch Wi-Fi"; case "iPad6,4": return "iPad Pro (9.7-inch) Wi-Fi + Cellular"; case "iPad6,3": return "iPad Pro (9.7-inch) Wi-Fi"; case "iPad5,4": return "iPad Air 2 Wi-Fi + Cellular"; case "iPad5,3": return "iPad Air 2 Wi-Fi"; case "iPad5,2": return "iPad mini 4 Wi-Fi + Cellular"; case "iPad5,1": return "iPad mini 4 Wi-Fi"; case "iPad4,9": return "iPad mini 3 Wi-Fi + Cellular (TD-LTE)"; case "iPad4,8": return "iPad mini 3 Wi-Fi + Cellular"; case "iPad4,7": return "iPad mini 3 Wi-Fi"; case "iPad4,6": return "iPad mini 2 Wi-Fi + Cellular (TD-LTE)"; case "iPad4,5": return "iPad mini 2 Wi-Fi + Cellular"; case "iPad4,4": return "iPad mini 2 Wi-Fi"; case "iPad4,3": return "iPad Air Wi-Fi + Cellular (TD-LTE)"; case "iPad4,2": return "iPad Air Wi-Fi + Cellular"; case "iPad4,1": return "iPad Air Wi-Fi"; case "iPad3,6": return "iPad (4th generation) Wi-Fi + Cellular (MM)"; case "iPad3,5": return "iPad (4th generation) Wi-Fi + Cellular"; case "iPad3,4": return "iPad (4th generation) Wi-Fi"; case "iPad3,3": return "iPad 3 Wi-Fi + Cellular (CDMA)"; case "iPad3,2": return "iPad 3 Wi-Fi + Cellular (GSM)"; case "iPad3,1": return "iPad 3 Wi-Fi"; case "iPad2,7": return "iPad mini Wi-Fi + Cellular (MM)"; case "iPad2,6": return "iPad mini Wi-Fi + Cellular"; case "iPad2,5": return "iPad mini Wi-Fi"; case "iPad2,4": return "iPad 2 Wi-Fi"; case "iPad2,3": return "iPad 2 CDMA"; case "iPad2,2": return "iPad 2 GSM"; case "iPad2,1": return "iPad 2 Wi-Fi"; case "iPad1,1": return "iPad"; } } if (hardware == "i386" || hardware == "x86_64") return "Simulator"; return (hardware == "" ? "Unknown" : hardware); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Security; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { #pragma warning disable BCL0015 // CoreFxPort /*typedef struct _DOMAIN_CONTROLLER_INFO { LPTSTR DomainControllerName; LPTSTR DomainControllerAddress; ULONG DomainControllerAddressType; GUID DomainGuid; LPTSTR DomainName; LPTSTR DnsForestName; ULONG Flags; LPTSTR DcSiteName; LPTSTR ClientSiteName; } DOMAIN_CONTROLLER_INFO, *PDOMAIN_CONTROLLER_INFO; */ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class DomainControllerInfo { public string DomainControllerName; public string DomainControllerAddress; public int DomainControllerAddressType; public Guid DomainGuid; public string DomainName; public string DnsForestName; public int Flags; public string DcSiteName; public string ClientSiteName; } /*typedef struct { LPTSTR NetbiosName; LPTSTR DnsHostName; LPTSTR SiteName; LPTSTR SiteObjectName; LPTSTR ComputerObjectName; LPTSTR ServerObjectName; LPTSTR NtdsaObjectName; BOOL fIsPdc; BOOL fDsEnabled; BOOL fIsGc; GUID SiteObjectGuid; GUID ComputerObjectGuid; GUID ServerObjectGuid; GUID NtdsDsaObjectGuid; } DS_DOMAIN_CONTROLLER_INFO_2, *PDS_DOMAIN_CONTROLLER_INFO_2;*/ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class DsDomainControllerInfo2 { public string netBiosName; public string dnsHostName; public string siteName; public string siteObjectName; public string computerObjectName; public string serverObjectName; public string ntdsaObjectName; public bool isPdc; public bool dsEnabled; public bool isGC; public Guid siteObjectGuid; public Guid computerObjectGuid; public Guid serverObjectGuid; public Guid ntdsDsaObjectGuid; } /*typedef struct { LPTSTR NetbiosName; LPTSTR DnsHostName; LPTSTR SiteName; LPTSTR SiteObjectName; LPTSTR ComputerObjectName; LPTSTR ServerObjectName; LPTSTR NtdsaObjectName; BOOL fIsPdc; BOOL fDsEnabled; BOOL fIsGc; BOOL fIsRodc; GUID SiteObjectGuid; GUID ComputerObjectGuid; GUID ServerObjectGuid; GUID NtdsDsaObjectGuid; } DS_DOMAIN_CONTROLLER_INFO_3, *PDS_DOMAIN_CONTROLLER_INFO_3;*/ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class DsDomainControllerInfo3 { public string netBiosName; public string dnsHostName; public string siteName; public string siteObjectName; public string computerObjectName; public string serverObjectName; public string ntdsaObjectName; public bool isPdc; public bool dsEnabled; public bool isGC; public bool isRodc; public Guid siteObjectGuid; public Guid computerObjectGuid; public Guid serverObjectGuid; public Guid ntdsDsaObjectGuid; } /*typedef struct { DWORD cItems; PDS_NAME_RESULT_ITEM rItems; } DS_NAME_RESULT, *PDS_NAME_RESULT;*/ [StructLayout(LayoutKind.Sequential)] internal sealed class DsNameResult { public int itemCount; public IntPtr items; } /*typedef struct { DWORD status; LPTSTR pDomain; LPTSTR pName; } DS_NAME_RESULT_ITEM, *PDS_NAME_RESULT_ITEM;*/ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class DsNameResultItem { public int status; public string domain; public string name; } /*typedef struct _DnsRecord { struct _DnsRecord * pNext; LPTSTR pName; WORD wType; WORD wDataLength; // Not referenced for DNS record //types defined above. union { DWORD DW; // flags as DWORD DNS_RECORD_FLAGS S; // flags as structure } Flags; DWORD dwTtl; DWORD dwReserved; // Record Data union { DNS_A_DATA A; DNS_SOA_DATA SOA, Soa; DNS_PTR_DATA PTR, Ptr, NS, Ns, CNAME, Cname, MB, Mb, MD, Md, MF, Mf, MG, Mg, MR, Mr; DNS_MINFO_DATA MINFO, Minfo, RP, Rp; DNS_MX_DATA MX, Mx, AFSDB, Afsdb, RT, Rt; DNS_TXT_DATA HINFO, Hinfo, ISDN, Isdn, TXT, Txt, X25; DNS_NULL_DATA Null; DNS_WKS_DATA WKS, Wks; DNS_AAAA_DATA AAAA; DNS_KEY_DATA KEY, Key; DNS_SIG_DATA SIG, Sig; DNS_ATMA_DATA ATMA, Atma; DNS_NXT_DATA NXT, Nxt; DNS_SRV_DATA SRV, Srv; DNS_TKEY_DATA TKEY, Tkey; DNS_TSIG_DATA TSIG, Tsig; DNS_WINS_DATA WINS, Wins; DNS_WINSR_DATA WINSR, WinsR, NBSTAT, Nbstat; } Data; }DNS_RECORD, *PDNS_RECORD;*/ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class DnsRecord { public IntPtr next; public string name; public short type; public short dataLength; public int flags; public int ttl; public int reserved; public DnsSrvData data; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class PartialDnsRecord { public IntPtr next; public string name; public short type; public short dataLength; public int flags; public int ttl; public int reserved; public IntPtr data; } /*typedef struct { LPTSTR pNameTarget; WORD wPriority; WORD wWeight; WORD wPort; WORD Pad; // keep ptrs DWORD aligned }DNS_SRV_DATA, *PDNS_SRV_DATA;*/ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class DnsSrvData { public string targetName; public short priority; public short weight; public short port; public short pad; } /*typedef struct _OSVERSIONINFOEX { DWORD dwOSVersionInfoSize; DWORD dwMajorVersion; DWORD dwMinorVersion; DWORD dwBuildNumber; DWORD dwPlatformId; TCHAR szCSDVersion[ 128 ]; WORD wServicePackMajor; WORD wServicePackMinor; WORD wSuiteMask; BYTE wProductType; BYTE wReserved; } OSVERSIONINFOEX, *POSVERSIONINFOEX, *LPOSVERSIONINFOEX;*/ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class OSVersionInfoEx { public OSVersionInfoEx() { osVersionInfoSize = (int)Marshal.SizeOf(this); } // The OSVersionInfoSize field must be set to Marshal.SizeOf(this) public int osVersionInfoSize = 0; public int majorVersion = 0; public int minorVersion = 0; public int buildNumber = 0; public int platformId = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string csdVersion = null; public short servicePackMajor = 0; public short servicePackMinor = 0; public short suiteMask = 0; public byte productType = 0; public byte reserved = 0; } /*typedef struct _LUID { DWORD LowPart; LONG HighPart; } LUID, *PLUID;*/ [StructLayout(LayoutKind.Sequential)] internal sealed class LUID { public int LowPart; public int HighPart; } /*typedef struct _NEGOTIATE_CALLER_NAME_REQUEST { ULONG MessageType ; LUID LogonId ; } NEGOTIATE_CALLER_NAME_REQUEST, *PNEGOTIATE_CALLER_NAME_REQUEST ;*/ [StructLayout(LayoutKind.Sequential)] internal sealed class NegotiateCallerNameRequest { public int messageType; public LUID logonId; } /*typedef struct _NEGOTIATE_CALLER_NAME_RESPONSE { ULONG MessageType ; PWSTR CallerName ; } NEGOTIATE_CALLER_NAME_RESPONSE, * PNEGOTIATE_CALLER_NAME_RESPONSE ;*/ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class NegotiateCallerNameResponse { public int messageType; public string callerName; } internal sealed class NativeMethods { // disable public constructor private NativeMethods() { } internal const int VER_PLATFORM_WIN32_NT = 2; internal const int ERROR_INVALID_DOMAIN_NAME_FORMAT = 1212; internal const int ERROR_NO_SUCH_DOMAIN = 1355; internal const int ERROR_NOT_ENOUGH_MEMORY = 8; internal const int ERROR_INVALID_FLAGS = 1004; internal const int DS_NAME_NO_ERROR = 0; internal const int ERROR_NO_MORE_ITEMS = 259; internal const int ERROR_FILE_MARK_DETECTED = 1101; internal const int DNS_ERROR_RCODE_NAME_ERROR = 9003; internal const int ERROR_NO_SUCH_LOGON_SESSION = 1312; internal const int DS_NAME_FLAG_SYNTACTICAL_ONLY = 1; internal const int DS_FQDN_1779_NAME = 1; internal const int DS_CANONICAL_NAME = 7; internal const int DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 6; internal const int STATUS_QUOTA_EXCEEDED = unchecked((int)0xC0000044); /*DWORD DsGetDcName( LPCTSTR ComputerName, LPCTSTR DomainName, GUID* DomainGuid, LPCTSTR SiteName, ULONG Flags, PDOMAIN_CONTROLLER_INFO* DomainControllerInfo );*/ [DllImport("Netapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)] internal static extern int DsGetDcName( [In] string computerName, [In] string domainName, [In] IntPtr domainGuid, [In] string siteName, [In] int flags, [Out] out IntPtr domainControllerInfo); /* DWORD WINAPI DsGetDcOpen( LPCTSTR DnsName, ULONG OptionFlags, LPCTSTR SiteName, GUID* DomainGuid, LPCTSTR DnsForestName, ULONG DcFlags, PHANDLE RetGetDcContext );*/ [DllImport("Netapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcOpenW", CharSet = CharSet.Unicode)] internal static extern int DsGetDcOpen( [In] string dnsName, [In] int optionFlags, [In] string siteName, [In] IntPtr domainGuid, [In] string dnsForestName, [In] int dcFlags, [Out] out IntPtr retGetDcContext); /*DWORD WINAPI DsGetDcNext( HANDLE GetDcContextHandle, PULONG SockAddressCount, LPSOCKET_ADDRESS* SockAddresses, LPTSTR* DnsHostName );*/ [DllImport("Netapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNextW", CharSet = CharSet.Unicode)] internal static extern int DsGetDcNext( [In] IntPtr getDcContextHandle, [In, Out] ref IntPtr sockAddressCount, [Out] out IntPtr sockAdresses, [Out] out IntPtr dnsHostName); /*void WINAPI DsGetDcClose( HANDLE GetDcContextHandle );*/ [DllImport("Netapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcCloseW", CharSet = CharSet.Unicode)] internal static extern void DsGetDcClose( [In] IntPtr getDcContextHandle); /*NET_API_STATUS NetApiBufferFree( LPVOID Buffer );*/ [DllImport("Netapi32.dll")] internal static extern int NetApiBufferFree( [In] IntPtr buffer); /*DWORD DsMakePasswordCredentials( LPTSTR User, LPTSTR Domain, LPTSTR Password, RPC_AUTH_IDENTITY_HANDLE* pAuthIdentity );*/ internal delegate int DsMakePasswordCredentials( [MarshalAs(UnmanagedType.LPWStr)] string user, [MarshalAs(UnmanagedType.LPWStr)] string domain, [MarshalAs(UnmanagedType.LPWStr)] string password, [Out] out IntPtr authIdentity); /*VOID DsFreePasswordCredentials( RPC_AUTH_IDENTITY_HANDLE AuthIdentity );*/ internal delegate void DsFreePasswordCredentials( [In] IntPtr authIdentity); /*DWORD DsBindWithCred( TCHAR* DomainController, TCHAR* DnsDomainName, RPC_AUTH_IDENTITY_HANDLE AuthIdentity, HANDLE* phDS );*/ internal delegate int DsBindWithCred( [MarshalAs(UnmanagedType.LPWStr)] string domainController, [MarshalAs(UnmanagedType.LPWStr)] string dnsDomainName, [In] IntPtr authIdentity, [Out] out IntPtr handle); /*DWORD DsUnBind( HANDLE* phDS );*/ internal delegate int DsUnBind( [In] ref IntPtr handle); /*DWORD DsGetDomainControllerInfo( HANDLE hDs, LPTSTR DomainName, DWORD InfoLevel, DWORD* pcOut, VOID** ppInfo );*/ internal delegate int DsGetDomainControllerInfo( [In] IntPtr handle, [MarshalAs(UnmanagedType.LPWStr)] string domainName, [In] int infoLevel, [Out] out int dcCount, [Out] out IntPtr dcInfo); internal const int DsDomainControllerInfoLevel2 = 2; internal const int DsDomainControllerInfoLevel3 = 3; /*VOID DsFreeDomainControllerInfo( DWORD InfoLevel, DWORD cInfo, VOID* pInfo );*/ internal delegate void DsFreeDomainControllerInfo( [In] int infoLevel, [In] int dcInfoListCount, [In] IntPtr dcInfoList); internal const int DsNameNoError = 0; /*DWORD DsListSites( HANDLE hDs, PDS_NAME_RESULT* ppSites );*/ internal delegate int DsListSites( [In] IntPtr dsHandle, [Out] out IntPtr sites); /*DWORD DsListRoles( HANDLE hDs, PDS_NAME_RESULTW* ppRoles );*/ internal delegate int DsListRoles( [In] IntPtr dsHandle, [Out] out IntPtr roles); /*DWORD GetLastError(VOID)*/ [DllImport("Kernel32.dll")] internal static extern int GetLastError(); internal const int DnsSrvData = 33; internal const int DnsQueryBypassCache = 8; /*DNS_STATUS WINAPI DnsQuery ( LPSTR lpstrName, WORD wType, DWORD fOptions, PIP4_ARRAY aipServers, PDNS_RECORD *ppQueryResultsSet, PVOID *pReserved );*/ [DllImport("Dnsapi.dll", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode)] internal static extern int DnsQuery( [In] string recordName, [In] short recordType, [In] int options, [In] IntPtr servers, [Out] out IntPtr dnsResultList, [Out] IntPtr reserved); /*VOID WINAPI DnsRecordListFree( PDNS_RECORD pRecordList, DNS_FREE_TYPE FreeType );*/ [DllImport("Dnsapi.dll", CharSet = CharSet.Unicode)] internal static extern void DnsRecordListFree( [In] IntPtr dnsResultList, [In] bool dnsFreeType); /*BOOL GetVersionEx( LPOSVERSIONINFO lpVersionInfo );*/ [DllImport("Kernel32.dll", EntryPoint = "GetVersionExW", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool GetVersionEx( [In, Out] OSVersionInfoEx ver); /*DWORD DsCrackNames( HANDLE hDS, DS_NAME_FLAGS flags, DS_NAME_FORMAT formatOffered, DS_NAME_FORMAT formatDesired, DWORD cNames, LPTSTR* rpNames, PDS_NAME_RESULT* ppResult );*/ internal delegate int DsCrackNames( [In] IntPtr hDS, [In] int flags, [In] int formatOffered, [In] int formatDesired, [In] int nameCount, [In] IntPtr names, [Out] out IntPtr results); /*NTSTATUS LsaConnectUntrusted( PHANDLE LsaHandle );*/ [DllImport("Secur32.dll")] internal static extern int LsaConnectUntrusted( [Out] out LsaLogonProcessSafeHandle lsaHandle); internal const int NegGetCallerName = 1; /*NTSTATUS LsaCallAuthenticationPackage( HANDLE LsaHandle, ULONG AuthenticationPackage, PVOID ProtocolSubmitBuffer, ULONG SubmitBufferLength, PVOID* ProtocolReturnBuffer, PULONG ReturnBufferLength, PNTSTATUS ProtocolStatus );*/ [DllImport("Secur32.dll")] internal static extern int LsaCallAuthenticationPackage( [In] LsaLogonProcessSafeHandle lsaHandle, [In] int authenticationPackage, [In] NegotiateCallerNameRequest protocolSubmitBuffer, [In] int submitBufferLength, [Out] out IntPtr protocolReturnBuffer, [Out] out int returnBufferLength, [Out] out int protocolStatus); /*NTSTATUS LsaFreeReturnBuffer( PVOID Buffer );*/ [DllImport("Secur32.dll")] internal static extern uint LsaFreeReturnBuffer( [In] IntPtr buffer); /*NTSTATUS LsaDeregisterLogonProcess( HANDLE LsaHandle );*/ [DllImport("Secur32.dll")] internal static extern int LsaDeregisterLogonProcess( [In] IntPtr lsaHandle); /*int CompareString(LCID Locale, DWORD dwCmpFlags, DWORD lpString1, DWORD cchCount1, DWORD lpString2, DWORD cchCount2 );*/ [DllImport("Kernel32.dll", EntryPoint = "CompareStringW", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern int CompareString( [In] uint locale, [In] uint dwCmpFlags, [In] IntPtr lpString1, [In] int cchCount1, [In] IntPtr lpString2, [In] int cchCount2); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)] internal static extern int LsaNtStatusToWinError(int ntStatus); } internal sealed class NativeComInterfaces { /*typedef enum { ADS_SETTYPE_FULL=1, ADS_SETTYPE_PROVIDER=2, ADS_SETTYPE_SERVER=3, ADS_SETTYPE_DN=4 } ADS_SETTYPE_ENUM; typedef enum { ADS_FORMAT_WINDOWS=1, ADS_FORMAT_WINDOWS_NO_SERVER=2, ADS_FORMAT_WINDOWS_DN=3, ADS_FORMAT_WINDOWS_PARENT=4, ADS_FORMAT_X500=5, ADS_FORMAT_X500_NO_SERVER=6, ADS_FORMAT_X500_DN=7, ADS_FORMAT_X500_PARENT=8, ADS_FORMAT_SERVER=9, ADS_FORMAT_PROVIDER=10, ADS_FORMAT_LEAF=11 } ADS_FORMAT_ENUM; typedef enum { ADS_ESCAPEDMODE_DEFAULT=1, ADS_ESCAPEDMODE_ON=2, ADS_ESCAPEDMODE_OFF=3, ADS_ESCAPEDMODE_OFF_EX=4 } ADS_ESCAPE_MODE_ENUM;*/ internal const int ADS_SETTYPE_DN = 4; internal const int ADS_FORMAT_X500_DN = 7; internal const int ADS_ESCAPEDMODE_ON = 2; internal const int ADS_ESCAPEDMODE_OFF_EX = 4; internal const int ADS_FORMAT_LEAF = 11; // // Pathname as a co-class that implements the IAdsPathname interface // [ComImport, Guid("080d0d78-f421-11d0-a36e-00c04fb950dc")] internal class Pathname { } [ComImport, Guid("D592AED4-F420-11D0-A36E-00C04FB950DC")] internal interface IAdsPathname { // HRESULT Set([in] BSTR bstrADsPath, [in] long lnSetType); int Set([In, MarshalAs(UnmanagedType.BStr)] string bstrADsPath, [In, MarshalAs(UnmanagedType.U4)] int lnSetType); // HRESULT SetDisplayType([in] long lnDisplayType); int SetDisplayType([In, MarshalAs(UnmanagedType.U4)] int lnDisplayType); // HRESULT Retrieve([in] long lnFormatType, [out, retval] BSTR* pbstrADsPath); [return: MarshalAs(UnmanagedType.BStr)] string Retrieve([In, MarshalAs(UnmanagedType.U4)] int lnFormatType); // HRESULT GetNumElements([out, retval] long* plnNumPathElements); [return: MarshalAs(UnmanagedType.U4)] int GetNumElements(); // HRESULT GetElement([in] long lnElementIndex, [out, retval] BSTR* pbstrElement); [return: MarshalAs(UnmanagedType.BStr)] string GetElement([In, MarshalAs(UnmanagedType.U4)] int lnElementIndex); // HRESULT AddLeafElement([in] BSTR bstrLeafElement); void AddLeafElement([In, MarshalAs(UnmanagedType.BStr)] string bstrLeafElement); // HRESULT RemoveLeafElement(); void RemoveLeafElement(); // HRESULT CopyPath([out, retval] IDispatch** ppAdsPath); [return: MarshalAs(UnmanagedType.Interface)] object CopyPath(); // HRESULT GetEscapedElement([in] long lnReserved, [in] BSTR bstrInStr, [out, retval] BSTR* pbstrOutStr ); [return: MarshalAs(UnmanagedType.BStr)] string GetEscapedElement([In, MarshalAs(UnmanagedType.U4)] int lnReserved, [In, MarshalAs(UnmanagedType.BStr)] string bstrInStr); int EscapedMode { get; set; } } [ComImport, Guid("C8F93DD3-4AE0-11CF-9E73-00AA004A5691")] internal interface IAdsProperty { // // Need to also include the IAds interface definition here // string Name { [return: MarshalAs(UnmanagedType.BStr)] get; } string Class { [return: MarshalAs(UnmanagedType.BStr)] get; } string GUID { [return: MarshalAs(UnmanagedType.BStr)] get; } string ADsPath { [return: MarshalAs(UnmanagedType.BStr)] get; } string Parent { [return: MarshalAs(UnmanagedType.BStr)] get; } string Schema { [return: MarshalAs(UnmanagedType.BStr)] get; } void GetInfo(); void SetInfo(); Object Get([In, MarshalAs(UnmanagedType.BStr)] string bstrName); void Put([In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] Object vProp); Object GetEx([In, MarshalAs(UnmanagedType.BStr)] String bstrName); void PutEx([In, MarshalAs(UnmanagedType.U4)] int lnControlCode, [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] Object vProp); void GetInfoEx([In] Object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved); // // IAdsProperty definition starts here // string OID { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string Syntax { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; } int MaxRange { [return: MarshalAs(UnmanagedType.U4)] get; [param: MarshalAs(UnmanagedType.U4)] set; } int MinRange { [return: MarshalAs(UnmanagedType.U4)] get; [param: MarshalAs(UnmanagedType.U4)] set; } bool MultiValued { get; set; } object Qualifiers(); } [ComImport, Guid("C8F93DD0-4AE0-11CF-9E73-00AA004A5691")] internal interface IAdsClass { // // Need to also include the IAds interface definition here // string Name { [return: MarshalAs(UnmanagedType.BStr)] get; } string Class { [return: MarshalAs(UnmanagedType.BStr)] get; } string GUID { [return: MarshalAs(UnmanagedType.BStr)] get; } string ADsPath { [return: MarshalAs(UnmanagedType.BStr)] get; } string Parent { [return: MarshalAs(UnmanagedType.BStr)] get; } string Schema { [return: MarshalAs(UnmanagedType.BStr)] get; } void GetInfo(); void SetInfo(); Object Get([In, MarshalAs(UnmanagedType.BStr)] string bstrName); void Put([In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] Object vProp); Object GetEx([In, MarshalAs(UnmanagedType.BStr)] String bstrName); void PutEx([In, MarshalAs(UnmanagedType.U4)] int lnControlCode, [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] Object vProp); void GetInfoEx([In] Object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved); // // IAdsClass definition starts here // string PrimaryInterface { [return: MarshalAs(UnmanagedType.BStr)] get; } string CLSID { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string OID { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; } bool Abstract { get; set; } bool Auxiliary { get; set; } object MandatoryProperties { get; set; } object OptionalProperties { get; set; } object NamingProperties { get; set; } object DerivedFrom { get; set; } object AuxDerivedFrom { get; set; } object PossibleSuperiors { get; set; } object Containment { get; set; } bool Container { get; set; } string HelpFileName { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; } int HelpFileContext { [return: MarshalAs(UnmanagedType.U4)] get; [param: MarshalAs(UnmanagedType.U4)] set; } [return: MarshalAs(UnmanagedType.Interface)] object Qualifiers(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipes.Tests { /// <summary> /// Tests that cover Write and WriteAsync behaviors that are shared between /// AnonymousPipes and NamedPipes /// </summary> public abstract partial class PipeTest_Write : PipeTestBase { public virtual bool SupportsBidirectionalReadingWriting => false; [Fact] public void WriteWithNullBuffer_Throws_ArgumentNullException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.writeablePipe; Assert.True(pipe.IsConnected); Assert.True(pipe.CanWrite); // Null is an invalid Buffer AssertExtensions.Throws<ArgumentNullException>("buffer", () => pipe.Write(null, 0, 1)); AssertExtensions.Throws<ArgumentNullException>("buffer", () => { pipe.WriteAsync(null, 0, 1); }); // Buffer validity is checked before Offset AssertExtensions.Throws<ArgumentNullException>("buffer", () => pipe.Write(null, -1, 1)); AssertExtensions.Throws<ArgumentNullException>("buffer", () => { pipe.WriteAsync(null, -1, 1); }); // Buffer validity is checked before Count AssertExtensions.Throws<ArgumentNullException>("buffer", () => pipe.Write(null, -1, -1)); AssertExtensions.Throws<ArgumentNullException>("buffer", () => { pipe.WriteAsync(null, -1, -1); }); } } [Fact] public void WriteWithNegativeOffset_Throws_ArgumentOutOfRangeException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.writeablePipe; Assert.True(pipe.IsConnected); Assert.True(pipe.CanWrite); Assert.False(pipe.CanSeek); // Offset must be nonnegative AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => pipe.Write(new byte[5], -1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => { pipe.WriteAsync(new byte[5], -1, 1); }); } } [Fact] public void WriteWithNegativeCount_Throws_ArgumentOutOfRangeException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.writeablePipe; Assert.True(pipe.IsConnected); Assert.True(pipe.CanWrite); // Count must be nonnegative AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => pipe.Write(new byte[5], 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => { pipe.WriteAsync(new byte[5], 0, -1); }); } } [Fact] public void WriteWithOutOfBoundsArray_Throws_ArgumentException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.writeablePipe; Assert.True(pipe.IsConnected); Assert.True(pipe.CanWrite); // offset out of bounds AssertExtensions.Throws<ArgumentException>(null, () => pipe.Write(new byte[1], 1, 1)); // offset out of bounds for 0 count read AssertExtensions.Throws<ArgumentException>(null, () => pipe.Write(new byte[1], 2, 0)); // offset out of bounds even for 0 length buffer AssertExtensions.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], 1, 0)); // combination offset and count out of bounds AssertExtensions.Throws<ArgumentException>(null, () => pipe.Write(new byte[2], 1, 2)); // edges AssertExtensions.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], int.MaxValue, 0)); AssertExtensions.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], int.MaxValue, int.MaxValue)); AssertExtensions.Throws<ArgumentException>(null, () => pipe.Write(new byte[5], 3, 4)); // offset out of bounds AssertExtensions.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[1], 1, 1); }); // offset out of bounds for 0 count read AssertExtensions.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[1], 2, 0); }); // offset out of bounds even for 0 length buffer AssertExtensions.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], 1, 0); }); // combination offset and count out of bounds AssertExtensions.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[2], 1, 2); }); // edges AssertExtensions.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], int.MaxValue, 0); }); AssertExtensions.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], int.MaxValue, int.MaxValue); }); AssertExtensions.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[5], 3, 4); }); } } [Fact] public void ReadOnWriteOnlyPipe_Throws_NotSupportedException() { if (SupportsBidirectionalReadingWriting) { return; } using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.writeablePipe; Assert.True(pipe.IsConnected); Assert.False(pipe.CanRead); Assert.Throws<NotSupportedException>(() => pipe.Read(new byte[9], 0, 5)); Assert.Throws<NotSupportedException>(() => pipe.ReadByte()); Assert.Throws<NotSupportedException>(() => pipe.InBufferSize); Assert.Throws<NotSupportedException>(() => { pipe.ReadAsync(new byte[10], 0, 5); }); } } [Fact] public async Task WriteZeroLengthBuffer_Nop() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.writeablePipe; // Shouldn't throw pipe.Write(Array.Empty<byte>(), 0, 0); Task writeTask = pipe.WriteAsync(Array.Empty<byte>(), 0, 0); await writeTask; } } [Fact] public void WritePipeUnsupportedMembers_Throws_NotSupportedException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.writeablePipe; Assert.True(pipe.IsConnected); Assert.Throws<NotSupportedException>(() => pipe.Length); Assert.Throws<NotSupportedException>(() => pipe.SetLength(10L)); Assert.Throws<NotSupportedException>(() => pipe.Position); Assert.Throws<NotSupportedException>(() => pipe.Position = 10L); Assert.Throws<NotSupportedException>(() => pipe.Seek(10L, System.IO.SeekOrigin.Begin)); } } [Fact] public void WriteToDisposedWriteablePipe_Throws_ObjectDisposedException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.writeablePipe; pipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<ObjectDisposedException>(() => pipe.Write(buffer, 0, buffer.Length)); Assert.Throws<ObjectDisposedException>(() => pipe.WriteByte(5)); Assert.Throws<ObjectDisposedException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); }); Assert.Throws<ObjectDisposedException>(() => pipe.Flush()); Assert.Throws<ObjectDisposedException>(() => pipe.IsMessageComplete); Assert.Throws<ObjectDisposedException>(() => pipe.ReadMode); } } [Fact] public virtual void WriteToPipeWithClosedPartner_Throws_IOException() { using (ServerClientPair pair = CreateServerClientPair()) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && (pair.readablePipe is NamedPipeClientStream || pair.writeablePipe is NamedPipeClientStream)) { // On Unix, NamedPipe*Stream is implemented in term of sockets, where information // about shutdown is not immediately propagated. return; } pair.readablePipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<IOException>(() => pair.writeablePipe.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => pair.writeablePipe.WriteByte(123)); Assert.Throws<IOException>(() => { pair.writeablePipe.WriteAsync(buffer, 0, buffer.Length); }); Assert.Throws<IOException>(() => pair.writeablePipe.Flush()); } } [Fact] public async Task ValidFlush_DoesntThrow() { using (ServerClientPair pair = CreateServerClientPair()) { Task write = Task.Run(() => pair.writeablePipe.WriteByte(123)); pair.writeablePipe.Flush(); Assert.Equal(123, pair.readablePipe.ReadByte()); await write; await pair.writeablePipe.FlushAsync(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Xml; using policyDB.EntityClasses; using policyDB.CollectionClasses; using policyDB.HelperClasses; using System.IO; using PolicyBuilder.Models; namespace PolicyBuilder.Controllers { public class importController : Controller { private AttributeEntity m_literalAttribute = new AttributeEntity(); // // GET: /import/ public ActionResult Index(baseData vData) { return View(); } public ActionResult ImportBondiSVN(baseData vData) { try { policyController.DeleteEntireLibrary(vData.Library.Id); importFolder(vData); } catch (Exception ex) { TempData["message"] = ex.Message; } return RedirectToAction("Index", "policy"); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Import(baseData vData, FormCollection collection) { if (Request.Files.Count > 0) { // Save the uploaded file. string path = string.Format("~/imports/{0}.xml", Path.GetRandomFileName()); string mappedPath = Server.MapPath(path); Request.Files[0].SaveAs(mappedPath); try { string title = Path.GetFileName(Request.Files[0].FileName); if (Path.GetExtension(title) == ".xml" || Path.GetExtension(title) == ".conf") title = Path.GetFileNameWithoutExtension(title); PolicyDocumentEntity pde = importFile(vData,title, mappedPath); return RedirectToAction("EditPolicyDoc", "policy", new { id = pde.Id }); } catch (Exception ex) { TempData["error"] = ex.Message; } } else { TempData["message"] = "select a file to upload"; } return RedirectToAction("Index","policy"); } private void importFolder(baseData vData) { string importFrom = Server.MapPath("~/bondiSVN"); LibraryEntity li = vData.Library; li.Name = string.Format("Bondi SVN import at {0}", DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss")); li.Save(); DirectoryInfo di = new DirectoryInfo(importFrom); FileInfo[] files = di.GetFiles("*.*"); foreach (FileInfo fi in files) { try { importFile(vData, fi.Name, fi.FullName); } catch (Exception ex) { } } } private PolicyDocumentEntity importFile(baseData vData,string title, string filepath) { AttributeCollection acoll = new AttributeCollection(); acoll.GetMulti(AttributeFields.Name == "Literal"); if (acoll.Count == 0) throw new Exception("can't find literal attribute"); m_literalAttribute = acoll[0]; XmlDocument doc = new XmlDocument(); doc.Load(filepath); PolicyDocumentEntity pde = new PolicyDocumentEntity(); pde.LibraryId = vData.Library.Id; pde.Name = title; PolicyLinkEntity ple = new PolicyLinkEntity(); ple.Policy = new PolicyEntity(); ple.Policy.LibraryId = pde.LibraryId; pde.PolicyLink = ple; XmlNode policySet = doc.SelectSingleNode("policy-set"); if (policySet != null) loadPolicySet(1,title,ple,policySet); else { XmlNode policy = doc.SelectSingleNode("policy"); loadPolicy(1,title,ple,policy); } pde.Save(true); return pde; } private void loadPolicyBase(int idx, string title,PolicyEntity pe,XmlNode node) { XmlNode attr = node.Attributes.GetNamedItem("combine"); string combine = "deny-overrides"; if (attr != null) combine = attr.Value; CombineModeCollection cmcoll = new CombineModeCollection(); cmcoll.GetMulti((CombineModeFields.Name == combine)); if (cmcoll.Count != 1) throw new Exception(string.Format("unrecognised policy combine mode: {0}", combine)); attr = node.Attributes.GetNamedItem("description"); if (attr != null) pe.Description = attr.Value; else { if (pe.Set) pe.Description = string.Format("{0}-set-{1}", title, idx); else pe.Description = string.Format("{0}-policy-{1}", title, idx); } pe.CombineMode = cmcoll[0]; pe.Uid = Guid.NewGuid(); XmlNode target = node.SelectSingleNode("target"); loadTarget(pe,target); } private void loadPolicySet(int idx,string title,PolicyLinkEntity ple, XmlNode node) { ple.Policy.Set = true; loadPolicyBase(idx,title,ple.Policy, node); int policyCount = 0; int policySetCount = 0; foreach (XmlNode kid in node.ChildNodes) { if (kid.LocalName != "policy" && kid.LocalName != "policy-set") continue; PolicyLinkEntity pleKid = new PolicyLinkEntity(); pleKid.Order = policyCount + policySetCount; pleKid.Parent = ple; pleKid.Policy = new PolicyEntity(); pleKid.Policy.LibraryId = ple.Policy.LibraryId; if (kid.NodeType == XmlNodeType.Element && kid.LocalName == "policy") { loadPolicy(++policyCount, ple.Policy.Description, pleKid, kid); } else if (kid.NodeType == XmlNodeType.Element && kid.LocalName == "policy-set") { loadPolicySet(++policySetCount, ple.Policy.Description,pleKid, kid); } } } private void loadPolicy(int idx,string title,PolicyLinkEntity ple, XmlNode node) { loadPolicyBase(idx,title,ple.Policy, node); XmlNodeList rules = node.SelectNodes("rule"); int ruleIdx = 0; foreach (XmlNode rule in rules) { loadRule(ruleIdx, ple.Policy, rule); ruleIdx++; } } private void loadRule(int idx,PolicyEntity pe, XmlNode node) { RuleEntity re = new RuleEntity(); re.Policy = pe; re.Order = idx; string effect = "permit"; XmlNode attr = node.Attributes.GetNamedItem("effect"); if (attr != null) effect = attr.Value; EffectCollection ecoll = new EffectCollection(); ecoll.GetMulti(EffectFields.Name == effect); if (ecoll.Count != 1) throw new Exception(string.Format("unrecognised rule effect {0}", effect)); re.Effect = ecoll[0]; DecisionNodeEntity ce = new DecisionNodeEntity(); re.Condition = ce; ce.Type = constants.conditionType; ce.IsDirty = true; XmlNode condition = node.SelectSingleNode("condition"); if (condition != null) loadCondition(ce, condition); } private void loadTarget(PolicyEntity pe, XmlNode node) { pe.Target = new TargetEntity(); pe.Target.IsDirty = true; if (node != null) { XmlNodeList subjects = node.SelectNodes("subject"); foreach (XmlNode subject in subjects) loadSubject(pe.Target, subject); } } private void loadSubject(TargetEntity te, XmlNode node) { DecisionNodeEntity ce = new DecisionNodeEntity(); TargetConditionEntity tce = new TargetConditionEntity(); tce.Target = te; tce.DecisionNode = ce; loadCondition(ce, node); } private void loadCondition(DecisionNodeEntity ce,XmlNode node) { ce.Type = constants.conditionType; XmlNode attr = node.Attributes.GetNamedItem("combine"); if (attr == null || attr.Value == "and") ce.CombineAnd = true; else ce.CombineAnd = false; int matchIdx = 0; foreach (XmlNode child in node.ChildNodes) { if (child.NodeType != XmlNodeType.Element) continue; switch (child.LocalName) { case "condition": DecisionNodeEntity ceChild = new DecisionNodeEntity(); ceChild.Parent = ce; ceChild.Order = matchIdx++; loadCondition(ceChild,child); break; case "resource-match": case "environment-match": case "subject-match": loadMatch(matchIdx++, ce, child); break; } } } private void resolveAttribute(string inp, out string attr, out string extra) { int idx = inp.IndexOf('.'); if (idx == -1) idx = inp.IndexOf(':'); if (idx >= 0) { attr = inp.Substring(0, idx); extra = inp.Substring(idx + 1); } else { attr = inp; extra = string.Empty; } } private void loadMatch(int idx,DecisionNodeEntity ce, XmlNode node) { DecisionNodeEntity ame = new DecisionNodeEntity(); ame.Type = constants.attributeMatchType; ame.Parent = ce; ame.Order = idx; XmlNode attr = node.Attributes.GetNamedItem("attr"); if (attr == null) throw new Exception(string.Format("attr attribute missing from node: {0}", node.InnerXml)); AttributeCollection acoll = new AttributeCollection(); string attrVal; string attrExtra; resolveAttribute(attr.Value, out attrVal, out attrExtra); acoll.GetMulti(AttributeFields.Name == attrVal); if (acoll.Count == 0) throw new Exception(string.Format("unknown attribute {0} (toby please fix this)", attrVal)); ame.Attribute = acoll[0]; ame.Extra = attrExtra; attr = node.Attributes.GetNamedItem("match"); if (attr != null) { AttributeValueEntity ave = new AttributeValueEntity(); ave.Order = 0; ave.Attribute = m_literalAttribute; ave.Value = attr.Value; ave.AttributeMatch = ame; } else { int valueIdx = 0; foreach (XmlNode kid in node.ChildNodes) { switch (kid.NodeType) { case XmlNodeType.Text: { AttributeValueEntity ave = new AttributeValueEntity(); ave.Order = valueIdx; ave.Attribute = m_literalAttribute; ave.Value = kid.Value.Trim(); ave.AttributeMatch = ame; } break; case XmlNodeType.Element: { switch (kid.LocalName) { case "environment-attr": loadAttributeValue(valueIdx, ame, kid); break; case "resource-attr": loadAttributeValue(valueIdx, ame, kid); break; case "subject-attr": loadAttributeValue(valueIdx, ame, kid); break; default: throw new Exception(string.Format("unknown attribute value type: {0}", kid.LocalName)); break; } } break; default: break; } valueIdx++; } } } private void loadAttributeValue(int idx,DecisionNodeEntity ame, XmlNode node) { XmlNode attr = node.Attributes.GetNamedItem("attr"); if (attr == null) throw new Exception(string.Format("attr attribute missing from node: {0}", node.InnerXml)); string attrVal; string attrExtra; resolveAttribute(attr.Value, out attrVal, out attrExtra); AttributeCollection acoll = new AttributeCollection(); acoll.GetMulti(AttributeFields.Name == attrVal); if (acoll.Count == 0) throw new Exception(string.Format("unknown attribute {0} (toby please fix this)", attrVal)); AttributeValueEntity ave = new AttributeValueEntity(); ave.Order = idx; ave.Attribute = acoll[0]; ave.Value = attr.Value.Trim(); ave.AttributeMatch = ame; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. // See THIRD-PARTY-NOTICES.TXT in the project root for license information. using System.Buffers; using System.Diagnostics; namespace System.Net.Http.HPack { internal class HPackDecoder { private enum State { Ready, HeaderFieldIndex, HeaderNameIndex, HeaderNameLength, HeaderNameLengthContinue, HeaderName, HeaderValueLength, HeaderValueLengthContinue, HeaderValue, DynamicTableSizeUpdate } public const int DefaultHeaderTableSize = 4096; public const int DefaultStringOctetsSize = 4096; public const int DefaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength * 1024; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.1 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 1 | Index (7+) | // +---+---------------------------+ private const byte IndexedHeaderFieldMask = 0x80; private const byte IndexedHeaderFieldRepresentation = 0x80; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.1 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 1 | Index (6+) | // +---+---+-----------------------+ private const byte LiteralHeaderFieldWithIncrementalIndexingMask = 0xc0; private const byte LiteralHeaderFieldWithIncrementalIndexingRepresentation = 0x40; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.2 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 0 | Index (4+) | // +---+---+-----------------------+ private const byte LiteralHeaderFieldWithoutIndexingMask = 0xf0; private const byte LiteralHeaderFieldWithoutIndexingRepresentation = 0x00; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.3 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 1 | Index (4+) | // +---+---+-----------------------+ private const byte LiteralHeaderFieldNeverIndexedMask = 0xf0; private const byte LiteralHeaderFieldNeverIndexedRepresentation = 0x10; // http://httpwg.org/specs/rfc7541.html#rfc.section.6.3 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 1 | Max size (5+) | // +---+---------------------------+ private const byte DynamicTableSizeUpdateMask = 0xe0; private const byte DynamicTableSizeUpdateRepresentation = 0x20; // http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | H | String Length (7+) | // +---+---------------------------+ private const byte HuffmanMask = 0x80; private const int IndexedHeaderFieldPrefix = 7; private const int LiteralHeaderFieldWithIncrementalIndexingPrefix = 6; private const int LiteralHeaderFieldWithoutIndexingPrefix = 4; private const int LiteralHeaderFieldNeverIndexedPrefix = 4; private const int DynamicTableSizeUpdatePrefix = 5; private const int StringLengthPrefix = 7; private readonly int _maxDynamicTableSize; private readonly int _maxResponseHeadersLength; private readonly DynamicTable _dynamicTable; private readonly IntegerDecoder _integerDecoder = new IntegerDecoder(); private byte[] _stringOctets; private byte[] _headerNameOctets; private byte[] _headerValueOctets; private State _state = State.Ready; private byte[] _headerName; private int _stringIndex; private int _stringLength; private int _headerNameLength; private int _headerValueLength; private bool _index; private bool _huffman; private bool _headersObserved; public HPackDecoder(int maxDynamicTableSize = DefaultHeaderTableSize, int maxResponseHeadersLength = DefaultMaxResponseHeadersLength) : this(maxDynamicTableSize, maxResponseHeadersLength, new DynamicTable(maxDynamicTableSize)) { } // For testing. internal HPackDecoder(int maxDynamicTableSize, int maxResponseHeadersLength, DynamicTable dynamicTable) { _maxDynamicTableSize = maxDynamicTableSize; _maxResponseHeadersLength = maxResponseHeadersLength; _dynamicTable = dynamicTable; _stringOctets = new byte[DefaultStringOctetsSize]; _headerNameOctets = new byte[DefaultStringOctetsSize]; _headerValueOctets = new byte[DefaultStringOctetsSize]; } public void Decode(in ReadOnlySequence<byte> data, bool endHeaders, IHttpHeadersHandler handler) { foreach (ReadOnlyMemory<byte> segment in data) { DecodeInternal(segment.Span, endHeaders, handler); } CheckIncompleteHeaderBlock(endHeaders); } public void Decode(ReadOnlySpan<byte> data, bool endHeaders, IHttpHeadersHandler handler) { DecodeInternal(data, endHeaders, handler); CheckIncompleteHeaderBlock(endHeaders); } private void DecodeInternal(ReadOnlySpan<byte> data, bool endHeaders, IHttpHeadersHandler handler) { int intResult; for (int i = 0; i < data.Length; i++) { byte b = data[i]; switch (_state) { case State.Ready: // TODO: Instead of masking and comparing each prefix value, // consider doing a 16-way switch on the first four bits (which is the max prefix size). // Look at this once we have more concrete perf data. if ((b & IndexedHeaderFieldMask) == IndexedHeaderFieldRepresentation) { _headersObserved = true; int val = b & ~IndexedHeaderFieldMask; if (_integerDecoder.BeginTryDecode((byte)val, IndexedHeaderFieldPrefix, out intResult)) { OnIndexedHeaderField(intResult, handler); } else { _state = State.HeaderFieldIndex; } } else if ((b & LiteralHeaderFieldWithIncrementalIndexingMask) == LiteralHeaderFieldWithIncrementalIndexingRepresentation) { _headersObserved = true; _index = true; int val = b & ~LiteralHeaderFieldWithIncrementalIndexingMask; if (val == 0) { _state = State.HeaderNameLength; } else if (_integerDecoder.BeginTryDecode((byte)val, LiteralHeaderFieldWithIncrementalIndexingPrefix, out intResult)) { OnIndexedHeaderName(intResult); } else { _state = State.HeaderNameIndex; } } else if ((b & LiteralHeaderFieldWithoutIndexingMask) == LiteralHeaderFieldWithoutIndexingRepresentation) { _headersObserved = true; _index = false; int val = b & ~LiteralHeaderFieldWithoutIndexingMask; if (val == 0) { _state = State.HeaderNameLength; } else if (_integerDecoder.BeginTryDecode((byte)val, LiteralHeaderFieldWithoutIndexingPrefix, out intResult)) { OnIndexedHeaderName(intResult); } else { _state = State.HeaderNameIndex; } } else if ((b & LiteralHeaderFieldNeverIndexedMask) == LiteralHeaderFieldNeverIndexedRepresentation) { _headersObserved = true; _index = false; int val = b & ~LiteralHeaderFieldNeverIndexedMask; if (val == 0) { _state = State.HeaderNameLength; } else if (_integerDecoder.BeginTryDecode((byte)val, LiteralHeaderFieldNeverIndexedPrefix, out intResult)) { OnIndexedHeaderName(intResult); } else { _state = State.HeaderNameIndex; } } else if ((b & DynamicTableSizeUpdateMask) == DynamicTableSizeUpdateRepresentation) { // https://tools.ietf.org/html/rfc7541#section-4.2 // This dynamic table size // update MUST occur at the beginning of the first header block // following the change to the dynamic table size. if (_headersObserved) { throw new HPackDecodingException(SR.net_http_hpack_late_dynamic_table_size_update); } if (_integerDecoder.BeginTryDecode((byte)(b & ~DynamicTableSizeUpdateMask), DynamicTableSizeUpdatePrefix, out intResult)) { SetDynamicHeaderTableSize(intResult); } else { _state = State.DynamicTableSizeUpdate; } } else { // Can't happen Debug.Fail("Unreachable code"); throw new InvalidOperationException("Unreachable code."); } break; case State.HeaderFieldIndex: if (_integerDecoder.TryDecode(b, out intResult)) { OnIndexedHeaderField(intResult, handler); } break; case State.HeaderNameIndex: if (_integerDecoder.TryDecode(b, out intResult)) { OnIndexedHeaderName(intResult); } break; case State.HeaderNameLength: _huffman = (b & HuffmanMask) != 0; if (_integerDecoder.BeginTryDecode((byte)(b & ~HuffmanMask), StringLengthPrefix, out intResult)) { if (intResult == 0) { throw new HPackDecodingException(SR.Format(SR.net_http_invalid_response_header_name, "")); } OnStringLength(intResult, nextState: State.HeaderName); } else { _state = State.HeaderNameLengthContinue; } break; case State.HeaderNameLengthContinue: if (_integerDecoder.TryDecode(b, out intResult)) { // IntegerDecoder disallows overlong encodings, where an integer is encoded with more bytes than is strictly required. // 0 should always be represented by a single byte, so we shouldn't need to check for it in the continuation case. Debug.Assert(intResult != 0, "A header name length of 0 should never be encoded with a continuation byte."); OnStringLength(intResult, nextState: State.HeaderName); } break; case State.HeaderName: _stringOctets[_stringIndex++] = b; if (_stringIndex == _stringLength) { OnString(nextState: State.HeaderValueLength); } break; case State.HeaderValueLength: _huffman = (b & HuffmanMask) != 0; if (_integerDecoder.BeginTryDecode((byte)(b & ~HuffmanMask), StringLengthPrefix, out intResult)) { OnStringLength(intResult, nextState: State.HeaderValue); if (intResult == 0) { ProcessHeaderValue(handler); } } else { _state = State.HeaderValueLengthContinue; } break; case State.HeaderValueLengthContinue: if (_integerDecoder.TryDecode(b, out intResult)) { // IntegerDecoder disallows overlong encodings where an integer is encoded with more bytes than is strictly required. // 0 should always be represented by a single byte, so we shouldn't need to check for it in the continuation case. Debug.Assert(intResult != 0, "A header value length of 0 should never be encoded with a continuation byte."); OnStringLength(intResult, nextState: State.HeaderValue); } break; case State.HeaderValue: _stringOctets[_stringIndex++] = b; if (_stringIndex == _stringLength) { ProcessHeaderValue(handler); } break; case State.DynamicTableSizeUpdate: if (_integerDecoder.TryDecode(b, out intResult)) { SetDynamicHeaderTableSize(intResult); _state = State.Ready; } break; default: // Can't happen Debug.Fail("HPACK decoder reach an invalid state"); throw new InternalException(_state); } } } private void CheckIncompleteHeaderBlock(bool endHeaders) { if (endHeaders) { if (_state != State.Ready) { throw new HPackDecodingException(SR.net_http_hpack_incomplete_header_block); } _headersObserved = false; } } private void ProcessHeaderValue(IHttpHeadersHandler handler) { OnString(nextState: State.Ready); var headerNameSpan = new Span<byte>(_headerName, 0, _headerNameLength); var headerValueSpan = new Span<byte>(_headerValueOctets, 0, _headerValueLength); handler?.OnHeader(headerNameSpan, headerValueSpan); if (_index) { _dynamicTable.Insert(headerNameSpan, headerValueSpan); } } public void CompleteDecode() { if (_state != State.Ready) { // Incomplete header block throw new HPackDecodingException(SR.net_http_hpack_unexpected_end); } } private void OnIndexedHeaderField(int index, IHttpHeadersHandler handler) { HeaderField header = GetHeader(index); handler?.OnHeader(header.Name, header.Value); _state = State.Ready; } private void OnIndexedHeaderName(int index) { HeaderField header = GetHeader(index); _headerName = header.Name; _headerNameLength = header.Name.Length; _state = State.HeaderValueLength; } private void OnStringLength(int length, State nextState) { if (length > _stringOctets.Length) { if (length > _maxResponseHeadersLength) { throw new HPackDecodingException(SR.Format(SR.net_http_response_headers_exceeded_length, _maxResponseHeadersLength)); } _stringOctets = new byte[Math.Max(length, _stringOctets.Length * 2)]; } _stringLength = length; _stringIndex = 0; _state = nextState; } private void OnString(State nextState) { int Decode(ref byte[] dst) { if (_huffman) { return Huffman.Decode(new ReadOnlySpan<byte>(_stringOctets, 0, _stringLength), ref dst); } else { if (dst.Length < _stringLength) { dst = new byte[Math.Max(_stringLength, dst.Length * 2)]; } Buffer.BlockCopy(_stringOctets, 0, dst, 0, _stringLength); return _stringLength; } } try { if (_state == State.HeaderName) { _headerNameLength = Decode(ref _headerNameOctets); _headerName = _headerNameOctets; } else { _headerValueLength = Decode(ref _headerValueOctets); } } catch (HuffmanDecodingException ex) { throw new HPackDecodingException(SR.net_http_hpack_huffman_decode_failed, ex); } _state = nextState; } private HeaderField GetHeader(int index) { try { return index <= StaticTable.Count ? StaticTable.Get(index - 1) : _dynamicTable[index - StaticTable.Count - 1]; } catch (IndexOutOfRangeException) { // Header index out of range. throw new HPackDecodingException(SR.Format(SR.net_http_hpack_invalid_index, index)); } } private void SetDynamicHeaderTableSize(int size) { if (size > _maxDynamicTableSize) { throw new HPackDecodingException(SR.Format(SR.net_http_hpack_large_table_size_update, size, _maxDynamicTableSize)); } _dynamicTable.Resize(size); } } }
// 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 Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public class InstanceFieldLayoutTests { TestTypeSystemContext _context; ModuleDesc _testModule; ModuleDesc _ilTestModule; public InstanceFieldLayoutTests() { _context = new TestTypeSystemContext(TargetArchitecture.X64); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); _testModule = systemModule; _ilTestModule = _context.CreateModuleForSimpleName("ILTestAssembly"); } [Fact] public void TestExplicitLayout() { MetadataType t = _testModule.GetType("Explicit", "Class1"); // With 64bit, there should be 8 bytes for the System.Object EE data pointer + // 10 bytes up until the offset of the char field + the char size of 2 + we // round up the whole instance size to the next pointer size (+4) = 24 Assert.Equal(24, t.InstanceByteCount.AsInt); foreach (var field in t.GetFields()) { if (field.IsStatic) continue; if (field.Name == "Bar") { // Bar has explicit offset 4 and is in a class (with S.O size overhead of <pointer size>) // Therefore it should have offset 4 + 8 = 12 Assert.Equal(12, field.Offset.AsInt); } else if (field.Name == "Baz") { // Baz has explicit offset 10. 10 + 8 = 18 Assert.Equal(18, field.Offset.AsInt); } else { Assert.True(false); } } } [Fact] public void TestExplicitLayoutThatIsEmpty() { var explicitEmptyClassType = _testModule.GetType("Explicit", "ExplicitEmptyClass"); // ExplicitEmpty class has 8 from System.Object overhead = 8 Assert.Equal(8, explicitEmptyClassType.InstanceByteCount.AsInt); var explicitEmptyStructType = _testModule.GetType("Explicit", "ExplicitEmptyStruct"); // ExplicitEmpty class has 0 bytes in it... so instance field size gets pushed up to 1. Assert.Equal(1, explicitEmptyStructType.InstanceFieldSize.AsInt); } [Fact] public void TestExplicitTypeLayoutWithSize() { var explicitSizeType = _testModule.GetType("Explicit", "ExplicitSize"); Assert.Equal(48, explicitSizeType.InstanceByteCount.AsInt); } [Fact] public void TestExplicitTypeLayoutWithInheritance() { MetadataType class2Type = _testModule.GetType("Explicit", "Class2"); // Class1 has size 24 which Class2 inherits from. Class2 adds a byte at offset 20, so + 21 // = 45, rounding up to the next pointer size = 48 Assert.Equal(48, class2Type.InstanceByteCount.AsInt); foreach (var f in class2Type.GetFields()) { if (f.IsStatic) continue; if (f.Name == "Lol") { // First field after base class, with offset 0 so it should lie on the byte count of // the base class = 24 Assert.Equal(24, f.Offset.AsInt); } else if (f.Name == "Omg") { // Offset 20 from base class byte count = 44 Assert.Equal(44, f.Offset.AsInt); } else { Assert.True(false); } } } [Fact] public void TestSequentialTypeLayout() { MetadataType class1Type = _testModule.GetType("Sequential", "Class1"); // Byte count // Base Class 8 // MyInt 4 // MyBool 1 + 1 padding // MyChar 2 // MyString 8 // MyByteArray 8 // MyClass1SelfRef 8 // ------------------- // 40 (0x28) Assert.Equal(0x28, class1Type.InstanceByteCount.AsInt); foreach (var f in class1Type.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyInt": Assert.Equal(0x8, f.Offset.AsInt); break; case "MyBool": Assert.Equal(0xC, f.Offset.AsInt); break; case "MyChar": Assert.Equal(0xE, f.Offset.AsInt); break; case "MyString": Assert.Equal(0x10, f.Offset.AsInt); break; case "MyByteArray": Assert.Equal(0x18, f.Offset.AsInt); break; case "MyClass1SelfRef": Assert.Equal(0x20, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestSequentialTypeLayoutInheritance() { MetadataType class2Type = _testModule.GetType("Sequential", "Class2"); // Byte count // Base Class 40 // MyInt2 4 + 4 byte padding to make class size % pointer size == 0 // ------------------- // 48 (0x30) Assert.Equal(0x30, class2Type.InstanceByteCount.AsInt); foreach (var f in class2Type.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyInt2": Assert.Equal(0x28, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestSequentialTypeLayoutStruct() { MetadataType struct0Type = _testModule.GetType("Sequential", "Struct0"); // Byte count // bool b1 1 // bool b2 1 // bool b3 1 + 1 padding for int alignment // int i1 4 // string s1 8 // ------------------- // 16 (0x10) Assert.Equal(0x10, struct0Type.InstanceByteCount.AsInt); foreach (var f in struct0Type.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "b1": Assert.Equal(0x0, f.Offset.AsInt); break; case "b2": Assert.Equal(0x1, f.Offset.AsInt); break; case "b3": Assert.Equal(0x2, f.Offset.AsInt); break; case "i1": Assert.Equal(0x4, f.Offset.AsInt); break; case "s1": Assert.Equal(0x8, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] // Test that when a struct is used as a field, we use its instance byte size as the size (ie, treat it // as a value type) and not a pointer size. public void TestSequentialTypeLayoutStructEmbedded() { MetadataType struct1Type = _testModule.GetType("Sequential", "Struct1"); // Byte count // struct MyStruct0 16 // bool MyBool 1 // ----------------------- // 24 (0x18) Assert.Equal(0x18, struct1Type.InstanceByteCount.AsInt); foreach (var f in struct1Type.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyStruct0": Assert.Equal(0x0, f.Offset.AsInt); break; case "MyBool": Assert.Equal(0x10, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoLayoutStruct() { MetadataType structWithIntCharType = _testModule.GetType("Auto", "StructWithIntChar"); // Byte count // MyStructInt 4 // MyStructChar 2 // ------------------- // 8 (0x08) Assert.Equal(0x08, structWithIntCharType.InstanceByteCount.AsInt); foreach (var f in structWithIntCharType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyStructInt": Assert.Equal(0x00, f.Offset.AsInt); break; case "MyStructChar": Assert.Equal(0x04, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutClassContainingStructs() { MetadataType classContainingStructsType = _testModule.GetType("Auto", "ClassContainingStructs"); // Byte count // Base Class 8 // MyByteArray 8 // MyString1 8 // MyDouble 8 // MyLong 8 // MyInt 4 // MyChar1 2 // MyBool1 1 // MyBool2 1 // MyStructWithBool 1 + 3 to align up to the next multiple of 4 after placing a value class // 4 byte padding to make offset % pointer size == 0 before placing the next value class // MyStructWithIntChar 6 + 2 to align up to the next multiple of 4 after placing a value class // MyStructWithChar 2 + 2 to align up to the next multiple of 4 after placing a value class + 4 byte padding to make class size % pointer size == 0 // ------------------- // 72 (0x48) Assert.Equal(0x48, classContainingStructsType.InstanceByteCount.AsInt); foreach (var f in classContainingStructsType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyByteArray": Assert.Equal(0x08, f.Offset.AsInt); break; case "MyString1": Assert.Equal(0x10, f.Offset.AsInt); break; case "MyDouble": Assert.Equal(0x18, f.Offset.AsInt); break; case "MyLong": Assert.Equal(0x20, f.Offset.AsInt); break; case "MyInt": Assert.Equal(0x28, f.Offset.AsInt); break; case "MyChar1": Assert.Equal(0x2C, f.Offset.AsInt); break; case "MyBool1": Assert.Equal(0x2E, f.Offset.AsInt); break; case "MyBool2": Assert.Equal(0x2F, f.Offset.AsInt); break; case "MyStructWithBool": Assert.Equal(0x30, f.Offset.AsInt); break; case "MyStructWithIntChar": Assert.Equal(0x38, f.Offset.AsInt); break; case "MyStructWithChar": Assert.Equal(0x40, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutBaseClass7BytesRemaining() { MetadataType baseClass7BytesRemainingType = _testModule.GetType("Auto", "BaseClass7BytesRemaining"); // Byte count // Base Class 8 // MyByteArray1 8 // MyString1 8 // MyDouble1 8 // MyLong1 8 // MyBool1 1 + 7 byte padding to make class size % pointer size == 0 // ------------------- // 48 (0x30) Assert.Equal(0x30, baseClass7BytesRemainingType.InstanceByteCount.AsInt); foreach (var f in baseClass7BytesRemainingType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyByteArray1": Assert.Equal(0x08, f.Offset.AsInt); break; case "MyString1": Assert.Equal(0x10, f.Offset.AsInt); break; case "MyDouble1": Assert.Equal(0x18, f.Offset.AsInt); break; case "MyLong1": Assert.Equal(0x20, f.Offset.AsInt); break; case "MyBool1": Assert.Equal(0x28, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutBaseClass4BytesRemaining() { MetadataType baseClass4BytesRemainingType = _testModule.GetType("Auto", "BaseClass4BytesRemaining"); // Byte count // Base Class 8 // MyLong1 8 // MyUint1 4 + 4 byte padding to make class size % pointer size == 0 // ------------------- // 24 (0x18) Assert.Equal(0x18, baseClass4BytesRemainingType.InstanceByteCount.AsInt); foreach (var f in baseClass4BytesRemainingType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyLong1": Assert.Equal(0x08, f.Offset.AsInt); break; case "MyUint1": Assert.Equal(0x10, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutBaseClass3BytesRemaining() { MetadataType baseClass3BytesRemainingType = _testModule.GetType("Auto", "BaseClass3BytesRemaining"); // Byte count // Base Class 8 // MyString1 8 // MyInt1 4 // MyBool1 1 + 3 byte padding to make class size % pointer size == 0 // ------------------- // 24 (0x18) Assert.Equal(0x18, baseClass3BytesRemainingType.InstanceByteCount.AsInt); foreach (var f in baseClass3BytesRemainingType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "MyString1": Assert.Equal(0x08, f.Offset.AsInt); break; case "MyInt1": Assert.Equal(0x10, f.Offset.AsInt); break; case "MyBool1": Assert.Equal(0x14, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutOptimizePartial() { MetadataType optimizePartialType = _testModule.GetType("Auto", "OptimizePartial"); // Byte count // Base Class 41 (unaligned) // OptBool 1 // OptChar 2 + 4 byte padding to make class size % pointer size == 0 // NoOptString 8 // NoOptLong 8 // ------------------- // 64 (0x40) Assert.Equal(0x40, optimizePartialType.InstanceByteCount.AsInt); foreach (var f in optimizePartialType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "OptBool": Assert.Equal(0x29, f.Offset.AsInt); break; case "OptChar": Assert.Equal(0x2A, f.Offset.AsInt); break; case "NoOptString": Assert.Equal(0x30, f.Offset.AsInt); break; case "NoOptLong": Assert.Equal(0x38, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutOptimize7Bools() { MetadataType optimize7BoolsType = _testModule.GetType("Auto", "Optimize7Bools"); // Byte count // Base Class 41 (unaligned) // OptBool1 1 // OptBool2 1 // OptBool3 1 // OptBool4 1 // OptBool5 1 // OptBool6 1 // OptBool7 1 // NoOptString 8 // NoOptBool8 1 + 7 byte padding to make class size % pointer size == 0 // ------------------- // 64 (0x40) Assert.Equal(0x40, optimize7BoolsType.InstanceByteCount.AsInt); foreach (var f in optimize7BoolsType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "OptBool1": Assert.Equal(0x29, f.Offset.AsInt); break; case "OptBool2": Assert.Equal(0x2A, f.Offset.AsInt); break; case "OptBool3": Assert.Equal(0x2B, f.Offset.AsInt); break; case "OptBool4": Assert.Equal(0x2C, f.Offset.AsInt); break; case "OptBool5": Assert.Equal(0x2D, f.Offset.AsInt); break; case "OptBool6": Assert.Equal(0x2E, f.Offset.AsInt); break; case "OptBool7": Assert.Equal(0x2F, f.Offset.AsInt); break; case "NoOptString": Assert.Equal(0x30, f.Offset.AsInt); break; case "NoOptBool8": Assert.Equal(0x38, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutOptimizeAlignedFields() { MetadataType optimizeAlignedFieldsType = _testModule.GetType("Auto", "OptimizeAlignedFields"); // Byte count // Base Class 41 (unaligned) // OptBool1 1 // OptChar1 2 // OptChar2 2 // OptBool2 1 // OptBool3 1 // NoOptString 8 // NoOptBool4 1 + 7 byte padding to make class size % pointer size == 0 // ------------------- // 64 (0x40) Assert.Equal(0x40, optimizeAlignedFieldsType.InstanceByteCount.AsInt); foreach (var f in optimizeAlignedFieldsType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "OptBool1": Assert.Equal(0x29, f.Offset.AsInt); break; case "OptChar1": Assert.Equal(0x2A, f.Offset.AsInt); break; case "OptChar2": Assert.Equal(0x2C, f.Offset.AsInt); break; case "OptBool2": Assert.Equal(0x2E, f.Offset.AsInt); break; case "OptBool3": Assert.Equal(0x2F, f.Offset.AsInt); break; case "NoOptString": Assert.Equal(0x30, f.Offset.AsInt); break; case "NoOptBool4": Assert.Equal(0x38, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutOptimizeLargestField() { MetadataType optimizeLargestFieldType = _testModule.GetType("Auto", "OptimizeLargestField"); // Byte count // Base Class 20 (unaligned) // OptInt 4 // NoOptString 8 // NoOptChar 2 // NoOptBool 1 + 5 byte padding to make class size % pointer size == 0 // ------------------- // 40 (0x28) Assert.Equal(0x28, optimizeLargestFieldType.InstanceByteCount.AsInt); foreach (var f in optimizeLargestFieldType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "OptInt": Assert.Equal(0x14, f.Offset.AsInt); break; case "NoOptString": Assert.Equal(0x18, f.Offset.AsInt); break; case "NoOptChar": Assert.Equal(0x20, f.Offset.AsInt); break; case "NoOptBool": Assert.Equal(0x22, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutNoOptimizeMisaligned() { MetadataType noOptimizeMisalignedType = _testModule.GetType("Auto", "NoOptimizeMisaligned"); // Byte count // Base Class 21 (unaligned) + 3 byte padding to make class size % pointer size == 0 // NoOptString 8 // NoOptInt 4 // NoOptChar 2 + 2 byte padding to make class size % pointer size == 0 // ------------------- // 40 (0x28) Assert.Equal(0x28, noOptimizeMisalignedType.InstanceByteCount.AsInt); foreach (var f in noOptimizeMisalignedType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "NoOptString": Assert.Equal(0x18, f.Offset.AsInt); break; case "NoOptInt": Assert.Equal(0x20, f.Offset.AsInt); break; case "NoOptChar": Assert.Equal(0x24, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestAutoTypeLayoutNoOptimizeCharAtSize2Alignment() { MetadataType noOptimizeCharAtSize2AlignmentType = _testModule.GetType("Auto", "NoOptimizeCharAtSize2Alignment"); // Byte count // Base Class 21 (unaligned) + 1 byte padding to align char // NoOptChar 2 // ------------------- // 24 (0x18) Assert.Equal(0x18, noOptimizeCharAtSize2AlignmentType.InstanceByteCount.AsInt); foreach (var f in noOptimizeCharAtSize2AlignmentType.GetFields()) { if (f.IsStatic) continue; switch (f.Name) { case "NoOptChar": Assert.Equal(0x16, f.Offset.AsInt); break; default: Assert.True(false); break; } } } [Fact] public void TestTypeContainsGCPointers() { MetadataType type = _testModule.GetType("ContainsGCPointers", "NoPointers"); Assert.False(type.ContainsGCPointers); type = _testModule.GetType("ContainsGCPointers", "StillNoPointers"); Assert.False(type.ContainsGCPointers); type = _testModule.GetType("ContainsGCPointers", "ClassNoPointers"); Assert.False(type.ContainsGCPointers); type = _testModule.GetType("ContainsGCPointers", "HasPointers"); Assert.True(type.ContainsGCPointers); type = _testModule.GetType("ContainsGCPointers", "FieldHasPointers"); Assert.True(type.ContainsGCPointers); type = _testModule.GetType("ContainsGCPointers", "ClassHasPointers"); Assert.True(type.ContainsGCPointers); type = _testModule.GetType("ContainsGCPointers", "BaseClassHasPointers"); Assert.True(type.ContainsGCPointers); type = _testModule.GetType("ContainsGCPointers", "ClassHasIntArray"); Assert.True(type.ContainsGCPointers); type = _testModule.GetType("ContainsGCPointers", "ClassHasArrayOfClassType"); Assert.True(type.ContainsGCPointers); } [Fact] public void TestByRefLikeTypes() { { DefType type = _context.GetWellKnownType(WellKnownType.TypedReference); Assert.True(type.IsByRefLike); } { DefType type = _context.GetWellKnownType(WellKnownType.ByReferenceOfT); Assert.True(type.IsByRefLike); } { DefType type = _testModule.GetType("IsByRefLike", "ByRefLikeStruct"); Assert.True(type.IsByRefLike); } { DefType type = _testModule.GetType("IsByRefLike", "NotByRefLike"); Assert.False(type.IsByRefLike); } } [Fact] public void TestInvalidByRefLikeTypes() { { DefType type = _ilTestModule.GetType("IsByRefLike", "InvalidClass1"); Assert.Throws<TypeSystemException.TypeLoadException>(() => type.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields)); } { DefType type = _ilTestModule.GetType("IsByRefLike", "InvalidClass2"); Assert.Throws<TypeSystemException.TypeLoadException>(() => type.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields)); } { DefType type = _ilTestModule.GetType("IsByRefLike", "InvalidStruct"); Assert.Throws<TypeSystemException.TypeLoadException>(() => type.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields)); } } } }
// Byte related function helper. // Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors. // // 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. /* * Created by SharpDevelop. * User: lextm * Date: 2008/5/1 * Time: 12:31 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace Lextm.SharpSnmpLib { /// <summary> /// Helper utility that performs data conversions from/to bytes. /// </summary> public static class ByteTool { /// <summary> /// Converts decimal string to bytes. /// </summary> /// <param name="description">The decimal string.</param> /// <returns>The converted bytes.</returns> /// <remarks><c>" 16 18 "</c> is converted to <c>new byte[] { 0x10, 0x12 }</c>.</remarks> public static byte[] ConvertDecimal(string description) { if (description == null) { throw new ArgumentNullException("description"); } var result = new List<byte>(); var content = description.Trim().Split(new[] { ' ' }); foreach (var part in content) { #if CF result.Add(byte.Parse(part, NumberStyles.Integer, CultureInfo.InvariantCulture)); #else byte temp; if (byte.TryParse(part, out temp)) { result.Add(temp); } #endif } return result.ToArray(); } /// <summary> /// Converts the byte string to bytes. /// </summary> /// <param name="description">The HEX string.</param> /// <returns>The converted bytes.</returns> /// <remarks><c>"80 00"</c> is converted to <c>new byte[] { 0x80, 0x00 }</c>.</remarks> public static byte[] Convert(IEnumerable<char> description) { if (description == null) { throw new ArgumentNullException("description"); } var result = new List<byte>(); var buffer = new StringBuilder(2); foreach (var c in description.Where(c => !char.IsWhiteSpace(c))) { if (!char.IsLetterOrDigit(c)) { throw new ArgumentException("illegal character found", "description"); } buffer.Append(c); if (buffer.Length != 2) { continue; } #if CF result.Add(byte.Parse(buffer.ToString(), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture)); #else byte temp; if (byte.TryParse(buffer.ToString(), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out temp)) { result.Add(temp); } #endif buffer.Length = 0; } if (buffer.Length != 0) { throw new ArgumentException("not a complete byte string", "description"); } return result.ToArray(); } /// <summary> /// Converts bytes to a byte string. /// </summary> /// <param name="buffer">The bytes.</param> /// <returns>The formatted string.</returns> /// <remarks><c>new byte[] { 0x80, 0x00 }</c> is converted to <c>"80 00"</c>.</remarks> public static string Convert(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } return BitConverter.ToString(buffer).Replace('-', ' '); } internal static byte[] ParseItems(params ISnmpData[] items) { if (items == null) { throw new ArgumentNullException("items"); } using (var result = new MemoryStream()) { foreach (var item in items) { if (item == null) { throw new ArgumentException("item in the collection cannot be null", "items"); } item.AppendBytesTo(result); } return result.ToArray(); } } internal static byte[] ParseItems(IEnumerable<ISnmpData> items) { if (items == null) { throw new ArgumentNullException("items"); } using (var result = new MemoryStream()) { foreach (var item in items) { item.AppendBytesTo(result); } return result.ToArray(); } } internal static byte[] GetRawBytes(IEnumerable<byte> orig, bool negative) { if (orig == null) { throw new ArgumentNullException("orig"); } byte flag; byte sign; if (negative) { flag = 0xff; sign = 0x80; } else { flag = 0x0; sign = 0x0; } var list = new List<byte>(orig); while (list.Count > 1) { if (list[list.Count - 1] == flag) { list.RemoveAt(list.Count - 1); } else { break; } } // if sign bit is not correct, add an extra byte if ((list[list.Count - 1] & 0x80) != sign) { list.Add(flag); } list.Reverse(); return list.ToArray(); } /// <summary> /// Packs parts into a single message body. /// </summary> /// <param name="length">Message length.</param> /// <param name="version">Message version.</param> /// <param name="header">Header.</param> /// <param name="parameters">Security parameters.</param> /// <param name="data">Scope data.</param> /// <returns>The <see cref="Sequence" /> object that represents the message body.</returns> public static Sequence PackMessage(byte[] length, VersionCode version, ISegment header, ISegment parameters, ISnmpData data) { if (header == null) { throw new ArgumentNullException("header"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (data == null) { throw new ArgumentNullException("data"); } var items = new[] { new Integer32((int)version), header.GetData(version), parameters.GetData(version), data }; return new Sequence(length, items); } internal static byte[] WritePayloadLength(this int length) // excluding initial octet { if (length < 0) { throw new ArgumentException("length cannot be negative", "length"); } var stream = new MemoryStream(); if (length < 127) { stream.WriteByte((byte)length); return stream.ToArray(); } var c = new byte[16]; var j = 0; while (length > 0) { c[j++] = (byte)(length & 0xff); length = length >> 8; } stream.WriteByte((byte)(0x80 | j)); while (j > 0) { int x = c[--j]; stream.WriteByte((byte)x); } return stream.ToArray(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Serialization; using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.Pipelines; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { [ServiceLocator(Default = typeof(SvnCommandManager))] public interface ISvnCommandManager : IAgentService { /// <summary> /// Initializes svn command path and execution environment /// </summary> /// <param name="context">The build commands' execution context</param> /// <param name="endpoint">The Subversion server endpoint providing URL, username/password, and untrasted certs acceptace information</param> /// <param name="cancellationToken">The cancellation token used to stop svn command execution</param> void Init( IExecutionContext context, ServiceEndpoint endpoint, CancellationToken cancellationToken); /// <summary> /// Initializes svn command path and execution environment /// </summary> /// <param name="context">The build commands' execution context</param> /// <param name="repository">The Subversion repository resource providing URL, referenced service endpoint information</param> /// <param name="cancellationToken">The cancellation token used to stop svn command execution</param> void Init( IExecutionContext context, RepositoryResource repository, CancellationToken cancellationToken); /// <summary> /// svn info URL --depth empty --revision <sourceRevision> --xml --username <user> --password <password> --non-interactive [--trust-server-cert] /// </summary> /// <param name="serverPath"></param> /// <param name="sourceRevision"></param> /// <returns></returns> Task<long> GetLatestRevisionAsync(string serverPath, string sourceRevision); /// <summary> /// Removes unused and duplicate mappings. /// </summary> /// <param name="allMappings"></param> /// <returns></returns> Dictionary<string, SvnMappingDetails> NormalizeMappings(List<SvnMappingDetails> allMappings); /// <summary> /// Normalizes path separator for server and local paths. /// </summary> /// <param name="path"></param> /// <param name="pathSeparator"></param> /// <param name="altPathSeparator"></param> /// <returns></returns> string NormalizeRelativePath(string path, char pathSeparator, char altPathSeparator); /// <summary> /// Detects old mappings (if any) and refreshes the SVN working copies to match the new mappings. /// </summary> /// <param name="rootPath"></param> /// <param name="distinctMappings"></param> /// <param name="cleanRepository"></param> /// <param name="sourceBranch"></param> /// <param name="revision"></param> /// <returns></returns> Task<string> UpdateWorkspace(string rootPath, Dictionary<string, SvnMappingDetails> distinctMappings, bool cleanRepository, string sourceBranch, string revision); /// <summary> /// Finds a local path the provided server path is mapped to. /// </summary> /// <param name="serverPath"></param> /// <param name="rootPath"></param> /// <returns></returns> string ResolveServerPath(string serverPath, string rootPath); } public class SvnCommandManager : AgentService, ISvnCommandManager { public void Init( IExecutionContext context, ServiceEndpoint endpoint, CancellationToken cancellationToken) { // Validation. ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(endpoint, nameof(endpoint)); ArgUtil.NotNull(cancellationToken, nameof(cancellationToken)); ArgUtil.NotNull(endpoint.Url, nameof(endpoint.Url)); ArgUtil.Equal(true, endpoint.Url.IsAbsoluteUri, nameof(endpoint.Url.IsAbsoluteUri)); ArgUtil.NotNull(endpoint.Data, nameof(endpoint.Data)); ArgUtil.NotNull(endpoint.Authorization, nameof(endpoint.Authorization)); ArgUtil.NotNull(endpoint.Authorization.Parameters, nameof(endpoint.Authorization.Parameters)); ArgUtil.Equal(EndpointAuthorizationSchemes.UsernamePassword, endpoint.Authorization.Scheme, nameof(endpoint.Authorization.Scheme)); _context = context; _endpoint = endpoint; _cancellationToken = cancellationToken; // Find svn in %Path% string svnPath = WhichUtil.Which("svn", trace: Trace); if (string.IsNullOrEmpty(svnPath)) { throw new Exception(StringUtil.Loc("SvnNotInstalled")); } else { _context.Debug($"Found svn installation path: {svnPath}."); _svn = svnPath; } // External providers may need basic auth or tokens endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Username, out _username); endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Password, out _password); _acceptUntrusted = endpoint.Data.ContainsKey(EndpointData.SvnAcceptUntrustedCertificates) && StringUtil.ConvertToBoolean(endpoint.Data[EndpointData.SvnAcceptUntrustedCertificates], defaultValue: false); } public void Init( IExecutionContext context, RepositoryResource repository, CancellationToken cancellationToken) { // Validation. ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(repository, nameof(repository)); ArgUtil.NotNull(cancellationToken, nameof(cancellationToken)); ArgUtil.NotNull(repository.Url, nameof(repository.Url)); ArgUtil.Equal(true, repository.Url.IsAbsoluteUri, nameof(repository.Url.IsAbsoluteUri)); ArgUtil.NotNull(repository.Endpoint, nameof(repository.Endpoint)); ServiceEndpoint endpoint = context.Endpoints.Single(x => (repository.Endpoint.Id != Guid.Empty && x.Id == repository.Endpoint.Id) || (repository.Endpoint.Id == Guid.Empty && string.Equals(x.Name, repository.Endpoint.Name, StringComparison.OrdinalIgnoreCase))); ArgUtil.NotNull(endpoint.Data, nameof(endpoint.Data)); ArgUtil.NotNull(endpoint.Authorization, nameof(endpoint.Authorization)); ArgUtil.NotNull(endpoint.Authorization.Parameters, nameof(endpoint.Authorization.Parameters)); ArgUtil.Equal(EndpointAuthorizationSchemes.UsernamePassword, endpoint.Authorization.Scheme, nameof(endpoint.Authorization.Scheme)); _context = context; _repository = repository; _endpoint = endpoint; _cancellationToken = cancellationToken; // Find svn in %Path% string svnPath = WhichUtil.Which("svn", trace: Trace); if (string.IsNullOrEmpty(svnPath)) { throw new Exception(StringUtil.Loc("SvnNotInstalled")); } else { _context.Debug($"Found svn installation path: {svnPath}."); _svn = svnPath; } // External providers may need basic auth or tokens endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Username, out _username); endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Password, out _password); _acceptUntrusted = endpoint.Data.ContainsKey(EndpointData.SvnAcceptUntrustedCertificates) && StringUtil.ConvertToBoolean(endpoint.Data[EndpointData.SvnAcceptUntrustedCertificates], defaultValue: false); } public async Task<string> UpdateWorkspace( string rootPath, Dictionary<string, SvnMappingDetails> distinctMappings, bool cleanRepository, string sourceBranch, string revision) { if (cleanRepository) { // A clean build has been requested, if the $(build.Clean) variable didn't force // the BuildDirectoryManager to re-create the source directory earlier, // let's do it now explicitly. IBuildDirectoryManager buildDirectoryManager = HostContext.GetService<IBuildDirectoryManager>(); BuildCleanOption? cleanOption = _context.Variables.Build_Clean; buildDirectoryManager.CreateDirectory( _context, description: "source directory", path: rootPath, deleteExisting: !(cleanOption == BuildCleanOption.All || cleanOption == BuildCleanOption.Source)); } Dictionary<string, Uri> oldMappings = await GetOldMappings(rootPath); _context.Debug($"oldMappings.Count: {oldMappings.Count}"); oldMappings.ToList().ForEach(p => _context.Debug($" [{p.Key}] {p.Value}")); Dictionary<string, SvnMappingDetails> newMappings = BuildNewMappings(rootPath, sourceBranch, distinctMappings); _context.Debug($"newMappings.Count: {newMappings.Count}"); newMappings.ToList().ForEach(p => _context.Debug($" [{p.Key}] ServerPath: {p.Value.ServerPath}, LocalPath: {p.Value.LocalPath}, Depth: {p.Value.Depth}, Revision: {p.Value.Revision}, IgnoreExternals: {p.Value.IgnoreExternals}")); CleanUpSvnWorkspace(oldMappings, newMappings); long maxRevision = 0; foreach (SvnMappingDetails mapping in newMappings.Values) { long mappingRevision = await GetLatestRevisionAsync(mapping.ServerPath, revision); if (mappingRevision > maxRevision) { maxRevision = mappingRevision; } } await UpdateToRevisionAsync(oldMappings, newMappings, maxRevision); return maxRevision > 0 ? maxRevision.ToString() : "HEAD"; } private async Task<Dictionary<string, Uri>> GetOldMappings(string rootPath) { if (File.Exists(rootPath)) { throw new Exception(StringUtil.Loc("SvnFileAlreadyExists", rootPath)); } Dictionary<string, Uri> mappings = new Dictionary<string, Uri>(); if (Directory.Exists(rootPath)) { foreach (string workingDirectoryPath in GetSvnWorkingCopyPaths(rootPath)) { Uri url = await GetRootUrlAsync(workingDirectoryPath); if (url != null) { mappings.Add(workingDirectoryPath, url); } } } return mappings; } private List<string> GetSvnWorkingCopyPaths(string rootPath) { if (Directory.Exists(Path.Combine(rootPath, ".svn"))) { return new List<string>() { rootPath }; } else { ConcurrentStack<string> candidates = new ConcurrentStack<string>(); Directory.EnumerateDirectories(rootPath, "*", SearchOption.TopDirectoryOnly) .AsParallel() .ForAll(fld => candidates.PushRange(GetSvnWorkingCopyPaths(fld).ToArray())); return candidates.ToList(); } } private Dictionary<string, SvnMappingDetails> BuildNewMappings(string rootPath, string sourceBranch, Dictionary<string, SvnMappingDetails> distinctMappings) { Dictionary<string, SvnMappingDetails> mappings = new Dictionary<string, SvnMappingDetails>(); if (distinctMappings != null && distinctMappings.Count > 0) { foreach (KeyValuePair<string, SvnMappingDetails> mapping in distinctMappings) { SvnMappingDetails mappingDetails = mapping.Value; string localPath = mappingDetails.LocalPath; string absoluteLocalPath = Path.Combine(rootPath, localPath); SvnMappingDetails newMappingDetails = new SvnMappingDetails(); newMappingDetails.ServerPath = mappingDetails.ServerPath; newMappingDetails.LocalPath = absoluteLocalPath; newMappingDetails.Revision = mappingDetails.Revision; newMappingDetails.Depth = mappingDetails.Depth; newMappingDetails.IgnoreExternals = mappingDetails.IgnoreExternals; mappings.Add(absoluteLocalPath, newMappingDetails); } } else { SvnMappingDetails newMappingDetails = new SvnMappingDetails(); newMappingDetails.ServerPath = sourceBranch; newMappingDetails.LocalPath = rootPath; newMappingDetails.Revision = "HEAD"; newMappingDetails.Depth = 3; //Infinity newMappingDetails.IgnoreExternals = true; mappings.Add(rootPath, newMappingDetails); } return mappings; } public async Task<long> GetLatestRevisionAsync(string serverPath, string sourceRevision) { Trace.Verbose($@"Get latest revision of: '{_repository?.Url?.AbsoluteUri ?? _endpoint.Url.AbsoluteUri}' at or before: '{sourceRevision}'."); string xml = await RunPorcelainCommandAsync( "info", BuildSvnUri(serverPath), "--depth", "empty", "--revision", sourceRevision, "--xml"); // Deserialize the XML. // The command returns a non-zero exit code if the source revision is not found. // The assertions performed here should never fail. XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo)); ArgUtil.NotNullOrEmpty(xml, nameof(xml)); using (StringReader reader = new StringReader(xml)) { SvnInfo info = serializer.Deserialize(reader) as SvnInfo; ArgUtil.NotNull(info, nameof(info)); ArgUtil.NotNull(info.Entries, nameof(info.Entries)); ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length)); long revision = 0; long.TryParse(info.Entries[0].Commit?.Revision ?? sourceRevision, out revision); return revision; } } public string ResolveServerPath(string serverPath, string rootPath) { ArgUtil.Equal(true, serverPath.StartsWith(@"^/"), nameof(serverPath)); foreach (string workingDirectoryPath in GetSvnWorkingCopyPaths(rootPath)) { try { Trace.Verbose($@"Get SVN info for the working directory path '{workingDirectoryPath}'."); string xml = RunPorcelainCommandAsync( "info", workingDirectoryPath, "--depth", "empty", "--xml").GetAwaiter().GetResult(); // Deserialize the XML. // The command returns a non-zero exit code if the local path is not a working copy. // The assertions performed here should never fail. XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo)); ArgUtil.NotNullOrEmpty(xml, nameof(xml)); using (StringReader reader = new StringReader(xml)) { SvnInfo info = serializer.Deserialize(reader) as SvnInfo; ArgUtil.NotNull(info, nameof(info)); ArgUtil.NotNull(info.Entries, nameof(info.Entries)); ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length)); if (serverPath.Equals(info.Entries[0].RelativeUrl, StringComparison.Ordinal) || serverPath.StartsWith(info.Entries[0].RelativeUrl + '/', StringComparison.Ordinal)) { // We've found the mapping the serverPath belongs to. int n = info.Entries[0].RelativeUrl.Length; string relativePath = serverPath.Length <= n + 1 ? string.Empty : serverPath.Substring(n + 1); return Path.Combine(workingDirectoryPath, relativePath); } } } catch (ProcessExitCodeException) { Trace.Warning($@"The path '{workingDirectoryPath}' is not an SVN working directory path."); } } Trace.Warning($@"Haven't found any suitable mapping for '{serverPath}'"); // Since the server path starts with the "^/" prefix we return the original path without these two characters. return serverPath.Substring(2); } private async Task<Uri> GetRootUrlAsync(string localPath) { Trace.Verbose($@"Get URL for: '{localPath}'."); try { string xml = await RunPorcelainCommandAsync( "info", localPath, "--depth", "empty", "--xml"); // Deserialize the XML. // The command returns a non-zero exit code if the local path is not a working copy. // The assertions performed here should never fail. XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo)); ArgUtil.NotNullOrEmpty(xml, nameof(xml)); using (StringReader reader = new StringReader(xml)) { SvnInfo info = serializer.Deserialize(reader) as SvnInfo; ArgUtil.NotNull(info, nameof(info)); ArgUtil.NotNull(info.Entries, nameof(info.Entries)); ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length)); return new Uri(info.Entries[0].Url); } } catch (ProcessExitCodeException) { Trace.Verbose($@"The folder '{localPath}.svn' seems not to be a subversion system directory."); return null; } } private async Task UpdateToRevisionAsync(Dictionary<string, Uri> oldMappings, Dictionary<string, SvnMappingDetails> newMappings, long maxRevision) { foreach (KeyValuePair<string, SvnMappingDetails> mapping in newMappings) { string localPath = mapping.Key; SvnMappingDetails mappingDetails = mapping.Value; string effectiveServerUri = BuildSvnUri(mappingDetails.ServerPath); string effectiveRevision = EffectiveRevision(mappingDetails.Revision, maxRevision); mappingDetails.Revision = effectiveRevision; if (!Directory.Exists(Path.Combine(localPath, ".svn"))) { _context.Debug(String.Format( "Checking out with depth: {0}, revision: {1}, ignore externals: {2}", mappingDetails.Depth, effectiveRevision, mappingDetails.IgnoreExternals)); mappingDetails.ServerPath = effectiveServerUri; await CheckoutAsync(mappingDetails); } else if (oldMappings.ContainsKey(localPath) && oldMappings[localPath].Equals(new Uri(effectiveServerUri))) { _context.Debug(String.Format( "Updating with depth: {0}, revision: {1}, ignore externals: {2}", mappingDetails.Depth, mappingDetails.Revision, mappingDetails.IgnoreExternals)); await UpdateAsync(mappingDetails); } else { _context.Debug(String.Format( "Switching to {0} with depth: {1}, revision: {2}, ignore externals: {3}", mappingDetails.ServerPath, mappingDetails.Depth, mappingDetails.Revision, mappingDetails.IgnoreExternals)); await SwitchAsync(mappingDetails); } } } private string EffectiveRevision(string mappingRevision, long maxRevision) { if (!mappingRevision.Equals("HEAD", StringComparison.OrdinalIgnoreCase)) { // A specific revision has been requested in mapping return mappingRevision; } else if (maxRevision == 0) { // Tip revision return "HEAD"; } else { return maxRevision.ToString(); } } private void CleanUpSvnWorkspace(Dictionary<string, Uri> oldMappings, Dictionary<string, SvnMappingDetails> newMappings) { Trace.Verbose("Clean up Svn workspace."); oldMappings.Where(m => !newMappings.ContainsKey(m.Key)) .AsParallel() .ForAll(m => { Trace.Verbose($@"Delete unmapped folder: '{m.Key}'"); IOUtil.DeleteDirectory(m.Key, CancellationToken.None); }); } /// <summary> /// svn update localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert] /// </summary> /// <param name="mapping"></param> /// <returns></returns> private async Task UpdateAsync(SvnMappingDetails mapping) { Trace.Verbose($@"Update '{mapping.LocalPath}'."); await RunCommandAsync( "update", mapping.LocalPath, "--revision", mapping.Revision, "--depth", ToDepthArgument(mapping.Depth), mapping.IgnoreExternals ? "--ignore-externals" : null); } /// <summary> /// svn switch localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert] /// </summary> /// <param name="mapping"></param> /// <returns></returns> private async Task SwitchAsync(SvnMappingDetails mapping) { Trace.Verbose($@"Switch '{mapping.LocalPath}' to '{mapping.ServerPath}'."); await RunCommandAsync( "switch", $"^/{mapping.ServerPath}", mapping.LocalPath, "--ignore-ancestry", "--revision", mapping.Revision, "--depth", ToDepthArgument(mapping.Depth), mapping.IgnoreExternals ? "--ignore-externals" : null); } /// <summary> /// svn checkout localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert] /// </summary> /// <param name="mapping"></param> /// <returns></returns> private async Task CheckoutAsync(SvnMappingDetails mapping) { Trace.Verbose($@"Checkout '{mapping.ServerPath}' to '{mapping.LocalPath}'."); await RunCommandAsync( "checkout", mapping.ServerPath, mapping.LocalPath, "--revision", mapping.Revision, "--depth", ToDepthArgument(mapping.Depth), mapping.IgnoreExternals ? "--ignore-externals" : null); } private string BuildSvnUri(string serverPath) { StringBuilder sb = new StringBuilder((_repository?.Url ?? _endpoint.Url).ToString()); if (!string.IsNullOrEmpty(serverPath)) { if (sb[sb.Length - 1] != '/') { sb.Append('/'); } sb.Append(serverPath); } return sb.Replace('\\', '/').ToString(); } private string FormatArgumentsWithDefaults(params string[] args) { // Format each arg. List<string> formattedArgs = new List<string>(); foreach (string arg in args ?? new string[0]) { if (!string.IsNullOrEmpty(arg)) { // Validate the arg. if (arg.IndexOfAny(new char[] { '"', '\r', '\n' }) >= 0) { throw new Exception(StringUtil.Loc("InvalidCommandArg", arg)); } // Add the arg. formattedArgs.Add(QuotedArgument(arg)); } } // Add the common parameters. if (_acceptUntrusted) { formattedArgs.Add("--trust-server-cert"); } if (!string.IsNullOrWhiteSpace(_username)) { formattedArgs.Add("--username"); formattedArgs.Add(QuotedArgument(_username)); } if (!string.IsNullOrWhiteSpace(_password)) { formattedArgs.Add("--password"); formattedArgs.Add(QuotedArgument(_password)); } formattedArgs.Add("--no-auth-cache"); // Do not cache credentials formattedArgs.Add("--non-interactive"); // Add proxy setting parameters var agentProxy = HostContext.GetService<IVstsAgentWebProxy>(); if (!string.IsNullOrEmpty(_context.Variables.Agent_ProxyUrl) && !agentProxy.WebProxy.IsBypassed(_repository?.Url ?? _endpoint.Url)) { _context.Debug($"Add proxy setting parameters to '{_svn}' for proxy server '{_context.Variables.Agent_ProxyUrl}'."); formattedArgs.Add("--config-option"); formattedArgs.Add(QuotedArgument($"servers:global:http-proxy-host={new Uri(_context.Variables.Agent_ProxyUrl).Host}")); formattedArgs.Add("--config-option"); formattedArgs.Add(QuotedArgument($"servers:global:http-proxy-port={new Uri(_context.Variables.Agent_ProxyUrl).Port}")); if (!string.IsNullOrEmpty(_context.Variables.Agent_ProxyUsername)) { formattedArgs.Add("--config-option"); formattedArgs.Add(QuotedArgument($"servers:global:http-proxy-username={_context.Variables.Agent_ProxyUsername}")); } if (!string.IsNullOrEmpty(_context.Variables.Agent_ProxyPassword)) { formattedArgs.Add("--config-option"); formattedArgs.Add(QuotedArgument($"servers:global:http-proxy-password={_context.Variables.Agent_ProxyPassword}")); } } return string.Join(" ", formattedArgs); } private string QuotedArgument(string arg) { char quote = '\"'; char altQuote = '\''; if (arg.IndexOf(quote) > -1) { quote = '\''; altQuote = '\"'; } return (arg.IndexOfAny(new char[] { ' ', altQuote }) == -1) ? arg : $"{quote}{arg}{quote}"; } private string ToDepthArgument(int depth) { switch (depth) { case 0: return "empty"; case 1: return "files"; case 2: return "immediates"; default: return "infinity"; } } private async Task RunCommandAsync(params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(_context, nameof(_context)); // Invoke tf. using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { _context.Output(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { _context.Output(e.Data); } }; string arguments = FormatArgumentsWithDefaults(args); _context.Command($@"{_svn} {arguments}"); await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work), fileName: _svn, arguments: arguments, environment: null, requireExitCodeZero: true, cancellationToken: _cancellationToken); } } private async Task<string> RunPorcelainCommandAsync(params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(_context, nameof(_context)); // Invoke tf. using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var output = new List<string>(); var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { _context.Debug(e.Data); output.Add(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { _context.Debug(e.Data); output.Add(e.Data); } }; string arguments = FormatArgumentsWithDefaults(args); _context.Debug($@"{_svn} {arguments}"); // TODO: Test whether the output encoding needs to be specified on a non-Latin OS. try { await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work), fileName: _svn, arguments: arguments, environment: null, requireExitCodeZero: true, cancellationToken: _cancellationToken); } catch (ProcessExitCodeException) { // The command failed. Dump the output and throw. output.ForEach(x => _context.Output(x ?? string.Empty)); throw; } // Note, string.join gracefully handles a null element within the IEnumerable<string>. return string.Join(Environment.NewLine, output); } } public Dictionary<string, SvnMappingDetails> NormalizeMappings(List<SvnMappingDetails> allMappings) { // We use Ordinal comparer because SVN is case sensetive and keys in the dictionary are URLs. Dictionary<string, SvnMappingDetails> distinctMappings = new Dictionary<string, SvnMappingDetails>(StringComparer.Ordinal); HashSet<string> localPaths = new HashSet<string>(StringComparer.Ordinal); foreach (SvnMappingDetails map in allMappings) { string localPath = NormalizeRelativePath(map.LocalPath, Path.DirectorySeparatorChar, '/'); string serverPath = NormalizeRelativePath(map.ServerPath, '/', '\\'); if (string.IsNullOrEmpty(serverPath)) { _context.Debug(StringUtil.Loc("SvnEmptyServerPath", localPath)); _context.Debug(StringUtil.Loc("SvnMappingIgnored")); distinctMappings.Clear(); distinctMappings.Add(string.Empty, map); break; } if (localPaths.Contains(localPath)) { _context.Debug(StringUtil.Loc("SvnMappingDuplicateLocal", localPath)); continue; } else { localPaths.Add(localPath); } if (distinctMappings.ContainsKey(serverPath)) { _context.Debug(StringUtil.Loc("SvnMappingDuplicateServer", serverPath)); continue; } // Put normalized values of the local and server paths back into the mapping. map.LocalPath = localPath; map.ServerPath = serverPath; distinctMappings.Add(serverPath, map); } return distinctMappings; } public string NormalizeRelativePath(string path, char pathSeparator, char altPathSeparator) { string relativePath = (path ?? string.Empty).Replace(altPathSeparator, pathSeparator); relativePath = relativePath.Trim(pathSeparator, ' '); if (relativePath.Contains(":") || relativePath.Contains("..")) { throw new Exception(StringUtil.Loc("SvnIncorrectRelativePath", relativePath)); } return relativePath; } // The cancellation token used to stop svn command execution private CancellationToken _cancellationToken; // The Subversion server endpoint providing URL, username/password, and untrasted certs acceptace information private ServiceEndpoint _endpoint; // The Subversion repository resource providing URL, referenced service endpoint information private RepositoryResource _repository; // The build commands' execution context private IExecutionContext _context; // The svn command line utility location private string _svn; // The svn user name from SVN repository connection endpoint private string _username; // The svn user password from SVN repository connection endpoint private string _password; // The acceptUntrustedCerts property from SVN repository connection endpoint private bool _acceptUntrusted; } //////////////////////////////////////////////////////////////////////////////// // svn info data objects //////////////////////////////////////////////////////////////////////////////// [XmlRoot(ElementName = "info", Namespace = "")] public sealed class SvnInfo { [XmlElement(ElementName = "entry", Namespace = "")] public SvnInfoEntry[] Entries { get; set; } } public sealed class SvnInfoEntry { [XmlAttribute(AttributeName = "kind", Namespace = "")] public string Kind { get; set; } [XmlAttribute(AttributeName = "path", Namespace = "")] public string Path { get; set; } [XmlAttribute(AttributeName = "revision", Namespace = "")] public string Revision { get; set; } [XmlElement(ElementName = "url", Namespace = "")] public string Url { get; set; } [XmlElement(ElementName = "relative-url", Namespace = "")] public string RelativeUrl { get; set; } [XmlElement(ElementName = "repository", Namespace = "")] public SvnInfoRepository[] Repository { get; set; } [XmlElement(ElementName = "wc-info", Namespace = "", IsNullable = true)] public SvnInfoWorkingCopy[] WorkingCopyInfo { get; set; } [XmlElement(ElementName = "commit", Namespace = "")] public SvnInfoCommit Commit { get; set; } } public sealed class SvnInfoRepository { [XmlElement(ElementName = "wcroot-abspath", Namespace = "")] public string AbsPath { get; set; } [XmlElement(ElementName = "schedule", Namespace = "")] public string Schedule { get; set; } [XmlElement(ElementName = "depth", Namespace = "")] public string Depth { get; set; } } public sealed class SvnInfoWorkingCopy { [XmlElement(ElementName = "root", Namespace = "")] public string Root { get; set; } [XmlElement(ElementName = "uuid", Namespace = "")] public Guid Uuid { get; set; } } public sealed class SvnInfoCommit { [XmlAttribute(AttributeName = "revision", Namespace = "")] public string Revision { get; set; } [XmlElement(ElementName = "author", Namespace = "")] public string Author { get; set; } [XmlElement(ElementName = "date", Namespace = "")] public string Date { get; set; } } }
namespace Nancy.Testing { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Nancy.Bootstrapper; using Nancy.Helpers; using IO; /// <summary> /// Provides the capability of executing a request with Nancy, using a specific configuration provided by an <see cref="INancyBootstrapper"/> instance. /// </summary> public class Browser : IHideObjectMembers { private readonly Action<BrowserContext> defaultBrowserContext; private readonly INancyBootstrapper bootstrapper; private readonly INancyEngine engine; private readonly IDictionary<string, string> cookies = new Dictionary<string, string>(); /// <summary> /// Initializes a new instance of the <see cref="Browser"/> class, with the /// provided <see cref="ConfigurableBootstrapper"/> configuration. /// </summary> /// <param name="action">The <see cref="ConfigurableBootstrapper"/> configuration that should be used by the bootstrapper.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> public Browser(Action<ConfigurableBootstrapper.ConfigurableBootstrapperConfigurator> action, Action<BrowserContext> defaults = null) : this(new ConfigurableBootstrapper(action), defaults) { } /// <summary> /// Initializes a new instance of the <see cref="Browser"/> class. /// </summary> /// <param name="bootstrapper">A <see cref="INancyBootstrapper"/> instance that determines the Nancy configuration that should be used by the browser.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> public Browser(INancyBootstrapper bootstrapper, Action<BrowserContext> defaults = null) { this.bootstrapper = bootstrapper; this.bootstrapper.Initialise(); this.engine = this.bootstrapper.GetEngine(); this.defaultBrowserContext = defaults ?? DefaultBrowserContext; } /// <summary> /// Performs a DELETE request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Delete(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("DELETE", path, browserContext); } /// <summary> /// Performs a DELETE request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Delete(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("DELETE", url, browserContext); } /// <summary> /// Performs a GET request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Get(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("GET", path, browserContext); } /// <summary> /// Performs a GET request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Get(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("GET", url, browserContext); } /// <summary> /// Performs a HEAD request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Head(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("HEAD", path, browserContext); } /// <summary> /// Performs a HEAD request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Head(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("HEAD", url, browserContext); } /// <summary> /// Performs a OPTIONS request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Options(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("OPTIONS", path, browserContext); } /// <summary> /// Performs a OPTIONS request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Options(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("OPTIONS", url, browserContext); } /// <summary> /// Performs a PATCH request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Patch(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PATCH", path, browserContext); } /// <summary> /// Performs a PATCH request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Patch(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PATCH", url, browserContext); } /// <summary> /// Performs a POST request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Post(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("POST", path, browserContext); } /// <summary> /// Performs a POST request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Post(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("POST", url, browserContext); } /// <summary> /// Performs a PUT request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Put(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PUT", path, browserContext); } /// <summary> /// Performs a PUT request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Put(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PUT", url, browserContext); } /// <summary> /// Performs a request of the HTTP <paramref name="method"/>, on the given <paramref name="url"/>, using the /// provided <paramref name="browserContext"/> configuration. /// </summary> /// <param name="method">HTTP method to send the request as.</param> /// <param name="url">The URl of the request.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse HandleRequest(string method, Url url, Action<BrowserContext> browserContext) { var request = this.CreateRequest(method, url, browserContext ?? (with => {})); var response = new BrowserResponse(this.engine.HandleRequest(request), this); this.CaptureCookies(response); return response; } /// <summary> /// Performs a request of the HTTP <paramref name="method"/>, on the given <paramref name="path"/>, using the /// provided <paramref name="browserContext"/> configuration. /// </summary> /// <param name="method">HTTP method to send the request as.</param> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse HandleRequest(string method, string path, Action<BrowserContext> browserContext) { var url = Uri.IsWellFormedUriString(path, UriKind.Relative) ? new Url { Path = path } : (Url)new Uri(path); return this.HandleRequest(method, url, browserContext); } private static void DefaultBrowserContext(BrowserContext context) { context.HttpRequest(); } private void SetCookies(BrowserContext context) { if (!this.cookies.Any()) { return; } var cookieString = this.cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); context.Header("Cookie", cookieString); } private void CaptureCookies(BrowserResponse response) { if (response.Cookies == null || !response.Cookies.Any()) { return; } foreach (var cookie in response.Cookies) { if (string.IsNullOrEmpty(cookie.Value)) { this.cookies.Remove(cookie.Name); } else { this.cookies[cookie.Name] = cookie.Value; } } } private static void BuildRequestBody(IBrowserContextValues contextValues) { if (contextValues.Body != null) { return; } var useFormValues = !string.IsNullOrEmpty(contextValues.FormValues); var bodyContents = useFormValues ? contextValues.FormValues : contextValues.BodyString; var bodyBytes = bodyContents != null ? Encoding.UTF8.GetBytes(bodyContents) : new byte[] { }; if (useFormValues && !contextValues.Headers.ContainsKey("Content-Type")) { contextValues.Headers["Content-Type"] = new[] { "application/x-www-form-urlencoded" }; } contextValues.Body = new MemoryStream(bodyBytes); } private Request CreateRequest(string method, Url url, Action<BrowserContext> browserContext) { var context = new BrowserContext(); this.SetCookies(context); this.defaultBrowserContext.Invoke(context); browserContext.Invoke(context); var contextValues = (IBrowserContextValues)context; if (!contextValues.Headers.ContainsKey("user-agent")) { contextValues.Headers.Add("user-agent", new[] { "Nancy.Testing.Browser" }); } BuildRequestBody(contextValues); var requestStream = RequestStream.FromStream(contextValues.Body, 0, true); var certBytes = (contextValues.ClientCertificate == null) ? new byte[] { } : contextValues.ClientCertificate.GetRawCertData(); var requestUrl = url; requestUrl.Scheme = string.IsNullOrWhiteSpace(contextValues.Protocol) ? requestUrl.Scheme : contextValues.Protocol; requestUrl.HostName = string.IsNullOrWhiteSpace(contextValues.HostName) ? requestUrl.HostName : contextValues.HostName; requestUrl.Query = string.IsNullOrWhiteSpace(url.Query) ? (contextValues.QueryString ?? string.Empty) : url.Query; return new Request(method, requestUrl, requestStream, contextValues.Headers, contextValues.UserHostAddress, certBytes); } } }
// 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; /// <summary> /// System.Collections.Generic.List.IndexOf(T item, Int32) /// </summary> public class ListIndexOf2 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = new int[1000]; for (int i = 0; i < 1000; i++) { iArray[i] = i; } List<int> listObject = new List<int>(iArray); int ob = this.GetInt32(0, 1000); int result = listObject.IndexOf(ob, 0); if (result != ob) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string"); try { string[] strArray = { "apple", "dog", "banana", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.IndexOf("dog", 2); if (result != 4) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type"); try { MyClass myclass1 = new MyClass(); MyClass myclass2 = new MyClass(); MyClass myclass3 = new MyClass(); MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 }; List<MyClass> listObject = new List<MyClass>(mc); int result = listObject.IndexOf(myclass3, 2); if (result != 2) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: There are many element in the list with the same value"); try { string[] strArray = { "apple", "banana", "chocolate", "banana", "banana", "dog", "banana", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.IndexOf("banana", 2); if (result != 3) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Do not find the element "); try { int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.IndexOf(-11, 4); if (result != -1) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The index is negative"); try { int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.IndexOf(-11, -4); TestLibrary.TestFramework.LogError("101", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The index is greater than the last index of the list"); try { int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.IndexOf(-11, 12); TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ListIndexOf2 test = new ListIndexOf2(); TestLibrary.TestFramework.BeginTestCase("ListIndexOf2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } } public class MyClass { }
#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.Diagnostics; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] public void NewLine() { MemoryStream ms = new MemoryStream(); using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" }) using (var jsonWriter = new JsonTextWriter(streamWriter) { CloseOutput = true, Indentation = 2, Formatting = Formatting.Indented }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("prop"); jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } byte[] data = ms.ToArray(); string json = Encoding.UTF8.GetString(data, 0, data.Length); Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json); } [Test] public void QuoteNameAndStrings() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false }; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("value"); writer.WriteEndObject(); writer.Flush(); Assert.AreEqual(@"{name:""value""}", sb.ToString()); } [Test] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsFalse(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsTrue(ms.CanRead); } #if !(PORTABLE || NETFX_CORE) [Test] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.AreEqual("1", sw.ToString()); } #endif [Test] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Console.WriteLine("ValueFormatting"); Console.WriteLine(result); Assert.AreEqual(expected, result); } [Test] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithUnsupportedValue() { ExceptionAssert.Throws<JsonWriterException>(() => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''."); } [Test] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Console.WriteLine("StringEscaping"); Console.WriteLine(result); Assert.AreEqual(expected, result); } [Test] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); } } [Test] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.AreEqual("1", sw.ToString()); } [Test] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Test] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Test] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Test] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); StringAssert.AreEqual(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Test] public void BadWriteEndArray() { ExceptionAssert.Throws<JsonWriterException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }, "No token to close. Path ''."); } [Test] public void InvalidQuoteChar() { ExceptionAssert.Throws<ArgumentException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }, @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); } [Test] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.AreEqual(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.AreEqual('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.AreEqual(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.AreEqual('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.AreEqual(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Test] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.AreEqual("", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteValue(1); Assert.AreEqual("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[0]", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteNull(); Assert.AreEqual("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.AreEqual("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[1]", writer.Path); writer.WriteEndArray(); Assert.AreEqual("", writer.Path); } StringAssert.AreEqual(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Test] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states."); break; } } } [Test] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Test] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(script, reader.ReadAsString()); //Console.WriteLine(HttpUtility.HtmlEncode(script)); //System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer(); //Console.WriteLine(s.Serialize(new { html = script })); } [Test] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.AreEqual(8, json.Length); Assert.AreEqual(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.AreEqual(3, json.Length); Assert.AreEqual("\"\u5f20\"", json); } [Test] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } #if !NET20 [Test] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Test] public void Culture() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = new CultureInfo("en-NZ"); writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Test] public void CompareNewStringEscapingWithOld() { Console.WriteLine("Started"); char c = (char)0; do { if (c % 1000 == 0) Console.WriteLine("Position: " + (int)c); StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); c++; } while (c != char.MaxValue); Console.WriteLine("Finished"); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) writer.Write(delimiter); if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) continue; string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) unicodeBuffer = new char[6]; StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) continue; if (i > lastWritePosition) { if (chars == null) chars = s.ToCharArray(); // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) writer.Write(escapedValue); else writer.Write(unicodeBuffer); } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) chars = s.ToCharArray(); // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) writer.Write(delimiter); } [Test] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.AreEqual(WriteState.Property, writer.WriteState); Assert.AreEqual("Property1", writer.Path); writer.WriteNull(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.AreEqual(WriteState.Start, writer.WriteState); StringAssert.AreEqual(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Test] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } StringAssert.AreEqual(@"{ a: 1 }", stringWriter.ToString()); } } [Test] public void WriteComments() { string json = @"//comment*//*hi*/ {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + @" ,//comment after comma" + StringUtils.CarriageReturnLineFeed + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + @"Constructor (//comment null//comment ), ""Price"": 3.99, ""Sizes"": //comment [//comment ""Small""//comment ]//comment }//comment //comment 1 "; JsonTextReader r = new JsonTextReader(new StringReader(json)); StringWriter sw = new StringWriter(); JsonTextWriter w = new JsonTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteToken(r, true); StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/ ""Name"": /*comment*/ true/*comment after true*//*comment after comma*/, ""ExpiryDate"": /*comment*/ new Constructor( /*comment*/, null /*comment*/ ), ""Price"": 3.99, ""Sizes"": /*comment*/ [ /*comment*/ ""Small"" /*comment*/ ]/*comment*/ }/*comment *//*comment 1 */", sw.ToString()); } } public class CustomJsonTextWriter : JsonTextWriter { private readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) _writer.Write("}}}"); else base.WriteEnd(token); } } #if !(PORTABLE || NETFX_CORE) public struct ConvertibleInt : IConvertible { private readonly int _value; public ConvertibleInt(int value) { _value = value; } public TypeCode GetTypeCode() { return TypeCode.Int32; } public bool ToBoolean(IFormatProvider provider) { throw new NotImplementedException(); } public byte ToByte(IFormatProvider provider) { throw new NotImplementedException(); } public char ToChar(IFormatProvider provider) { throw new NotImplementedException(); } public DateTime ToDateTime(IFormatProvider provider) { throw new NotImplementedException(); } public decimal ToDecimal(IFormatProvider provider) { throw new NotImplementedException(); } public double ToDouble(IFormatProvider provider) { throw new NotImplementedException(); } public short ToInt16(IFormatProvider provider) { throw new NotImplementedException(); } public int ToInt32(IFormatProvider provider) { throw new NotImplementedException(); } public long ToInt64(IFormatProvider provider) { throw new NotImplementedException(); } public sbyte ToSByte(IFormatProvider provider) { throw new NotImplementedException(); } public float ToSingle(IFormatProvider provider) { throw new NotImplementedException(); } public string ToString(IFormatProvider provider) { throw new NotImplementedException(); } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) return _value; throw new Exception("Type not supported: " + conversionType.FullName); } public ushort ToUInt16(IFormatProvider provider) { throw new NotImplementedException(); } public uint ToUInt32(IFormatProvider provider) { throw new NotImplementedException(); } public ulong ToUInt64(IFormatProvider provider) { throw new NotImplementedException(); } } #endif }
using System; using System.Drawing; using System.Linq; using System.Windows.Forms; using hw.DebugFormatter; using hw.Helper; using JetBrains.Annotations; // ReSharper disable ConvertMethodToExpressionBody // ReSharper disable MergeConditionalExpression namespace hw.Forms { /// <summary> /// Used to persist location of window of parent /// </summary> [PublicAPI] public sealed class PositionConfig : IDisposable { readonly Func<string> GetFileName; Form InternalTarget; bool LoadPositionCalled; /// <summary> /// Ctor /// </summary> /// <param name="getFileName"> /// function to obtain filename of configuration file. /// <para>It will be called each time the name is required. </para> /// <para>Default: Target.Name</para> /// </param> public PositionConfig(Func<string> getFileName = null) => GetFileName = getFileName ?? (() => InternalTarget == null? null : InternalTarget.Name); /// <summary> /// Form that will be controlled by this instance /// </summary> public Form Target { [UsedImplicitly] get => InternalTarget; set { Disconnect(); InternalTarget = value; Connect(); } } /// <summary> /// Name that will be used as filename /// </summary> public string FileName => GetFileName(); Rectangle? Position { get => Convert (0, null, s => (Rectangle?)new RectangleConverter().ConvertFromString(s)); set => Save(value, WindowState); } string[] ParameterStrings { get { if(InternalTarget == null) return null; var content = FileHandle.String; return content == null? null : content.Split('\n'); } } SmbFile FileHandle { get { var fileName = FileName; return fileName == null? null : fileName.ToSmbFile(); } } FormWindowState WindowState { get => Convert(1, FormWindowState.Normal, s => s.Parse<FormWindowState>()); set => Save(Position, value); } void IDisposable.Dispose() { Disconnect(); } void Disconnect() { if(InternalTarget == null) return; InternalTarget.SuspendLayout(); LoadPositionCalled = false; InternalTarget.Load -= OnLoad; InternalTarget.LocationChanged -= OnLocationChanged; InternalTarget.SizeChanged -= OnLocationChanged; InternalTarget.ResumeLayout(); InternalTarget = null; } void Connect() { if(InternalTarget == null) return; InternalTarget.SuspendLayout(); LoadPositionCalled = false; InternalTarget.Load += OnLoad; InternalTarget.LocationChanged += OnLocationChanged; InternalTarget.SizeChanged += OnLocationChanged; InternalTarget.ResumeLayout(); } void OnLocationChanged(object target, EventArgs e) { if(target != InternalTarget) return; SavePosition(); } void OnLoad(object target, EventArgs e) { if(target != InternalTarget) return; LoadPosition(); } void Save(Rectangle? position, FormWindowState state) { var fileHandle = FileHandle; Tracer.Assert(fileHandle != null); fileHandle.String = "{0}\n{1}" .ReplaceArgs ( position == null? "" : new RectangleConverter().ConvertToString(position.Value), state ); } T Convert<T>(int position, T defaultValue, Func<string, T> converter) { return ParameterStrings == null || ParameterStrings.Length <= position ? defaultValue : converter(ParameterStrings[position]); } void LoadPosition() { var fileHandle = FileHandle; Tracer.Assert(fileHandle != null); if(fileHandle.String != null) { var position = Position; Tracer.Assert(position != null); InternalTarget.SuspendLayout(); InternalTarget.StartPosition = FormStartPosition.Manual; InternalTarget.Bounds = EnsureVisible(position.Value); InternalTarget.WindowState = WindowState; InternalTarget.ResumeLayout(true); } LoadPositionCalled = true; } void SavePosition() { if(!LoadPositionCalled) return; if(InternalTarget.WindowState == FormWindowState.Normal) Position = InternalTarget.Bounds; WindowState = InternalTarget.WindowState; } static Rectangle EnsureVisible(Rectangle value) { var allScreens = Screen.AllScreens; if(allScreens.Any(s => s.Bounds.IntersectsWith(value))) return value; var closestScreen = Screen.FromRectangle(value); var result = value; var leftDistance = value.Left - closestScreen.Bounds.Right; var rightDistance = value.Right - closestScreen.Bounds.Left; if(leftDistance > 0 && rightDistance > 0) result.X += leftDistance < rightDistance? -(leftDistance + 10) : rightDistance + 10; var topDistance = value.Top - closestScreen.Bounds.Bottom; var bottomDistance = value.Bottom - closestScreen.Bounds.Top; if(topDistance > 0 && bottomDistance > 0) result.Y += topDistance < bottomDistance? -(topDistance + 10) : bottomDistance + 10; Tracer.Assert(closestScreen.Bounds.IntersectsWith(result)); return result; } } }