context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using IntuiLab.Kinect.DataUserTracking;
using IntuiLab.Kinect.Enums;
using Microsoft.Kinect;
using System.Collections.Generic;
using System.Linq;
namespace IntuiLab.Kinect.GestureRecognizer.Gestures
{
internal class SwipeCondition : Condition
{
#region Fields
/// <summary>
/// Instance of Checker
/// </summary>
private readonly Checker m_refChecker;
/// <summary>
/// Hand treated
/// </summary>
private readonly JointType m_refHand;
/// <summary>
/// Movement direction to hand
/// </summary>
private EnumKinectDirectionGesture m_refDirection;
/// <summary>
/// Consecutive numbers of frame where the condition is satisfied
/// </summary>
private int m_nIndex;
/// <summary>
/// Informe if the gesture is begin
/// </summary>
private bool m_GestureBegin;
/// <summary>
/// Hand velocity in each frame
/// </summary>
private List<double> m_handVelocity;
#endregion
/// <summary>
/// Constructor
/// </summary>
/// <param name="refUser">User data</param>
/// <param name="leftOrRightHand">Hand treated</param>
public SwipeCondition(UserData refUser, JointType leftOrRightHand)
: base(refUser)
{
m_nIndex = 0;
m_refHand = leftOrRightHand;
m_refChecker = new Checker(refUser, PropertiesPluginKinect.Instance.SwipeCheckerTolerance);
m_handVelocity = new List<double>();
m_GestureBegin = false;
}
/// <summary>
/// See description in Condition class
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected override void Check(object sender, NewSkeletonEventArgs e)
{
// Relative position between HipCenter and Hand
List<EnumKinectDirectionGesture> handToHipOrientation = m_refChecker.GetRelativePosition(JointType.HipCenter, m_refHand).ToList();
// Relative position between Head and Hand
List<EnumKinectDirectionGesture> handToHeadOrientation = m_refChecker.GetRelativePosition(JointType.Head, m_refHand).ToList();
// Movement directions to hand
List<EnumKinectDirectionGesture> handMovement = m_refChecker.GetAbsoluteMovement(m_refHand).ToList();
// Relative velocity of hand
m_handVelocity.Add(m_refChecker.GetRelativeVelocity(JointType.HipCenter, m_refHand));
double handVelocity = m_refChecker.GetRelativeVelocity(JointType.HipCenter, m_refHand);
if (m_refHand == JointType.HandRight)
{
IntuiLab.Kinect.Utils.DebugLog.DebugTraceLog("Swipe Left speed = " + handVelocity, false);
}
else if (m_refHand == JointType.HandLeft)
{
IntuiLab.Kinect.Utils.DebugLog.DebugTraceLog("Swipe Right speed = " + handVelocity, false);
}
// Speed condition
if (handVelocity < PropertiesPluginKinect.Instance.SwipeLowerBoundForVelocity)
{
Reset();
}
// Condition : Hand is in front of the body and between HipCenter and Head
else if (handToHipOrientation.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_FORWARD)
&& handToHeadOrientation.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_DOWNWARD))
{
// Movement did not start yet, initializing
if (m_refDirection == EnumKinectDirectionGesture.KINECT_DIRECTION_NONE)
{
// Condition : Hand is right && Movement direction hand => left
if (PropertiesPluginKinect.Instance.EnableGestureSwipeLeft &&
handMovement.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_LEFT)
&& !handMovement.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_UPWARD))
{
m_refDirection = EnumKinectDirectionGesture.KINECT_DIRECTION_LEFT;
m_GestureBegin = true;
// Notify the gesture swipe left is begin
RaiseGestureBegining(this, new BeginGestureEventArgs
{
Gesture = EnumGesture.GESTURE_SWIPE_LEFT,
Posture = EnumPosture.POSTURE_NONE
});
}
// Condition : Hand is left && Movement direction hand => right
else if (PropertiesPluginKinect.Instance.EnableGestureSwipeRight &&
handMovement.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_RIGHT) &&
!handMovement.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_UPWARD))
{
m_refDirection = EnumKinectDirectionGesture.KINECT_DIRECTION_RIGHT;
m_GestureBegin = true;
// Notify the gesture swipe right is begin
RaiseGestureBegining(this, new BeginGestureEventArgs
{
Gesture = EnumGesture.GESTURE_SWIPE_RIGHT,
Posture = EnumPosture.POSTURE_NONE
});
}
else
{
// Take other direction
Reset();
}
}
// Movement direction hand changed
else if (!handMovement.Contains(m_refDirection))
{
Reset();
}
else
{
// Gesture Swipe is complete
if (m_nIndex >= PropertiesPluginKinect.Instance.SwipeLowerBoundForSuccess)
{
// Calculate mean velocity
double meanVelocity = 0;
foreach (double velocity in m_handVelocity)
{
meanVelocity += velocity;
}
meanVelocity = meanVelocity / (double)m_handVelocity.Count;
IntuiLab.Kinect.Utils.DebugLog.DebugTraceLog("Mean Velocity = " + meanVelocity, false);
if (m_refDirection == EnumKinectDirectionGesture.KINECT_DIRECTION_LEFT)
{
// Notify Gesture Swipe Left is detected
FireSucceeded(this, new SuccessGestureEventArgs
{
Gesture = EnumGesture.GESTURE_SWIPE_LEFT,
Posture = EnumPosture.POSTURE_NONE
});
IntuiLab.Kinect.Utils.DebugLog.DebugTraceLog("Condition Swipe Left complete", false);
}
else if (m_refDirection == EnumKinectDirectionGesture.KINECT_DIRECTION_RIGHT)
{
// Notify Gesture Swipe Right is detected
FireSucceeded(this, new SuccessGestureEventArgs
{
Gesture = EnumGesture.GESTURE_SWIPE_RIGHT,
Posture = EnumPosture.POSTURE_NONE
});
IntuiLab.Kinect.Utils.DebugLog.DebugTraceLog("Condition Swipe Right complete", false);
}
m_nIndex = 0;
m_refDirection = EnumKinectDirectionGesture.KINECT_DIRECTION_NONE;
}
// Step successful, waiting for next
else
{
m_nIndex++;
}
}
}
}
/// <summary>
/// Restart detecting
/// </summary>
private void Reset()
{
// If gesture begin, notify gesture is end
if (m_GestureBegin)
{
m_GestureBegin = false;
if (m_refDirection == EnumKinectDirectionGesture.KINECT_DIRECTION_LEFT)
{
RaiseGestureEnded(this, new EndGestureEventArgs
{
Gesture = EnumGesture.GESTURE_SWIPE_LEFT,
Posture = EnumPosture.POSTURE_NONE
});
}
else if (m_refDirection == EnumKinectDirectionGesture.KINECT_DIRECTION_RIGHT)
{
RaiseGestureEnded(this, new EndGestureEventArgs
{
Gesture = EnumGesture.GESTURE_SWIPE_RIGHT,
Posture = EnumPosture.POSTURE_NONE
});
}
}
m_nIndex = 0;
m_handVelocity.Clear();
m_refDirection = EnumKinectDirectionGesture.KINECT_DIRECTION_NONE;
FireFailed(this, new FailedGestureEventArgs
{
refCondition = this
});
}
}
}
| |
// 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.Runtime.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
[IsByRefLike]
public struct ReadOnlySpan<T>
{
/// <summary>A byref or a native ptr.</summary>
private readonly ByReference<T> _pointer;
/// <summary>The number of elements this ReadOnlySpan contains.</summary>
#if PROJECTN
[Bound]
#endif
private readonly int _length;
/// <summary>
/// Creates a new read-only span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()));
_length = array.Length;
}
/// <summary>
/// Creates a new read-only span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the read-only span.</param>
/// <param name="length">The number of items in the read-only span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
_length = length;
}
/// <summary>
/// Creates a new read-only span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe ReadOnlySpan(void* pointer, int length)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
_length = length;
}
/// <summary>
/// Create a new read-only span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) => new ReadOnlySpan<T>(ref objectData, length);
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlySpan(ref T ptr, int length)
{
Debug.Assert(length >= 0);
_pointer = new ByReference<T>(ref ptr);
_length = length;
}
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T DangerousGetPinnableReference()
{
return ref _pointer.Value;
}
/// <summary>
/// The number of items in the read-only span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns the specified element of the read-only span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public T this[int index]
{
#if PROJECTN
[BoundsChecking]
get
{
return Unsafe.Add(ref _pointer.Value, index);
}
#else
#if CORERT
[Intrinsic]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
return Unsafe.Add(ref _pointer.Value, index);
}
#endif
}
/// <summary>
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
if ((uint)_length > (uint)destination.Length)
return false;
Span.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref _pointer.Value, _length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(T[] array) => new ReadOnlySpan<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(ArraySegment<T> arraySegment) => new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Forms a slice out of the given read-only span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
}
/// <summary>
/// Forms a slice out of the given read-only span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
}
/// <summary>
/// Copies the contents of this read-only span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray()
{
if (_length == 0)
return Array.Empty<T>();
var destination = new T[_length];
Span.CopyTo<T>(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, _length);
return destination;
}
/// <summary>
/// Returns a 0-length read-only span whose base is the null pointer.
/// </summary>
public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
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.Xml;
using System.Text;
namespace fyiReporting.RDL
{
///<summary>
/// The width of the border. Expressions for all sides as well as default expression.
///</summary>
[Serializable]
internal class StyleBorderWidth : ReportLink
{
Expression _Default; //(Size) Width of the border (unless overridden for a specific side)
// Borders are centered on the edge of the object
// Default: 1 pt Max: 20 pt Min: 0.25 pt
Expression _Left; //(Size) Width of the left border. Max: 20 pt Min: 0.25 pt
Expression _Right; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt
Expression _Top; //(Size) Width of the top border. Max: 20 pt Min: 0.25 pt
Expression _Bottom; //(Size) Width of the bottom border. Max: 20 pt Min: 0.25 pt
internal StyleBorderWidth(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
_Default=null;
_Left=null;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Default":
_Default = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit);
break;
case "Left":
_Left = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit);
break;
case "Right":
_Right = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit);
break;
case "Top":
_Top = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit);
break;
case "Bottom":
_Bottom = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown BorderWidth element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
}
// Handle parsing of function in final pass
override internal void FinalPass()
{
if (_Default != null)
_Default.FinalPass();
if (_Left != null)
_Left.FinalPass();
if (_Right != null)
_Right.FinalPass();
if (_Top != null)
_Top.FinalPass();
if (_Bottom != null)
_Bottom.FinalPass();
return;
}
// Generate a CSS string from the specified styles
internal string GetCSS(Report rpt, Row row, bool bDefaults)
{
StringBuilder sb = new StringBuilder();
if (_Default != null)
sb.AppendFormat("border-width:{0};",_Default.EvaluateString(rpt, row));
else if (bDefaults)
sb.Append("border-width:1pt;");
if (_Left != null)
sb.AppendFormat("border-left-width:{0};",_Left.EvaluateString(rpt, row));
if (_Right != null)
sb.AppendFormat("border-right-width:{0};",_Right.EvaluateString(rpt, row));
if (_Top != null)
sb.AppendFormat("border-top-width:{0};",_Top.EvaluateString(rpt, row));
if (_Bottom != null)
sb.AppendFormat("border-bottom-width:{0};",_Bottom.EvaluateString(rpt, row));
return sb.ToString();
}
internal bool IsConstant()
{
bool rc = true;
if (_Default != null)
rc = _Default.IsConstant();
if (!rc)
return false;
if (_Left != null)
rc = _Left.IsConstant();
if (!rc)
return false;
if (_Right != null)
rc = _Right.IsConstant();
if (!rc)
return false;
if (_Top != null)
rc = _Top.IsConstant();
if (!rc)
return false;
if (_Bottom != null)
rc = _Bottom.IsConstant();
return rc;
}
static internal string GetCSSDefaults()
{
return "border-width:1pt;";
}
internal Expression Default
{
get { return _Default; }
set { _Default = value; }
}
internal float EvalDefault(Report rpt, Row r) // return points
{
if (_Default == null)
return 1;
string sw;
sw = _Default.EvaluateString(rpt, r);
RSize rs = new RSize(this.OwnerReport, sw);
return rs.Points;
}
internal Expression Left
{
get { return _Left; }
set { _Left = value; }
}
internal float EvalLeft(Report rpt, Row r) // return points
{
if (_Left == null)
return EvalDefault(rpt, r);
string sw = _Left.EvaluateString(rpt, r);
RSize rs = new RSize(this.OwnerReport, sw);
return rs.Points;
}
internal Expression Right
{
get { return _Right; }
set { _Right = value; }
}
internal float EvalRight(Report rpt, Row r) // return points
{
if (_Right == null)
return EvalDefault(rpt, r);
string sw = _Right.EvaluateString(rpt, r);
RSize rs = new RSize(this.OwnerReport, sw);
return rs.Points;
}
internal Expression Top
{
get { return _Top; }
set { _Top = value; }
}
internal float EvalTop(Report rpt, Row r) // return points
{
if (_Top == null)
return EvalDefault(rpt, r);
string sw = _Top.EvaluateString(rpt, r);
RSize rs = new RSize(this.OwnerReport, sw);
return rs.Points;
}
internal Expression Bottom
{
get { return _Bottom; }
set { _Bottom = value; }
}
internal float EvalBottom(Report rpt, Row r) // return points
{
if (_Bottom == null)
return EvalDefault(rpt, r);
string sw = _Bottom.EvaluateString(rpt, r);
RSize rs = new RSize(this.OwnerReport, sw);
return rs.Points;
}
}
}
| |
using System.Xml.Linq;
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.Logging;
using GitVersion.OutputVariables;
namespace GitVersion.VersionConverters.AssemblyInfo;
public interface IProjectFileUpdater : IVersionConverter<AssemblyInfoContext>
{
bool CanUpdateProjectFile(XElement xmlRoot);
}
public sealed class ProjectFileUpdater : IProjectFileUpdater
{
internal const string AssemblyVersionElement = "AssemblyVersion";
private const string FileVersionElement = "FileVersion";
private const string InformationalVersionElement = "InformationalVersion";
private const string VersionElement = "Version";
private readonly List<Action> restoreBackupTasks = new();
private readonly List<Action> cleanupBackupTasks = new();
private readonly IFileSystem fileSystem;
private readonly ILog log;
public ProjectFileUpdater(ILog log, IFileSystem fileSystem)
{
this.fileSystem = fileSystem;
this.log = log;
}
public void Execute(VersionVariables variables, AssemblyInfoContext context)
{
if (context.EnsureAssemblyInfo)
throw new WarningException($"Configuration setting {nameof(context.EnsureAssemblyInfo)} is not valid when updating project files!");
var projectFilesToUpdate = GetProjectFiles(context).ToList();
var assemblyVersion = variables.AssemblySemVer;
var assemblyInfoVersion = variables.InformationalVersion;
var assemblyFileVersion = variables.AssemblySemFileVer;
var packageVersion = variables.NuGetVersion;
foreach (var projectFile in projectFilesToUpdate)
{
var localProjectFile = projectFile.FullName;
var originalFileContents = this.fileSystem.ReadAllText(localProjectFile);
var fileXml = XElement.Parse(originalFileContents);
if (!CanUpdateProjectFile(fileXml))
{
this.log.Warning($"Unable to update file: {localProjectFile}");
continue;
}
this.log.Debug($"Update file: {localProjectFile}");
var backupProjectFile = localProjectFile + ".bak";
this.fileSystem.Copy(localProjectFile, backupProjectFile, true);
this.restoreBackupTasks.Add(() =>
{
if (this.fileSystem.Exists(localProjectFile))
{
this.fileSystem.Delete(localProjectFile);
}
this.fileSystem.Move(backupProjectFile, localProjectFile);
});
this.cleanupBackupTasks.Add(() => this.fileSystem.Delete(backupProjectFile));
if (!assemblyVersion.IsNullOrWhiteSpace())
{
UpdateProjectVersionElement(fileXml, AssemblyVersionElement, assemblyVersion);
}
if (!assemblyFileVersion.IsNullOrWhiteSpace())
{
UpdateProjectVersionElement(fileXml, FileVersionElement, assemblyFileVersion);
}
if (!assemblyInfoVersion.IsNullOrWhiteSpace())
{
UpdateProjectVersionElement(fileXml, InformationalVersionElement, assemblyInfoVersion);
}
if (!packageVersion.IsNullOrWhiteSpace())
{
UpdateProjectVersionElement(fileXml, VersionElement, packageVersion);
}
var outputXmlString = fileXml.ToString();
if (originalFileContents != outputXmlString)
{
this.fileSystem.WriteAllText(localProjectFile, outputXmlString);
}
}
CommitChanges();
}
public bool CanUpdateProjectFile(XElement xmlRoot)
{
if (xmlRoot.Name != "Project")
{
this.log.Warning("Invalid project file specified, root element must be <Project>.");
return false;
}
var sdkAttribute = xmlRoot.Attribute("Sdk");
if (sdkAttribute == null || !sdkAttribute.Value.StartsWith("Microsoft.NET.Sdk"))
{
this.log.Warning($"Specified project file Sdk ({sdkAttribute?.Value}) is not supported, please ensure the project sdk starts with 'Microsoft.NET.Sdk'");
return false;
}
var propertyGroups = xmlRoot.Descendants("PropertyGroup").ToList();
if (!propertyGroups.Any())
{
this.log.Warning("Unable to locate any <PropertyGroup> elements in specified project file. Are you sure it is in a correct format?");
return false;
}
var lastGenerateAssemblyInfoElement = propertyGroups.SelectMany(s => s.Elements("GenerateAssemblyInfo")).LastOrDefault();
if (lastGenerateAssemblyInfoElement != null && (bool)lastGenerateAssemblyInfoElement == false)
{
this.log.Warning("Project file specifies <GenerateAssemblyInfo>false</GenerateAssemblyInfo>: versions set in this project file will not affect the output artifacts.");
return false;
}
return true;
}
internal static void UpdateProjectVersionElement(XElement xmlRoot, string versionElement, string versionValue)
{
var propertyGroups = xmlRoot.Descendants("PropertyGroup").ToList();
var propertyGroupToModify = propertyGroups.LastOrDefault(l => l.Element(versionElement) != null)
?? propertyGroups.First();
var versionXmlElement = propertyGroupToModify.Elements(versionElement).LastOrDefault();
if (versionXmlElement != null)
{
versionXmlElement.Value = versionValue;
}
else
{
propertyGroupToModify.SetElementValue(versionElement, versionValue);
}
}
public void Dispose()
{
foreach (var restoreBackup in this.restoreBackupTasks)
{
restoreBackup();
}
this.cleanupBackupTasks.Clear();
this.restoreBackupTasks.Clear();
}
private void CommitChanges()
{
foreach (var cleanupBackupTask in this.cleanupBackupTasks)
{
cleanupBackupTask();
}
this.cleanupBackupTasks.Clear();
this.restoreBackupTasks.Clear();
}
private IEnumerable<FileInfo> GetProjectFiles(AssemblyInfoContext context)
{
var workingDirectory = context.WorkingDirectory;
var assemblyInfoFileNames = new HashSet<string>(context.AssemblyInfoFiles);
if (assemblyInfoFileNames.Any(x => !x.IsNullOrWhiteSpace()))
{
foreach (var item in assemblyInfoFileNames)
{
var fullPath = PathHelper.Combine(workingDirectory, item);
if (this.fileSystem.Exists(fullPath))
{
yield return new FileInfo(fullPath);
}
else
{
this.log.Warning($"Specified file {fullPath} was not found and will not be updated.");
}
}
}
else
{
foreach (var item in this.fileSystem.DirectoryEnumerateFiles(workingDirectory, "*", SearchOption.AllDirectories).Where(IsSupportedProjectFile))
{
var assemblyInfoFile = new FileInfo(item);
yield return assemblyInfoFile;
}
}
}
private static bool IsSupportedProjectFile(string fileName)
{
if (fileName.IsNullOrEmpty())
{
return false;
}
return fileName.EndsWith(".csproj") ||
fileName.EndsWith(".fsproj") ||
fileName.EndsWith(".vbproj");
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Security.Policy;
using System.Reflection;
using System.Globalization;
using System.Xml;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Interfaces;
namespace OpenSim.Region.ScriptEngine.Shared.Instance
{
public class ScriptInstance : MarshalByRefObject, IScriptInstance
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IScriptEngine m_Engine;
private IScriptWorkItem m_CurrentResult = null;
private Queue m_EventQueue = new Queue(32);
private bool m_RunEvents = false;
private UUID m_ItemID;
private uint m_LocalID;
private UUID m_ObjectID;
private UUID m_AssetID;
private IScript m_Script;
private UUID m_AppDomain;
private DetectParams[] m_DetectParams;
private bool m_TimerQueued;
private DateTime m_EventStart;
private bool m_InEvent;
private string m_PrimName;
private string m_ScriptName;
private string m_Assembly;
private int m_StartParam;
private string m_CurrentEvent = String.Empty;
private bool m_InSelfDelete;
private int m_MaxScriptQueue;
private bool m_SaveState = true;
private bool m_ShuttingDown;
private int m_ControlEventsInQueue;
private int m_LastControlLevel;
private bool m_CollisionInQueue;
private TaskInventoryItem m_thisScriptTask;
// The following is for setting a minimum delay between events
private double m_minEventDelay;
private long m_eventDelayTicks;
private long m_nextEventTimeTicks;
private bool m_startOnInit = true;
private UUID m_AttachedAvatar;
private StateSource m_stateSource;
private bool m_postOnRez;
private bool m_startedFromSavedState;
private UUID m_CurrentStateHash;
private UUID m_RegionID;
private bool m_Suspended = false;
private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
m_LineMap;
public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
LineMap
{
get { return m_LineMap; }
set { m_LineMap = value; }
}
private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
// Script state
private string m_State="default";
public Object[] PluginData = new Object[0];
/// <summary>
/// Used by llMinEventDelay to suppress events happening any faster than this speed.
/// This currently restricts all events in one go. Not sure if each event type has
/// its own check so take the simple route first.
/// </summary>
public double MinEventDelay
{
get { return m_minEventDelay; }
set
{
if (value > 0.001)
m_minEventDelay = value;
else
m_minEventDelay = 0.0;
m_eventDelayTicks = (long)(m_minEventDelay * 10000000L);
m_nextEventTimeTicks = DateTime.Now.Ticks;
}
}
public bool Running
{
get { return m_RunEvents; }
set { m_RunEvents = value; }
}
public bool ShuttingDown
{
get { return m_ShuttingDown; }
set { m_ShuttingDown = value; }
}
public string State
{
get { return m_State; }
set { m_State = value; }
}
public IScriptEngine Engine
{
get { return m_Engine; }
}
public UUID AppDomain
{
get { return m_AppDomain; }
set { m_AppDomain = value; }
}
public string PrimName
{
get { return m_PrimName; }
}
public string ScriptName
{
get { return m_ScriptName; }
}
public UUID ItemID
{
get { return m_ItemID; }
}
public UUID ObjectID
{
get { return m_ObjectID; }
}
public uint LocalID
{
get { return m_LocalID; }
}
public UUID AssetID
{
get { return m_AssetID; }
}
public Queue EventQueue
{
get { return m_EventQueue; }
}
public void ClearQueue()
{
m_TimerQueued = false;
m_EventQueue.Clear();
}
public int StartParam
{
get { return m_StartParam; }
set { m_StartParam = value; }
}
public TaskInventoryItem ScriptTask
{
get { return m_thisScriptTask; }
}
public ScriptInstance(IScriptEngine engine, SceneObjectPart part,
UUID itemID, UUID assetID, string assembly,
AppDomain dom, string primName, string scriptName,
int startParam, bool postOnRez, StateSource stateSource,
int maxScriptQueue)
{
m_Engine = engine;
m_LocalID = part.LocalId;
m_ObjectID = part.UUID;
m_ItemID = itemID;
m_AssetID = assetID;
m_PrimName = primName;
m_ScriptName = scriptName;
m_Assembly = assembly;
m_StartParam = startParam;
m_MaxScriptQueue = maxScriptQueue;
m_stateSource = stateSource;
m_postOnRez = postOnRez;
m_AttachedAvatar = part.AttachedAvatar;
m_RegionID = part.ParentGroup.Scene.RegionInfo.RegionID;
if (part != null)
{
lock (part.TaskInventory)
{
if (part.TaskInventory.ContainsKey(m_ItemID))
{
m_thisScriptTask = part.TaskInventory[m_ItemID];
}
}
}
ApiManager am = new ApiManager();
foreach (string api in am.GetApis())
{
m_Apis[api] = am.CreateApi(api);
m_Apis[api].Initialize(engine, part, m_LocalID, itemID);
}
try
{
if (dom != System.AppDomain.CurrentDomain)
m_Script = (IScript)dom.CreateInstanceAndUnwrap(
Path.GetFileNameWithoutExtension(assembly),
"SecondLife.Script");
else
m_Script = (IScript)Assembly.Load(
Path.GetFileNameWithoutExtension(assembly)).CreateInstance(
"SecondLife.Script");
//ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
//RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
// lease.Register(this);
}
catch (Exception)
{
// m_log.ErrorFormat("[Script] Error loading assembly {0}\n"+e.ToString(), assembly);
}
try
{
foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
{
m_Script.InitApi(kv.Key, kv.Value);
}
// // m_log.Debug("[Script] Script instance created");
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
}
catch (Exception)
{
// m_log.Error("[Script] Error loading script instance\n"+e.ToString());
return;
}
m_SaveState = true;
string savedState = Path.Combine(Path.GetDirectoryName(assembly),
m_ItemID.ToString() + ".state");
if (File.Exists(savedState))
{
string xml = String.Empty;
try
{
FileInfo fi = new FileInfo(savedState);
int size = (int)fi.Length;
if (size < 512000)
{
using (FileStream fs = File.Open(savedState,
FileMode.Open, FileAccess.Read, FileShare.None))
{
System.Text.UTF8Encoding enc =
new System.Text.UTF8Encoding();
Byte[] data = new Byte[size];
fs.Read(data, 0, size);
xml = enc.GetString(data);
ScriptSerializer.Deserialize(xml, this);
AsyncCommandManager.CreateFromData(m_Engine,
m_LocalID, m_ItemID, m_ObjectID,
PluginData);
// m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName);
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
if (m_RunEvents && (!m_ShuttingDown))
{
m_RunEvents = false;
}
else
{
m_RunEvents = false;
m_startOnInit = false;
}
// we get new rez events on sim restart, too
// but if there is state, then we fire the change
// event
// We loaded state, don't force a re-save
m_SaveState = false;
m_startedFromSavedState = true;
}
}
else
{
// m_log.Error("[Script] Unable to load script state: Memory limit exceeded");
}
}
catch (Exception)
{
// m_log.ErrorFormat("[Script] Unable to load script state from xml: {0}\n"+e.ToString(), xml);
}
}
// else
// {
// ScenePresence presence = m_Engine.World.GetScenePresence(part.OwnerID);
// if (presence != null && (!postOnRez))
// presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);
// }
}
public void Init()
{
if (!m_startOnInit) return;
if (m_startedFromSavedState)
{
Start();
if (m_postOnRez)
{
PostEvent(new EventParams("on_rez",
new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
}
if (m_stateSource == StateSource.AttachedRez)
{
PostEvent(new EventParams("attach",
new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
}
else if (m_stateSource == StateSource.RegionStart)
{
//m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script");
PostEvent(new EventParams("changed",
new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0]));
}
else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting)
{
// CHANGED_REGION
PostEvent(new EventParams("changed",
new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0]));
// CHANGED_TELEPORT
if (m_stateSource == StateSource.Teleporting)
PostEvent(new EventParams("changed",
new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0]));
}
}
else
{
Start();
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
if (m_postOnRez)
{
PostEvent(new EventParams("on_rez",
new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
}
if (m_stateSource == StateSource.AttachedRez)
{
PostEvent(new EventParams("attach",
new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
}
}
}
private void ReleaseControls()
{
SceneObjectPart part = m_Engine.World.GetSceneObjectPart(m_LocalID);
if (part != null)
{
int permsMask;
UUID permsGranter;
lock (part.TaskInventory)
{
if (!part.TaskInventory.ContainsKey(m_ItemID))
return;
permsGranter = part.TaskInventory[m_ItemID].PermsGranter;
permsMask = part.TaskInventory[m_ItemID].PermsMask;
}
if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
{
ScenePresence presence = m_Engine.World.GetScenePresence(permsGranter);
if (presence != null)
presence.UnRegisterControlEventsToScript(m_LocalID, m_ItemID);
}
}
}
public void DestroyScriptInstance()
{
ReleaseControls();
AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
}
public void RemoveState()
{
string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
m_ItemID.ToString() + ".state");
try
{
File.Delete(savedState);
}
catch(Exception)
{
}
}
public void VarDump(Dictionary<string, object> vars)
{
// m_log.Info("Variable dump for script "+ m_ItemID.ToString());
// foreach (KeyValuePair<string, object> v in vars)
// {
// m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
// }
}
public void Start()
{
lock (m_EventQueue)
{
if (Running)
return;
m_RunEvents = true;
if (m_EventQueue.Count > 0)
{
if (m_CurrentResult == null)
m_CurrentResult = m_Engine.QueueEventHandler(this);
// else
// m_log.Error("[Script] Tried to start a script that was already queued");
}
}
}
public bool Stop(int timeout)
{
IScriptWorkItem result;
lock (m_EventQueue)
{
if (!Running)
return true;
if (m_CurrentResult == null)
{
m_RunEvents = false;
return true;
}
if (m_CurrentResult.Cancel())
{
m_CurrentResult = null;
m_RunEvents = false;
return true;
}
result = m_CurrentResult;
m_RunEvents = false;
}
if (result.Wait(new TimeSpan((long)timeout * 100000)))
{
return true;
}
lock (m_EventQueue)
{
result = m_CurrentResult;
}
if (result == null)
return true;
if (!m_InSelfDelete)
result.Abort();
lock (m_EventQueue)
{
m_CurrentResult = null;
}
return true;
}
public void SetState(string state)
{
if (state == State)
return;
PostEvent(new EventParams("state_exit", new Object[0],
new DetectParams[0]));
PostEvent(new EventParams("state", new Object[] { state },
new DetectParams[0]));
PostEvent(new EventParams("state_entry", new Object[0],
new DetectParams[0]));
throw new EventAbortException();
}
public void PostEvent(EventParams data)
{
// m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
// m_PrimName, m_ScriptName, data.EventName, m_State);
if (!Running)
return;
// If min event delay is set then ignore any events untill the time has expired
// This currently only allows 1 event of any type in the given time period.
// This may need extending to allow for a time for each individual event type.
if (m_eventDelayTicks != 0)
{
if (DateTime.Now.Ticks < m_nextEventTimeTicks)
return;
m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
}
lock (m_EventQueue)
{
if (m_EventQueue.Count >= m_MaxScriptQueue)
return;
if (data.EventName == "timer")
{
if (m_TimerQueued)
return;
m_TimerQueued = true;
}
if (data.EventName == "control")
{
int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
// int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
// If the last message was a 0 (nothing held)
// and this one is also nothing held, drop it
//
if (m_LastControlLevel == held && held == 0)
return;
// If there is one or more queued, then queue
// only changed ones, else queue unconditionally
//
if (m_ControlEventsInQueue > 0)
{
if (m_LastControlLevel == held)
return;
}
m_LastControlLevel = held;
m_ControlEventsInQueue++;
}
if (data.EventName == "collision")
{
if (m_CollisionInQueue)
return;
if (data.DetectParams == null)
return;
m_CollisionInQueue = true;
}
m_EventQueue.Enqueue(data);
if (m_CurrentResult == null)
{
m_CurrentResult = m_Engine.QueueEventHandler(this);
}
}
}
/// <summary>
/// Process the next event queued for this script
/// </summary>
/// <returns></returns>
public object EventProcessor()
{
if (m_Suspended)
return 0;
lock (m_Script)
{
EventParams data = null;
lock (m_EventQueue)
{
data = (EventParams) m_EventQueue.Dequeue();
if (data == null) // Shouldn't happen
{
if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
{
m_CurrentResult = m_Engine.QueueEventHandler(this);
}
else
{
m_CurrentResult = null;
}
return 0;
}
if (data.EventName == "timer")
m_TimerQueued = false;
if (data.EventName == "control")
{
if (m_ControlEventsInQueue > 0)
m_ControlEventsInQueue--;
}
if (data.EventName == "collision")
m_CollisionInQueue = false;
}
//m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this);
m_DetectParams = data.DetectParams;
if (data.EventName == "state") // Hardcoded state change
{
// m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}",
// m_PrimName, m_ScriptName, data.Params[0].ToString());
m_State=data.Params[0].ToString();
AsyncCommandManager.RemoveScript(m_Engine,
m_LocalID, m_ItemID);
SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
m_LocalID);
if (part != null)
{
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
}
}
else
{
if (m_Engine.World.PipeEventsForScript(m_LocalID) ||
data.EventName == "control") // Don't freeze avies!
{
SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
m_LocalID);
// m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
// m_PrimName, m_ScriptName, data.EventName, m_State);
try
{
m_CurrentEvent = data.EventName;
m_EventStart = DateTime.Now;
m_InEvent = true;
m_Script.ExecuteEvent(State, data.EventName, data.Params);
m_InEvent = false;
m_CurrentEvent = String.Empty;
if (m_SaveState)
{
// This will be the very first event we deliver
// (state_entry) in default state
//
SaveState(m_Assembly);
m_SaveState = false;
}
}
catch (Exception e)
{
// m_log.DebugFormat("[SCRIPT] Exception: {0}", e.Message);
m_InEvent = false;
m_CurrentEvent = String.Empty;
if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException))
{
try
{
// DISPLAY ERROR INWORLD
string text = FormatException(e);
if (text.Length > 1000)
text = text.Substring(0, 1000);
m_Engine.World.SimChat(Utils.StringToBytes(text),
ChatTypeEnum.DebugChannel, 2147483647,
part.AbsolutePosition,
part.Name, part.UUID, false);
}
catch (Exception)
{
}
// catch (Exception e2) // LEGIT: User Scripting
// {
// m_log.Error("[SCRIPT]: "+
// "Error displaying error in-world: " +
// e2.ToString());
// m_log.Error("[SCRIPT]: " +
// "Errormessage: Error compiling script:\r\n" +
// e.ToString());
// }
}
else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
{
m_InSelfDelete = true;
if (part != null && part.ParentGroup != null)
m_Engine.World.DeleteSceneObject(part.ParentGroup, false);
}
else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
{
m_InSelfDelete = true;
if (part != null && part.ParentGroup != null)
part.Inventory.RemoveInventoryItem(m_ItemID);
}
}
}
}
lock (m_EventQueue)
{
if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
{
m_CurrentResult = m_Engine.QueueEventHandler(this);
}
else
{
m_CurrentResult = null;
}
}
m_DetectParams = null;
return 0;
}
}
public int EventTime()
{
if (!m_InEvent)
return 0;
return (DateTime.Now - m_EventStart).Seconds;
}
public void ResetScript()
{
if (m_Script == null)
return;
bool running = Running;
RemoveState();
ReleaseControls();
Stop(0);
SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
m_EventQueue.Clear();
m_Script.ResetVars();
m_State = "default";
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
if (running)
Start();
m_SaveState = true;
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
}
public void ApiResetScript()
{
// bool running = Running;
RemoveState();
ReleaseControls();
m_Script.ResetVars();
SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
m_EventQueue.Clear();
m_Script.ResetVars();
m_State = "default";
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
if (m_CurrentEvent != "state_entry")
{
m_SaveState = true;
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
throw new EventAbortException();
}
}
public Dictionary<string, object> GetVars()
{
if (m_Script != null)
return m_Script.GetVars();
else
return new Dictionary<string, object>();
}
public void SetVars(Dictionary<string, object> vars)
{
m_Script.SetVars(vars);
}
public DetectParams GetDetectParams(int idx)
{
if (m_DetectParams == null)
return null;
if (idx < 0 || idx >= m_DetectParams.Length)
return null;
return m_DetectParams[idx];
}
public UUID GetDetectID(int idx)
{
if (m_DetectParams == null)
return UUID.Zero;
if (idx < 0 || idx >= m_DetectParams.Length)
return UUID.Zero;
return m_DetectParams[idx].Key;
}
public void SaveState(string assembly)
{
// If we're currently in an event, just tell it to save upon return
//
if (m_InEvent)
{
m_SaveState = true;
return;
}
PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
string xml = ScriptSerializer.Serialize(this);
// Compare hash of the state we just just created with the state last written to disk
// If the state is different, update the disk file.
UUID hash = UUID.Parse(Utils.MD5String(xml));
if (hash != m_CurrentStateHash)
{
try
{
FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"));
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
Byte[] buf = enc.GetBytes(xml);
fs.Write(buf, 0, buf.Length);
fs.Close();
}
catch(Exception)
{
// m_log.Error("Unable to save xml\n"+e.ToString());
}
//if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state")))
//{
// throw new Exception("Completed persistence save, but no file was created");
//}
m_CurrentStateHash = hash;
}
}
public IScriptApi GetApi(string name)
{
if (m_Apis.ContainsKey(name))
return m_Apis[name];
return null;
}
public override string ToString()
{
return String.Format("{0} {1} on {2}", m_ScriptName, m_ItemID, m_PrimName);
}
string FormatException(Exception e)
{
if (e.InnerException == null) // Not a normal runtime error
return e.ToString();
string message = "Runtime error:\n" + e.InnerException.StackTrace;
string[] lines = message.Split(new char[] {'\n'});
foreach (string line in lines)
{
if (line.Contains("SecondLife.Script"))
{
int idx = line.IndexOf(':');
if (idx != -1)
{
string val = line.Substring(idx+1);
int lineNum = 0;
if (int.TryParse(val, out lineNum))
{
KeyValuePair<int, int> pos =
Compiler.FindErrorPosition(
lineNum, 0, LineMap);
int scriptLine = pos.Key;
int col = pos.Value;
if (scriptLine == 0)
scriptLine++;
if (col == 0)
col++;
message = string.Format("Runtime error:\n" +
"({0}): {1}", scriptLine - 1,
e.InnerException.Message);
System.Console.WriteLine(e.ToString()+"\n");
return message;
}
}
}
}
// m_log.ErrorFormat("Scripting exception:");
// m_log.ErrorFormat(e.ToString());
return e.ToString();
}
public string GetAssemblyName()
{
return m_Assembly;
}
public string GetXMLState()
{
bool run = Running;
Stop(100);
Running = run;
// We should not be doing this, but since we are about to
// dispose this, it really doesn't make a difference
// This is meant to work around a Windows only race
//
m_InEvent = false;
// Force an update of the in-memory plugin data
//
PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
return ScriptSerializer.Serialize(this);
}
public UUID RegionID
{
get { return m_RegionID; }
}
public void Suspend()
{
m_Suspended = true;
}
public void Resume()
{
m_Suspended = false;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileFastHttpBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileFastHttpProfileFastHttpStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileString))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileProfileMode))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileUncleanShutdownMode))]
public partial class LocalLBProfileFastHttp : iControlInterface {
public LocalLBProfileFastHttp() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void create(
string [] profile_names
) {
this.Invoke("create", new object [] {
profile_names});
}
public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
profile_names}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_profiles
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void delete_all_profiles(
) {
this.Invoke("delete_all_profiles", new object [0]);
}
public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState);
}
public void Enddelete_all_profiles(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void delete_profile(
string [] profile_names
) {
this.Invoke("delete_profile", new object [] {
profile_names});
}
public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_profile", new object[] {
profile_names}, callback, asyncState);
}
public void Enddelete_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileFastHttpProfileFastHttpStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBProfileFastHttpProfileFastHttpStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBProfileFastHttpProfileFastHttpStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileFastHttpProfileFastHttpStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_client_close_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_client_close_timeout(
string [] profile_names
) {
object [] results = this.Invoke("get_client_close_timeout", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_client_close_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_client_close_timeout", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_client_close_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_pool_idle_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_connection_pool_idle_timeout(
string [] profile_names
) {
object [] results = this.Invoke("get_connection_pool_idle_timeout", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_connection_pool_idle_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_pool_idle_timeout", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_connection_pool_idle_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_pool_maximum_reuse
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_connection_pool_maximum_reuse(
string [] profile_names
) {
object [] results = this.Invoke("get_connection_pool_maximum_reuse", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_connection_pool_maximum_reuse(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_pool_maximum_reuse", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_connection_pool_maximum_reuse(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_pool_maximum_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_connection_pool_maximum_size(
string [] profile_names
) {
object [] results = this.Invoke("get_connection_pool_maximum_size", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_connection_pool_maximum_size(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_pool_maximum_size", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_connection_pool_maximum_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_pool_minimum_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_connection_pool_minimum_size(
string [] profile_names
) {
object [] results = this.Invoke("get_connection_pool_minimum_size", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_connection_pool_minimum_size(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_pool_minimum_size", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_connection_pool_minimum_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_pool_ramp_increment
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_connection_pool_ramp_increment(
string [] profile_names
) {
object [] results = this.Invoke("get_connection_pool_ramp_increment", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_connection_pool_ramp_increment(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_pool_ramp_increment", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_connection_pool_ramp_increment(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_pool_replenish_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_connection_pool_replenish_state(
string [] profile_names
) {
object [] results = this.Invoke("get_connection_pool_replenish_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_connection_pool_replenish_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_pool_replenish_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_connection_pool_replenish_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_default_profile(
string [] profile_names
) {
object [] results = this.Invoke("get_default_profile", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_profile", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] profile_names
) {
object [] results = this.Invoke("get_description", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_force_http10_response_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_force_http10_response_state(
string [] profile_names
) {
object [] results = this.Invoke("get_force_http10_response_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_force_http10_response_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_force_http10_response_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_force_http10_response_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_header_insert
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_header_insert(
string [] profile_names
) {
object [] results = this.Invoke("get_header_insert", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_header_insert(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_header_insert", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_header_insert(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_http11_close_workarounds_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_http11_close_workarounds_state(
string [] profile_names
) {
object [] results = this.Invoke("get_http11_close_workarounds_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_http11_close_workarounds_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_http11_close_workarounds_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_http11_close_workarounds_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_idle_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_idle_timeout(
string [] profile_names
) {
object [] results = this.Invoke("get_idle_timeout", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_idle_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_idle_timeout", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_idle_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_insert_xforwarded_for_header_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileProfileMode [] get_insert_xforwarded_for_header_mode(
string [] profile_names
) {
object [] results = this.Invoke("get_insert_xforwarded_for_header_mode", new object [] {
profile_names});
return ((LocalLBProfileProfileMode [])(results[0]));
}
public System.IAsyncResult Beginget_insert_xforwarded_for_header_mode(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_insert_xforwarded_for_header_mode", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileProfileMode [] Endget_insert_xforwarded_for_header_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileProfileMode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_layer7_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_layer7_state(
string [] profile_names
) {
object [] results = this.Invoke("get_layer7_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_layer7_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_layer7_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_layer7_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_maximum_header_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_maximum_header_size(
string [] profile_names
) {
object [] results = this.Invoke("get_maximum_header_size", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_maximum_header_size(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_maximum_header_size", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_maximum_header_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_maximum_requests
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_maximum_requests(
string [] profile_names
) {
object [] results = this.Invoke("get_maximum_requests", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_maximum_requests(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_maximum_requests", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_maximum_requests(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mss_override
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_mss_override(
string [] profile_names
) {
object [] results = this.Invoke("get_mss_override", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_mss_override(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mss_override", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_mss_override(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_reset_on_timeout_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_reset_on_timeout_state(
string [] profile_names
) {
object [] results = this.Invoke("get_reset_on_timeout_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_reset_on_timeout_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_reset_on_timeout_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_reset_on_timeout_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_server_close_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_server_close_timeout(
string [] profile_names
) {
object [] results = this.Invoke("get_server_close_timeout", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_server_close_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_server_close_timeout", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_server_close_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileFastHttpProfileFastHttpStatistics get_statistics(
string [] profile_names
) {
object [] results = this.Invoke("get_statistics", new object [] {
profile_names});
return ((LocalLBProfileFastHttpProfileFastHttpStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileFastHttpProfileFastHttpStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileFastHttpProfileFastHttpStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
object [] results = this.Invoke("get_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
//-----------------------------------------------------------------------
// get_unclean_shutdown_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileUncleanShutdownMode [] get_unclean_shutdown_mode(
string [] profile_names
) {
object [] results = this.Invoke("get_unclean_shutdown_mode", new object [] {
profile_names});
return ((LocalLBProfileUncleanShutdownMode [])(results[0]));
}
public System.IAsyncResult Beginget_unclean_shutdown_mode(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_unclean_shutdown_mode", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileUncleanShutdownMode [] Endget_unclean_shutdown_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileUncleanShutdownMode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_base_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_base_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_base_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_base_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_base_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// is_system_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_system_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_system_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_system_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_system_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void reset_statistics(
string [] profile_names
) {
this.Invoke("reset_statistics", new object [] {
profile_names});
}
public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
profile_names}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void reset_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
this.Invoke("reset_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
}
public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_client_close_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_client_close_timeout(
string [] profile_names,
LocalLBProfileULong [] timeouts
) {
this.Invoke("set_client_close_timeout", new object [] {
profile_names,
timeouts});
}
public System.IAsyncResult Beginset_client_close_timeout(string [] profile_names,LocalLBProfileULong [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_client_close_timeout", new object[] {
profile_names,
timeouts}, callback, asyncState);
}
public void Endset_client_close_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_pool_idle_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_connection_pool_idle_timeout(
string [] profile_names,
LocalLBProfileULong [] timeouts
) {
this.Invoke("set_connection_pool_idle_timeout", new object [] {
profile_names,
timeouts});
}
public System.IAsyncResult Beginset_connection_pool_idle_timeout(string [] profile_names,LocalLBProfileULong [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_pool_idle_timeout", new object[] {
profile_names,
timeouts}, callback, asyncState);
}
public void Endset_connection_pool_idle_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_pool_maximum_reuse
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_connection_pool_maximum_reuse(
string [] profile_names,
LocalLBProfileULong [] reuses
) {
this.Invoke("set_connection_pool_maximum_reuse", new object [] {
profile_names,
reuses});
}
public System.IAsyncResult Beginset_connection_pool_maximum_reuse(string [] profile_names,LocalLBProfileULong [] reuses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_pool_maximum_reuse", new object[] {
profile_names,
reuses}, callback, asyncState);
}
public void Endset_connection_pool_maximum_reuse(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_pool_maximum_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_connection_pool_maximum_size(
string [] profile_names,
LocalLBProfileULong [] sizes
) {
this.Invoke("set_connection_pool_maximum_size", new object [] {
profile_names,
sizes});
}
public System.IAsyncResult Beginset_connection_pool_maximum_size(string [] profile_names,LocalLBProfileULong [] sizes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_pool_maximum_size", new object[] {
profile_names,
sizes}, callback, asyncState);
}
public void Endset_connection_pool_maximum_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_pool_minimum_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_connection_pool_minimum_size(
string [] profile_names,
LocalLBProfileULong [] sizes
) {
this.Invoke("set_connection_pool_minimum_size", new object [] {
profile_names,
sizes});
}
public System.IAsyncResult Beginset_connection_pool_minimum_size(string [] profile_names,LocalLBProfileULong [] sizes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_pool_minimum_size", new object[] {
profile_names,
sizes}, callback, asyncState);
}
public void Endset_connection_pool_minimum_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_pool_ramp_increment
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_connection_pool_ramp_increment(
string [] profile_names,
LocalLBProfileULong [] increments
) {
this.Invoke("set_connection_pool_ramp_increment", new object [] {
profile_names,
increments});
}
public System.IAsyncResult Beginset_connection_pool_ramp_increment(string [] profile_names,LocalLBProfileULong [] increments, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_pool_ramp_increment", new object[] {
profile_names,
increments}, callback, asyncState);
}
public void Endset_connection_pool_ramp_increment(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_pool_replenish_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_connection_pool_replenish_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_connection_pool_replenish_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_connection_pool_replenish_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_pool_replenish_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_connection_pool_replenish_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_default_profile(
string [] profile_names,
string [] defaults
) {
this.Invoke("set_default_profile", new object [] {
profile_names,
defaults});
}
public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_profile", new object[] {
profile_names,
defaults}, callback, asyncState);
}
public void Endset_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_description(
string [] profile_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
profile_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
profile_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_force_http10_response_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_force_http10_response_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_force_http10_response_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_force_http10_response_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_force_http10_response_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_force_http10_response_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_header_insert
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_header_insert(
string [] profile_names,
LocalLBProfileString [] headers
) {
this.Invoke("set_header_insert", new object [] {
profile_names,
headers});
}
public System.IAsyncResult Beginset_header_insert(string [] profile_names,LocalLBProfileString [] headers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_header_insert", new object[] {
profile_names,
headers}, callback, asyncState);
}
public void Endset_header_insert(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_http11_close_workarounds_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_http11_close_workarounds_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_http11_close_workarounds_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_http11_close_workarounds_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_http11_close_workarounds_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_http11_close_workarounds_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_idle_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_idle_timeout(
string [] profile_names,
LocalLBProfileULong [] timeouts
) {
this.Invoke("set_idle_timeout", new object [] {
profile_names,
timeouts});
}
public System.IAsyncResult Beginset_idle_timeout(string [] profile_names,LocalLBProfileULong [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_idle_timeout", new object[] {
profile_names,
timeouts}, callback, asyncState);
}
public void Endset_idle_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_insert_xforwarded_for_header_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_insert_xforwarded_for_header_mode(
string [] profile_names,
LocalLBProfileProfileMode [] modes
) {
this.Invoke("set_insert_xforwarded_for_header_mode", new object [] {
profile_names,
modes});
}
public System.IAsyncResult Beginset_insert_xforwarded_for_header_mode(string [] profile_names,LocalLBProfileProfileMode [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_insert_xforwarded_for_header_mode", new object[] {
profile_names,
modes}, callback, asyncState);
}
public void Endset_insert_xforwarded_for_header_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_layer7_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_layer7_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_layer7_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_layer7_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_layer7_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_layer7_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_maximum_header_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_maximum_header_size(
string [] profile_names,
LocalLBProfileULong [] sizes
) {
this.Invoke("set_maximum_header_size", new object [] {
profile_names,
sizes});
}
public System.IAsyncResult Beginset_maximum_header_size(string [] profile_names,LocalLBProfileULong [] sizes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_maximum_header_size", new object[] {
profile_names,
sizes}, callback, asyncState);
}
public void Endset_maximum_header_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_maximum_requests
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_maximum_requests(
string [] profile_names,
LocalLBProfileULong [] maximum_requests
) {
this.Invoke("set_maximum_requests", new object [] {
profile_names,
maximum_requests});
}
public System.IAsyncResult Beginset_maximum_requests(string [] profile_names,LocalLBProfileULong [] maximum_requests, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_maximum_requests", new object[] {
profile_names,
maximum_requests}, callback, asyncState);
}
public void Endset_maximum_requests(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_mss_override
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_mss_override(
string [] profile_names,
LocalLBProfileULong [] mss_overrides
) {
this.Invoke("set_mss_override", new object [] {
profile_names,
mss_overrides});
}
public System.IAsyncResult Beginset_mss_override(string [] profile_names,LocalLBProfileULong [] mss_overrides, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_mss_override", new object[] {
profile_names,
mss_overrides}, callback, asyncState);
}
public void Endset_mss_override(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_reset_on_timeout_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_reset_on_timeout_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_reset_on_timeout_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_reset_on_timeout_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_reset_on_timeout_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_reset_on_timeout_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_server_close_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_server_close_timeout(
string [] profile_names,
LocalLBProfileULong [] timeouts
) {
this.Invoke("set_server_close_timeout", new object [] {
profile_names,
timeouts});
}
public System.IAsyncResult Beginset_server_close_timeout(string [] profile_names,LocalLBProfileULong [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_server_close_timeout", new object[] {
profile_names,
timeouts}, callback, asyncState);
}
public void Endset_server_close_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_unclean_shutdown_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileFastHttp",
RequestNamespace="urn:iControl:LocalLB/ProfileFastHttp", ResponseNamespace="urn:iControl:LocalLB/ProfileFastHttp")]
public void set_unclean_shutdown_mode(
string [] profile_names,
LocalLBProfileUncleanShutdownMode [] modes
) {
this.Invoke("set_unclean_shutdown_mode", new object [] {
profile_names,
modes});
}
public System.IAsyncResult Beginset_unclean_shutdown_mode(string [] profile_names,LocalLBProfileUncleanShutdownMode [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_unclean_shutdown_mode", new object[] {
profile_names,
modes}, callback, asyncState);
}
public void Endset_unclean_shutdown_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileFastHttp.ProfileFastHttpStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBProfileFastHttpProfileFastHttpStatisticEntry
{
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileFastHttp.ProfileFastHttpStatistics", Namespace = "urn:iControl")]
public partial class LocalLBProfileFastHttpProfileFastHttpStatistics
{
private LocalLBProfileFastHttpProfileFastHttpStatisticEntry [] statisticsField;
public LocalLBProfileFastHttpProfileFastHttpStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
#region License
/*
* HttpListener.cs
*
* This code is derived from HttpListener.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2016 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
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
// TODO: Logging.
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a simple, programmatically controlled HTTP listener.
/// </summary>
public sealed class HttpListener : IDisposable
{
#region Private Fields
private AuthenticationSchemes _authSchemes;
private Func<HttpListenerRequest, AuthenticationSchemes> _authSchemeSelector;
private string _certFolderPath;
private Dictionary<HttpConnection, HttpConnection> _connections;
private object _connectionsSync;
private List<HttpListenerContext> _ctxQueue;
private object _ctxQueueSync;
private Dictionary<HttpListenerContext, HttpListenerContext> _ctxRegistry;
private object _ctxRegistrySync;
private static readonly string _defaultRealm;
private bool _disposed;
private bool _ignoreWriteExceptions;
private volatile bool _listening;
private Logger _logger;
private HttpListenerPrefixCollection _prefixes;
private string _realm;
private bool _reuseAddress;
private ServerSslConfiguration _sslConfig;
private Func<IIdentity, NetworkCredential> _userCredFinder;
private List<HttpListenerAsyncResult> _waitQueue;
private object _waitQueueSync;
#endregion
#region Static Constructor
static HttpListener ()
{
_defaultRealm = "SECRET AREA";
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpListener"/> class.
/// </summary>
public HttpListener ()
{
_authSchemes = AuthenticationSchemes.Anonymous;
_connections = new Dictionary<HttpConnection, HttpConnection> ();
_connectionsSync = ((ICollection) _connections).SyncRoot;
_ctxQueue = new List<HttpListenerContext> ();
_ctxQueueSync = ((ICollection) _ctxQueue).SyncRoot;
_ctxRegistry = new Dictionary<HttpListenerContext, HttpListenerContext> ();
_ctxRegistrySync = ((ICollection) _ctxRegistry).SyncRoot;
_logger = new Logger ();
_prefixes = new HttpListenerPrefixCollection (this);
_waitQueue = new List<HttpListenerAsyncResult> ();
_waitQueueSync = ((ICollection) _waitQueue).SyncRoot;
}
#endregion
#region Internal Properties
internal bool IsDisposed {
get {
return _disposed;
}
}
internal bool ReuseAddress {
get {
return _reuseAddress;
}
set {
_reuseAddress = value;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// represents the scheme used to authenticate the clients. The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public AuthenticationSchemes AuthenticationSchemes {
get {
CheckDisposed ();
return _authSchemes;
}
set {
CheckDisposed ();
_authSchemes = value;
}
}
/// <summary>
/// Gets or sets the delegate called to select the scheme used to authenticate the clients.
/// </summary>
/// <remarks>
/// If you set this property, the listener uses the authentication scheme selected by
/// the delegate for each request. Or if you don't set, the listener uses the value of
/// the <see cref="HttpListener.AuthenticationSchemes"/> property as the authentication
/// scheme for all requests.
/// </remarks>
/// <value>
/// A <c>Func<<see cref="HttpListenerRequest"/>, <see cref="AuthenticationSchemes"/>></c>
/// delegate that references the method used to select an authentication scheme. The default
/// value is <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public Func<HttpListenerRequest, AuthenticationSchemes> AuthenticationSchemeSelector {
get {
CheckDisposed ();
return _authSchemeSelector;
}
set {
CheckDisposed ();
_authSchemeSelector = value;
}
}
/// <summary>
/// Gets or sets the path to the folder in which stores the certificate files used to
/// authenticate the server on the secure connection.
/// </summary>
/// <remarks>
/// <para>
/// This property represents the path to the folder in which stores the certificate files
/// associated with each port number of added URI prefixes. A set of the certificate files
/// is a pair of the <c>'port number'.cer</c> (DER) and <c>'port number'.key</c>
/// (DER, RSA Private Key).
/// </para>
/// <para>
/// If this property is <see langword="null"/> or empty, the result of
/// <c>System.Environment.GetFolderPath
/// (<see cref="Environment.SpecialFolder.ApplicationData"/>)</c> is used as the default path.
/// </para>
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the path to the folder in which stores
/// the certificate files. The default value is <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public string CertificateFolderPath {
get {
CheckDisposed ();
return _certFolderPath;
}
set {
CheckDisposed ();
_certFolderPath = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the listener returns exceptions that occur when
/// sending the response to the client.
/// </summary>
/// <value>
/// <c>true</c> if the listener shouldn't return those exceptions; otherwise, <c>false</c>.
/// The default value is <c>false</c>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public bool IgnoreWriteExceptions {
get {
CheckDisposed ();
return _ignoreWriteExceptions;
}
set {
CheckDisposed ();
_ignoreWriteExceptions = value;
}
}
/// <summary>
/// Gets a value indicating whether the listener has been started.
/// </summary>
/// <value>
/// <c>true</c> if the listener has been started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _listening;
}
}
/// <summary>
/// Gets a value indicating whether the listener can be used with the current operating system.
/// </summary>
/// <value>
/// <c>true</c>.
/// </value>
public static bool IsSupported {
get {
return true;
}
}
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it,
/// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum
/// values.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
public Logger Log {
get {
return _logger;
}
}
/// <summary>
/// Gets the URI prefixes handled by the listener.
/// </summary>
/// <value>
/// A <see cref="HttpListenerPrefixCollection"/> that contains the URI prefixes.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerPrefixCollection Prefixes {
get {
CheckDisposed ();
return _prefixes;
}
}
/// <summary>
/// Gets or sets the name of the realm associated with the listener.
/// </summary>
/// <remarks>
/// If this property is <see langword="null"/> or empty, <c>"SECRET AREA"</c> will be used as
/// the name of the realm.
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the name of the realm. The default value is
/// <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public string Realm {
get {
CheckDisposed ();
return _realm;
}
set {
CheckDisposed ();
_realm = value;
}
}
/// <summary>
/// Gets or sets the SSL configuration used to authenticate the server and
/// optionally the client for secure connection.
/// </summary>
/// <value>
/// A <see cref="ServerSslConfiguration"/> that represents the configuration used to
/// authenticate the server and optionally the client for secure connection.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public ServerSslConfiguration SslConfiguration {
get {
CheckDisposed ();
return _sslConfig ?? (_sslConfig = new ServerSslConfiguration ());
}
set {
CheckDisposed ();
_sslConfig = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether, when NTLM authentication is used,
/// the authentication information of first request is used to authenticate
/// additional requests on the same connection.
/// </summary>
/// <remarks>
/// This property isn't currently supported and always throws
/// a <see cref="NotSupportedException"/>.
/// </remarks>
/// <value>
/// <c>true</c> if the authentication information of first request is used;
/// otherwise, <c>false</c>.
/// </value>
/// <exception cref="NotSupportedException">
/// Any use of this property.
/// </exception>
public bool UnsafeConnectionNtlmAuthentication {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for an identity used to
/// authenticate a client.
/// </summary>
/// <value>
/// A <c>Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>></c> delegate
/// that references the method used to find the credentials. The default value is
/// <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
CheckDisposed ();
return _userCredFinder;
}
set {
CheckDisposed ();
_userCredFinder = value;
}
}
#endregion
#region Private Methods
private void cleanupConnections ()
{
HttpConnection[] conns = null;
lock (_connectionsSync) {
if (_connections.Count == 0)
return;
// Need to copy this since closing will call the RemoveConnection method.
var keys = _connections.Keys;
conns = new HttpConnection[keys.Count];
keys.CopyTo (conns, 0);
_connections.Clear ();
}
for (var i = conns.Length - 1; i >= 0; i--)
conns[i].Close (true);
}
private void cleanupContextQueue (bool sendServiceUnavailable)
{
HttpListenerContext[] ctxs = null;
lock (_ctxQueueSync) {
if (_ctxQueue.Count == 0)
return;
ctxs = _ctxQueue.ToArray ();
_ctxQueue.Clear ();
}
if (!sendServiceUnavailable)
return;
foreach (var ctx in ctxs) {
var res = ctx.Response;
res.StatusCode = (int) HttpStatusCode.ServiceUnavailable;
res.Close ();
}
}
private void cleanupContextRegistry ()
{
HttpListenerContext[] ctxs = null;
lock (_ctxRegistrySync) {
if (_ctxRegistry.Count == 0)
return;
// Need to copy this since closing will call the UnregisterContext method.
var keys = _ctxRegistry.Keys;
ctxs = new HttpListenerContext[keys.Count];
keys.CopyTo (ctxs, 0);
_ctxRegistry.Clear ();
}
for (var i = ctxs.Length - 1; i >= 0; i--)
ctxs[i].Connection.Close (true);
}
private void cleanupWaitQueue (Exception exception)
{
HttpListenerAsyncResult[] aress = null;
lock (_waitQueueSync) {
if (_waitQueue.Count == 0)
return;
aress = _waitQueue.ToArray ();
_waitQueue.Clear ();
}
foreach (var ares in aress)
ares.Complete (exception);
}
private void close (bool force)
{
if (_listening) {
_listening = false;
EndPointManager.RemoveListener (this);
}
lock (_ctxRegistrySync)
cleanupContextQueue (!force);
cleanupContextRegistry ();
cleanupConnections ();
cleanupWaitQueue (new ObjectDisposedException (GetType ().ToString ()));
_disposed = true;
}
private HttpListenerAsyncResult getAsyncResultFromQueue ()
{
if (_waitQueue.Count == 0)
return null;
var ares = _waitQueue[0];
_waitQueue.RemoveAt (0);
return ares;
}
private HttpListenerContext getContextFromQueue ()
{
if (_ctxQueue.Count == 0)
return null;
var ctx = _ctxQueue[0];
_ctxQueue.RemoveAt (0);
return ctx;
}
#endregion
#region Internal Methods
internal bool AddConnection (HttpConnection connection)
{
if (!_listening)
return false;
lock (_connectionsSync) {
if (!_listening)
return false;
_connections[connection] = connection;
return true;
}
}
internal HttpListenerAsyncResult BeginGetContext (HttpListenerAsyncResult asyncResult)
{
lock (_ctxRegistrySync) {
if (!_listening)
throw new HttpListenerException (995);
var ctx = getContextFromQueue ();
if (ctx == null)
_waitQueue.Add (asyncResult);
else
asyncResult.Complete (ctx, true);
return asyncResult;
}
}
internal void CheckDisposed ()
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
}
internal string GetRealm ()
{
var realm = _realm;
return realm != null && realm.Length > 0 ? realm : _defaultRealm;
}
internal Func<IIdentity, NetworkCredential> GetUserCredentialsFinder ()
{
return _userCredFinder;
}
internal bool RegisterContext (HttpListenerContext context)
{
if (!_listening)
return false;
lock (_ctxRegistrySync) {
if (!_listening)
return false;
_ctxRegistry[context] = context;
var ares = getAsyncResultFromQueue ();
if (ares == null)
_ctxQueue.Add (context);
else
ares.Complete (context);
return true;
}
}
internal void RemoveConnection (HttpConnection connection)
{
lock (_connectionsSync)
_connections.Remove (connection);
}
internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerRequest request)
{
var selector = _authSchemeSelector;
if (selector == null)
return _authSchemes;
try {
return selector (request);
}
catch {
return AuthenticationSchemes.None;
}
}
internal void UnregisterContext (HttpListenerContext context)
{
lock (_ctxRegistrySync)
_ctxRegistry.Remove (context);
}
#endregion
#region Public Methods
/// <summary>
/// Shuts down the listener immediately.
/// </summary>
public void Abort ()
{
if (_disposed)
return;
close (true);
}
/// <summary>
/// Begins getting an incoming request asynchronously.
/// </summary>
/// <remarks>
/// This asynchronous operation must be completed by calling the <c>EndGetContext</c> method.
/// Typically, the method is invoked by the <paramref name="callback"/> delegate.
/// </remarks>
/// <returns>
/// An <see cref="IAsyncResult"/> that represents the status of the asynchronous operation.
/// </returns>
/// <param name="callback">
/// An <see cref="AsyncCallback"/> delegate that references the method to invoke when
/// the asynchronous operation completes.
/// </param>
/// <param name="state">
/// An <see cref="object"/> that represents a user defined object to pass to
/// the <paramref name="callback"/> delegate.
/// </param>
/// <exception cref="InvalidOperationException">
/// <para>
/// This listener has no URI prefix on which listens.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// This listener hasn't been started, or is currently stopped.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public IAsyncResult BeginGetContext (AsyncCallback callback, Object state)
{
CheckDisposed ();
if (_prefixes.Count == 0)
throw new InvalidOperationException ("The listener has no URI prefix on which listens.");
if (!_listening)
throw new InvalidOperationException ("The listener hasn't been started.");
return BeginGetContext (new HttpListenerAsyncResult (callback, state));
}
/// <summary>
/// Shuts down the listener.
/// </summary>
public void Close ()
{
if (_disposed)
return;
close (false);
}
/// <summary>
/// Ends an asynchronous operation to get an incoming request.
/// </summary>
/// <remarks>
/// This method completes an asynchronous operation started by calling
/// the <c>BeginGetContext</c> method.
/// </remarks>
/// <returns>
/// A <see cref="HttpListenerContext"/> that represents a request.
/// </returns>
/// <param name="asyncResult">
/// An <see cref="IAsyncResult"/> obtained by calling the <c>BeginGetContext</c> method.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="asyncResult"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="asyncResult"/> wasn't obtained by calling the <c>BeginGetContext</c> method.
/// </exception>
/// <exception cref="InvalidOperationException">
/// This method was already called for the specified <paramref name="asyncResult"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerContext EndGetContext (IAsyncResult asyncResult)
{
CheckDisposed ();
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
var ares = asyncResult as HttpListenerAsyncResult;
if (ares == null)
throw new ArgumentException ("A wrong IAsyncResult.", "asyncResult");
if (ares.EndCalled)
throw new InvalidOperationException ("This IAsyncResult cannot be reused.");
ares.EndCalled = true;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne ();
return ares.GetContext (); // This may throw an exception.
}
/// <summary>
/// Gets an incoming request.
/// </summary>
/// <remarks>
/// This method waits for an incoming request, and returns when a request is received.
/// </remarks>
/// <returns>
/// A <see cref="HttpListenerContext"/> that represents a request.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <para>
/// This listener has no URI prefix on which listens.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// This listener hasn't been started, or is currently stopped.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerContext GetContext ()
{
CheckDisposed ();
if (_prefixes.Count == 0)
throw new InvalidOperationException ("The listener has no URI prefix on which listens.");
if (!_listening)
throw new InvalidOperationException ("The listener hasn't been started.");
var ares = BeginGetContext (new HttpListenerAsyncResult (null, null));
ares.InGet = true;
return EndGetContext (ares);
}
/// <summary>
/// Starts receiving incoming requests.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public void Start ()
{
CheckDisposed ();
if (_listening)
return;
EndPointManager.AddListener (this);
_listening = true;
}
/// <summary>
/// Stops receiving incoming requests.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public void Stop ()
{
CheckDisposed ();
if (!_listening)
return;
_listening = false;
EndPointManager.RemoveListener (this);
lock (_ctxRegistrySync)
cleanupContextQueue (true);
cleanupContextRegistry ();
cleanupConnections ();
cleanupWaitQueue (new HttpListenerException (995, "The listener is stopped."));
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Releases all resources used by the listener.
/// </summary>
void IDisposable.Dispose ()
{
if (_disposed)
return;
close (true);
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2018 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Internal;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// DictionaryContainsKeyConstraint is used to test whether a dictionary
/// contains an expected object as a key.
/// </summary>
public class DictionaryContainsKeyConstraint : CollectionItemsEqualConstraint
{
private const string ObsoleteMessage = "DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.";
private bool _isDeprecatedMode = false;
/// <summary>
/// Construct a DictionaryContainsKeyConstraint
/// </summary>
/// <param name="expected"></param>
public DictionaryContainsKeyConstraint(object expected)
: base(expected)
{
Expected = expected;
}
/// <summary>
/// The display name of this Constraint for use by ToString().
/// The default value is the name of the constraint with
/// trailing "Constraint" removed. Derived classes may set
/// this to another name in their constructors.
/// </summary>
public override string DisplayName { get { return "ContainsKey"; } }
/// <summary>
/// The Description of what this constraint tests, for
/// use in messages and in the ConstraintResult.
/// </summary>
public override string Description
{
get { return "dictionary containing key " + MsgUtils.FormatValue(Expected); }
}
/// <summary>
/// Gets the expected object
/// </summary>
protected object Expected { get; }
/// <summary>
/// Flag the constraint to ignore case and return self.
/// </summary>
[Obsolete(ObsoleteMessage)]
public new CollectionItemsEqualConstraint IgnoreCase
{
get
{
_isDeprecatedMode = true;
return base.IgnoreCase;
}
}
private bool Matches(object actual)
{
if (_isDeprecatedMode)
{
var dictionary = ConstraintUtils.RequireActual<IDictionary>(actual, nameof(actual));
foreach (object obj in dictionary.Keys)
if (ItemsEqual(obj, Expected))
return true;
return false;
}
var method = GetContainsKeyMethod(actual);
if (method != null)
return (bool)method.Invoke(actual, new[] { Expected });
throw new ArgumentException($"The {TypeHelper.GetDisplayName(actual.GetType())} value must have a ContainsKey or Contains(TKey) method.");
}
/// <summary>
/// Test whether the constraint is satisfied by a given value
/// </summary>
/// <param name="actual">The value to be tested</param>
public override ConstraintResult ApplyTo<TActual>(TActual actual)
{
return new ConstraintResult(this, actual, Matches(actual));
}
/// <summary>
/// Test whether the expected key is contained in the dictionary
/// </summary>
protected override bool Matches(IEnumerable collection)
{
return Matches(collection);
}
#region Shadowing CollectionItemsEqualConstraint Methods
/// <summary>
/// Flag the constraint to use the supplied predicate function
/// </summary>
/// <param name="comparison">The comparison function to use.</param>
[Obsolete(ObsoleteMessage)]
public DictionaryContainsKeyConstraint Using<TCollectionType, TMemberType>(Func<TCollectionType, TMemberType, bool> comparison)
{
// reverse the order of the arguments to match expectations of PredicateEqualityComparer
Func<TMemberType, TCollectionType, bool> invertedComparison = (actual, expected) => comparison.Invoke(expected, actual);
_isDeprecatedMode = true;
base.Using(EqualityAdapter.For(invertedComparison));
return this;
}
/// <summary>
/// Flag the constraint to use the supplied Comparison object.
/// </summary>
/// <param name="comparison">The Comparison object to use.</param>
[Obsolete(ObsoleteMessage)]
public new CollectionItemsEqualConstraint Using<T>(Comparison<T> comparison)
{
_isDeprecatedMode = true;
return base.Using(comparison);
}
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
[Obsolete(ObsoleteMessage)]
public new CollectionItemsEqualConstraint Using(IComparer comparer)
{
_isDeprecatedMode = true;
return base.Using(comparer);
}
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
[Obsolete(ObsoleteMessage)]
public new CollectionItemsEqualConstraint Using<T>(IComparer<T> comparer)
{
_isDeprecatedMode = true;
return base.Using(comparer);
}
/// <summary>
/// Flag the constraint to use the supplied IEqualityComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
[Obsolete(ObsoleteMessage)]
public new CollectionItemsEqualConstraint Using(IEqualityComparer comparer)
{
_isDeprecatedMode = true;
return base.Using(comparer);
}
/// <summary>
/// Flag the constraint to use the supplied IEqualityComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
[Obsolete(ObsoleteMessage)]
public new CollectionItemsEqualConstraint Using<T>(IEqualityComparer<T> comparer)
{
_isDeprecatedMode = true;
return base.Using(comparer);
}
/// <summary>
/// Flag the constraint to use the supplied boolean-returning delegate.
/// </summary>
/// <param name="comparer">The supplied boolean-returning delegate to use.</param>
[Obsolete(ObsoleteMessage)]
public new CollectionItemsEqualConstraint Using<T>(Func<T, T, bool> comparer)
{
_isDeprecatedMode = true;
return base.Using(comparer);
}
#endregion
private static MethodInfo GetContainsKeyMethod(object keyedItemContainer)
{
if (keyedItemContainer == null) throw new ArgumentNullException(nameof(keyedItemContainer));
var instanceType = keyedItemContainer.GetType();
var method = FindContainsKeyMethod(instanceType)
?? instanceType
.GetInterfaces()
.Concat(GetBaseTypes(instanceType))
.Select(FindContainsKeyMethod)
.FirstOrDefault(m => m != null);
return method;
}
private static MethodInfo FindContainsKeyMethod(Type type)
{
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
var method = methods.FirstOrDefault(m =>
m.ReturnType == typeof(bool)
&& m.Name == "ContainsKey"
&& !m.IsGenericMethod
&& m.GetParameters().Length == 1);
if (method == null && type.GetTypeInfo().IsGenericType)
{
var definition = type.GetGenericTypeDefinition();
var tKeyGenericArg = definition.GetGenericArguments().FirstOrDefault(typeArg => typeArg.Name == "TKey");
if (tKeyGenericArg != null)
{
method = definition
.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault(m =>
m.ReturnType == typeof(bool)
&& m.Name == "Contains"
&& !m.IsGenericMethod
&& m.GetParameters().Length == 1
&& m.GetParameters()[0].ParameterType == tKeyGenericArg);
if (method != null)
{
#if NETSTANDARD1_4
method = methods.Single(m => Matched(method, m));
#else
method = methods.Single(m => m.MetadataToken == method.MetadataToken);
#endif
}
}
}
return method;
}
#if NETSTANDARD1_4
// This is for missing MetadataToken in NetStandard 1.4, matched by method signature
private static bool Matched(MethodInfo methodInfo, MethodInfo matchedMethodInfo)
{
return methodInfo.Name == matchedMethodInfo.Name &&
methodInfo.Attributes == matchedMethodInfo.Attributes &&
methodInfo.IsHideBySig == matchedMethodInfo.IsHideBySig &&
methodInfo.IsGenericMethod == matchedMethodInfo.IsGenericMethod &&
methodInfo.ReturnParameter.ParameterType == matchedMethodInfo.ReturnParameter.ParameterType &&
Matched(methodInfo.GetParameters(), matchedMethodInfo.GetParameters()) &&
Matched(methodInfo.GetGenericArguments(), matchedMethodInfo.GetGenericArguments());
}
private static bool Matched(ParameterInfo[] parameterInfos, ParameterInfo[] matchedParameterInfos)
{
if (parameterInfos.Length != matchedParameterInfos.Length) return false;
for (var index = 0; index < parameterInfos.Length; index++)
{
if (parameterInfos[index].ParameterType == matchedParameterInfos[index].ParameterType)
return false;
}
return true;
}
private static bool Matched(Type[] types, Type[] matchedTypes)
{
if (types.Length != matchedTypes.Length) return false;
for (var index = 0; index < types.Length; index++)
{
if (types[index] == matchedTypes[index])
return false;
}
return true;
}
#endif
private static IEnumerable<Type> GetBaseTypes(Type type)
{
for (; ; )
{
type = type.GetTypeInfo().BaseType;
if (type == null) break;
yield return type;
}
}
}
}
| |
using System;
using System.Data;
namespace PCSComUtils.MasterSetup.DS
{
[Serializable]
public class MST_TransactionHistoryVO
{
private int mMasterLocationID;
private int mBinID;
private Decimal mBuySellCost;
private int mInspStatus;
private int mTransactionHistoryID;
private DateTime mTransDate;
private DateTime mPostDate;
private int mRefMasterID;
private int mRefDetailID;
private Decimal mCost;
private int mCCNID;
private int mTranTypeID;
private int mPartyID;
private int mPartyLocationID;
private int mLocationID;
private int mProductID;
private int mStockUMID;
private int mCurrencyID;
private Decimal mQuantity;
private Decimal mMasLocOHQuantity;
private Decimal mLocationOHQuantity;
private Decimal mBinOHQuantity;
private string mComment;
private Decimal mExchangeRate;
private string mLot;
private string mSerial;
private Decimal mOldAvgCost;
private Decimal mNewAvgCost;
private decimal mMasLocCommitQuantity;
private decimal mLocationCommitQuantity;
private decimal mBinCommitQuantity;
private int mPurposeID;
private string mUsername;
public int MasterLocationID
{
set { mMasterLocationID = value; }
get { return mMasterLocationID; }
}
public int BinID
{
set { mBinID = value; }
get { return mBinID; }
}
public Decimal BuySellCost
{
set { mBuySellCost = value; }
get { return mBuySellCost; }
}
public int InspStatus
{
set { mInspStatus = value; }
get { return mInspStatus; }
}
public int TransactionHistoryID
{
set { mTransactionHistoryID = value; }
get { return mTransactionHistoryID; }
}
public DateTime TransDate
{
set { mTransDate = value; }
get { return mTransDate; }
}
public DateTime PostDate
{
set { mPostDate = value; }
get { return mPostDate; }
}
public int RefMasterID
{
set { mRefMasterID = value; }
get { return mRefMasterID; }
}
public int RefDetailID
{
set { mRefDetailID = value; }
get { return mRefDetailID; }
}
public Decimal Cost
{
set { mCost = value; }
get { return mCost; }
}
public int CCNID
{
set { mCCNID = value; }
get { return mCCNID; }
}
public int TranTypeID
{
set { mTranTypeID = value; }
get { return mTranTypeID; }
}
public int PartyID
{
set { mPartyID = value; }
get { return mPartyID; }
}
public int PartyLocationID
{
set { mPartyLocationID = value; }
get { return mPartyLocationID; }
}
public int LocationID
{
set { mLocationID = value; }
get { return mLocationID; }
}
public int ProductID
{
set { mProductID = value; }
get { return mProductID; }
}
public int StockUMID
{
set { mStockUMID = value; }
get { return mStockUMID; }
}
public int CurrencyID
{
set { mCurrencyID = value; }
get { return mCurrencyID; }
}
public Decimal Quantity
{
set { mQuantity = value; }
get { return mQuantity; }
}
public Decimal MasLocOHQuantity
{
set { mMasLocOHQuantity = value; }
get { return mMasLocOHQuantity; }
}
public Decimal LocationOHQuantity
{
set { mLocationOHQuantity = value; }
get { return mLocationOHQuantity; }
}
public Decimal BinOHQuantity
{
set { mBinOHQuantity = value; }
get { return mBinOHQuantity; }
}
public string Comment
{
set { mComment = value; }
get { return mComment; }
}
public Decimal ExchangeRate
{
set { mExchangeRate = value; }
get { return mExchangeRate; }
}
public string Lot
{
set { mLot = value; }
get { return mLot; }
}
public string Serial
{
set { mSerial = value; }
get { return mSerial; }
}
public Decimal OldAvgCost
{
set { mOldAvgCost = value; }
get { return mOldAvgCost; }
}
public Decimal NewAvgCost
{
set { mNewAvgCost = value; }
get { return mNewAvgCost; }
}
public decimal MasLocCommitQuantity
{
get { return mMasLocCommitQuantity; }
set { mMasLocCommitQuantity = value; }
}
public decimal LocationCommitQuantity
{
get { return mLocationCommitQuantity; }
set { mLocationCommitQuantity = value; }
}
public decimal BinCommitQuantity
{
get { return mBinCommitQuantity; }
set { mBinCommitQuantity = value; }
}
public int PurposeID
{
get {return this.mPurposeID;}
set {this.mPurposeID = value;}
}
public string Username
{
get { return mUsername; }
set { mUsername = value; }
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Xml;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using Google.GData.Client;
namespace Google.GData.Documents {
/// <summary>
/// A subclass of FeedQuery, to create an Documents query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
///
/// Documents List supports the following standard GData query parameters:
/// alt, author, q, start-index, max-results, updated-min, updated-max, /category
/// For more information about the standard parameters, see the GData protocol reference document.
/// In addition to the standard GData query parameters, the Documents List data API uses the following parameters.
/// Parameter Meaning
/// title Specifies the search terms for the title of a document.
/// This parameter used without title-exact will only submit partial queries, not exact queries.
///
/// title-exact Specifies whether the title query should be taken as an exact string.
/// Meaningless without title. Possible values are true and false.
///
/// The Documents List data API supports the following categories.
/// Category: Document Type
/// Scheme: http://schemas.google.com/g/2005#kind
/// Term: http://schemas.google.com/docs/2007#type
/// Label: type
/// All documents of the corresponding type in the requesting users document list.
/// Type is currently one of (document|spreadsheet|presentation)
/// Category: Starred Status
/// Scheme: http://schemas.google.com/g/2005/labels
/// Term: starred
/// Label: starred
/// All documents that have been starred by the requesting user
/// Category: Containing Folders
/// Scheme: http://schemas.google.com/docs/2007/folders/user-email
/// Term: folder-id
/// Label: folder-name
/// All documents inside the given folder for the requesting user
/// </summary>
public class DocumentsListQuery : FeedQuery {
/// <summary>
/// document feed base URI
/// </summary>
public static string documentsBaseUri = "https://docs.google.com/feeds/default/private/full";
/// <summary>
/// document feed base URI with ACLs
/// </summary>
public static string documentsAclUri = "https://docs.google.com/feeds/default/private/expandAcl";
/// <summary>
/// template to construct a folder URI for a folder ID
/// </summary>
public static string foldersUriTemplate = "https://docs.google.com/feeds/default/private/full/{0}/contents";
/// <summary>
/// template to get the ACLs for a resourceID
/// </summary>
public static string aclsUriTemplate = "https://docs.google.com/feeds/default/private/full/{0}/acl";
/// <summary>
/// template to get the media for a resourceID
/// </summary>
public static string mediaUriTemplate = "https://docs.google.com/feeds/default/media/{0}";
/// <summary>
/// uri to get you all folders
/// </summary>
public static string allFoldersUri = "https://docs.google.com/feeds/default/private/full/-/folder";
/// <summary>
/// template to access the changes feed
/// </summary>
public static string allChangesTemplate = "https://docs.google.com/feeds/{0}/private/changes";
/// <summary>
/// template to access the metadata feed
/// </summary>
public static string metadataTemplate = "https://docs.google.com/feeds/metadata/{0}";
/// <summary>
/// template to get a revision for a given resourceID and revisionID
/// </summary>
public static string revisionsUriTemplate = "https://docs.google.com/feeds/default/private/full/{0}/revisions/{1}";
/// <summary>
/// URI to access the archive feed
/// </summary>
public static string archiveUri = "https://docs.google.com/feeds/default/private/archive";
/// <summary>
/// predefined query category for documents
/// </summary>
public static QueryCategory DOCUMENTS = new QueryCategory(new AtomCategory("document"));
/// <summary>
/// predefined query category for spreadsheets
/// </summary>
public static QueryCategory SPREADSHEETS = new QueryCategory(new AtomCategory("spreadsheet"));
/// <summary>
/// predefined query category for presentations
/// </summary>
public static QueryCategory PRESENTATIONS = new QueryCategory(new AtomCategory("presentation"));
/// <summary>
/// predefined query category for drawings
/// </summary>
public static QueryCategory DRAWINGS = new QueryCategory(new AtomCategory("drawing"));
/// <summary>
/// predefined query category for PDFS
/// </summary>
public static QueryCategory PDFS = new QueryCategory(new AtomCategory("pdf"));
/// <summary>
/// predefined query category for Forms
/// </summary>
public static QueryCategory FORMS = new QueryCategory(new AtomCategory("form"));
/// <summary>
/// predefined query category for starred documents
/// </summary>
public static QueryCategory STARRED = new QueryCategory(new AtomCategory("starred"));
/// <summary>
/// predefined query category for starred documents
/// </summary>
public static QueryCategory VIEWED = new QueryCategory(new AtomCategory("viewed"));
/// <summary>
/// predefined query category for hidden documents
/// </summary>
public static QueryCategory HIDDEN = new QueryCategory(new AtomCategory("hidden"));
/// <summary>
/// predefined query category for trashed documents
/// </summary>
public static QueryCategory TRASHED = new QueryCategory(new AtomCategory("trashed"));
/// <summary>
/// predefined query category for user owned documents
/// </summary>
public static QueryCategory MINE = new QueryCategory(new AtomCategory("mine"));
/// <summary>
/// predefined query category for private documents
/// </summary>
public static QueryCategory PRIVATE = new QueryCategory(new AtomCategory("private"));
/// <summary>
/// predefined query category for shared documents
/// </summary>
public static QueryCategory SHARED = new QueryCategory(new AtomCategory("shared-with-domain"));
//Local variable to hold the contents of a title query
private string title;
//Local variable to hold if the title query we are doing should be exact.
private bool titleExact;
//Local variable to hold if the root collection should be shown in the feed.
private bool showRoot;
private string owner;
private string writer;
private string reader;
private string targetLanguage;
private string sourceLanguage;
private bool showFolders = false;
private bool showDeleted = false;
private bool includeProfileInfo = false;
private bool ocr = false;
private DateTime editedMin;
private DateTime editedMax;
/// <summary>
/// base constructor
/// </summary>
public DocumentsListQuery()
: base(documentsBaseUri) {
this.CategoryQueriesAsParameter = true;
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public DocumentsListQuery(string queryUri)
: base(queryUri) {
this.CategoryQueriesAsParameter = true;
}
/// <summary>Doclist does not support index based paging</returns>
[Obsolete("Index based paging is not supported on DocumentsList")]
public override int StartIndex {
get { return 0; }
set { }
}
/// <summary>
/// Restricts the results to only starred documents
/// </summary>
[CLSCompliant(false)]
public bool Starred {
get {
return this.Categories.Contains(DocumentsListQuery.STARRED);
}
set {
if (value) {
this.Categories.Add(DocumentsListQuery.STARRED);
} else {
this.Categories.Remove(DocumentsListQuery.STARRED);
}
}
}
/// <summary>
/// Restricts the results to only viewed documents
/// </summary>
[CLSCompliant(false)]
public bool Viewed {
get {
return this.Categories.Contains(DocumentsListQuery.VIEWED);
}
set {
if (value) {
this.Categories.Add(DocumentsListQuery.VIEWED);
} else {
this.Categories.Remove(DocumentsListQuery.VIEWED);
}
}
}
/// <summary>
/// Restricts the results to only trashed documents
/// </summary>
[CLSCompliant(false)]
public bool Trashed {
get {
return this.Categories.Contains(DocumentsListQuery.TRASHED);
}
set {
if (value) {
this.Categories.Add(DocumentsListQuery.TRASHED);
} else {
this.Categories.Remove(DocumentsListQuery.TRASHED);
}
}
}
/// <summary>
/// Restricts the results to only documents owned by the user
/// </summary>
[CLSCompliant(false)]
public bool Mine {
get {
return this.Categories.Contains(DocumentsListQuery.MINE);
}
set {
if (value) {
this.Categories.Add(DocumentsListQuery.MINE);
} else {
this.Categories.Remove(DocumentsListQuery.MINE);
}
}
}
/// <summary>
/// if true, shows folders in the result
/// </summary>
[CLSCompliant(false)]
public bool ShowFolders {
get {
return this.showFolders;
}
set {
this.showFolders = value;
}
}
/// <summary>
/// if true, shows root in the result
/// </summary>
public bool ShowRoot {
get {
return this.showRoot;
}
set {
this.showRoot = value;
}
}
/// <summary>
/// Restricts the results to only documents with titles matching a string.
/// </summary>
public string Title {
get {
return this.title;
}
set {
this.title = value;
}
}
/// <summary>
/// Restricts the results to only documents matching a string provided
/// by the Title property exactly. (No partial matches.)
/// </summary>
public bool TitleExact {
get {
return this.titleExact;
}
set {
this.titleExact = value;
}
}
/// <summary>
/// Searches for documents with a specific owner. Use the email address of the owner
/// </summary>
public string Owner {
get {
return this.owner;
}
set {
this.owner = value;
}
}
/// <summary>
/// Searches for documents which can be written to by specific users.
/// Use a single email address or a comma separated list of email addresses.
/// </summary>
public string Writer {
get {
return this.writer;
}
set {
this.writer = value;
}
}
/// <summary>
/// Searches for documents which can be read by specific users.
/// Use a single email address or a comma separated list of email addresses.
/// </summary>
public string Reader {
get {
return this.reader;
}
set {
this.reader = value;
}
}
/// <summary>
/// Specifies whether to attempt OCR on a .jpg, .png, of .gif upload.
/// </summary>
public bool Ocr {
get {
return this.ocr;
}
set {
this.ocr = value;
}
}
/// <summary>
/// Specifies whether the query should return documents which are in the trash as well as other documents.
/// </summary>
public bool ShowDeleted {
get {
return this.showDeleted;
}
set {
this.showDeleted = value;
}
}
/// <summary>
/// Specifies the language to translate a document into.
/// </summary>
public string TargetLanguage {
get {
return this.targetLanguage;
}
set {
this.targetLanguage = value;
}
}
/// <summary>
/// Specifies the source langugate to translate a document from.
/// </summary>
public string SourceLanguage {
get {
return this.sourceLanguage;
}
set {
this.sourceLanguage = value;
}
}
/// <summary>
/// Lower bound on the last time a document was edited by the current user.
/// </summary>
public DateTime EditedMin {
get { return this.editedMin; }
set { this.editedMin = value; }
}
/// <summary>Upper bound on the last time a document was edited by the current user.</summary>
public DateTime EditedMax {
get { return this.editedMax; }
set { this.editedMax = value; }
}
/// <summary>
/// Specifies whether the query should return additional profile information for the users.
/// </summary>
public bool IncludeProfileInfo {
get {
return this.includeProfileInfo;
}
set {
this.includeProfileInfo = value;
}
}
/// <summary>Parses custom properties out of the incoming URI</summary>
/// <param name="targetUri">A URI representing a query on a feed</param>
/// <returns>returns the base uri</returns>
protected override Uri ParseUri(Uri targetUri) {
base.ParseUri(targetUri);
if (targetUri != null) {
char[] deli = { '?', '&' };
string source = HttpUtility.UrlDecode(targetUri.Query);
TokenCollection tokens = new TokenCollection(source, deli);
foreach (String token in tokens) {
if (token.Length > 0) {
char[] otherDeli = { '=' };
String[] parameters = token.Split(otherDeli, 2);
switch (parameters[0]) {
case "title-exact":
this.TitleExact = bool.Parse(parameters[1]);
break;
case "title":
this.Title = parameters[1];
break;
case "owner":
this.Owner = parameters[1];
break;
case "reader":
this.Reader = parameters[1];
break;
case "writer":
this.Writer = parameters[1];
break;
case "targetLanguage":
this.TargetLanguage = parameters[1];
break;
case "sourceLanguage":
this.SourceLanguage = parameters[1];
break;
case "showfolders":
this.ShowFolders = bool.Parse(parameters[1]);
break;
case "ocr":
this.Ocr = bool.Parse(parameters[1]);
break;
case "showDeleted":
this.ShowDeleted = bool.Parse(parameters[1]);
break;
case "edited-min":
this.EditedMin = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture);
break;
case "edited-max":
this.EditedMax = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture);
break;
case "include-profile-info":
this.IncludeProfileInfo = bool.Parse(parameters[1]);
break;
case "showroot":
this.ShowRoot = bool.Parse(parameters[1]);
break;
}
}
}
}
return this.Uri;
}
/// <summary>Creates the partial URI query string based on all
/// set properties.</summary>
/// <returns> A string representing the query part of the URI.</returns>
protected override string CalculateQuery(string basePath) {
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
paramInsertion = AppendQueryPart(this.Title, "title", paramInsertion, newPath);
if (this.TitleExact) {
paramInsertion = AppendQueryPart("true", "title-exact", paramInsertion, newPath);
}
if (this.ShowFolders) {
paramInsertion = AppendQueryPart("true", "showfolders", paramInsertion, newPath);
}
if (this.Ocr) {
paramInsertion = AppendQueryPart("true", "ocr", paramInsertion, newPath);
}
if (this.ShowDeleted) {
paramInsertion = AppendQueryPart("true", "showDeleted", paramInsertion, newPath);
}
if (this.ShowRoot) {
paramInsertion = AppendQueryPart("true", "showroot", paramInsertion, newPath);
}
if (this.IncludeProfileInfo) {
paramInsertion = AppendQueryPart("true", "include-profile-info", paramInsertion, newPath);
}
paramInsertion = AppendQueryPart(this.Owner, "owner", paramInsertion, newPath);
paramInsertion = AppendQueryPart(this.Writer, "writer", paramInsertion, newPath);
paramInsertion = AppendQueryPart(this.Reader, "reader", paramInsertion, newPath);
paramInsertion = AppendQueryPart(this.EditedMin, "edited-min", paramInsertion, newPath);
paramInsertion = AppendQueryPart(this.EditedMax, "edited-max", paramInsertion, newPath);
paramInsertion = AppendQueryPart(this.TargetLanguage, "targetLanguage", paramInsertion, newPath);
paramInsertion = AppendQueryPart(this.SourceLanguage, "sourceLanguage", paramInsertion, newPath);
return newPath.ToString();
}
}
/// <summary>
/// a subclass setup to just retrieve all word processor documents
/// </summary>
public class TextDocumentQuery : DocumentsListQuery {
/// <summary>
/// base constructor
/// </summary>
public TextDocumentQuery()
: base() {
this.Categories.Add(DocumentsListQuery.DOCUMENTS);
}
}
/// <summary>
/// a subclass setup to just retrieve all spreadsheets
/// </summary>
public class SpreadsheetQuery : DocumentsListQuery {
/// <summary>
/// base constructor
/// </summary>
public SpreadsheetQuery()
: base() {
this.Categories.Add(DocumentsListQuery.SPREADSHEETS);
}
}
/// <summary>
/// a subclass setup to just retrieve all presentations
/// </summary>
public class PresentationsQuery : DocumentsListQuery {
/// <summary>
/// base constructor
/// </summary>
public PresentationsQuery()
: base() {
this.Categories.Add(DocumentsListQuery.PRESENTATIONS);
}
}
/// <summary>
/// a subclass setup to just retrieve all drawings
/// </summary>
public class DrawingsQuery : DocumentsListQuery {
/// <summary>
/// base constructor
/// </summary>
public DrawingsQuery()
: base() {
this.Categories.Add(DocumentsListQuery.DRAWINGS);
}
}
/// <summary>
/// a subclass setup to just retrieve all PDFs
/// </summary>
public class PDFsQuery : DocumentsListQuery {
/// <summary>
/// base constructor
/// </summary>
public PDFsQuery()
: base() {
this.Categories.Add(DocumentsListQuery.PDFS);
}
}
/// <summary>
/// a subclass setup to just retrieve all Folders
/// </summary>
public class FolderQuery : DocumentsListQuery {
/// <summary>
/// base constructor
/// </summary>
public FolderQuery()
: base() {
this.baseUri = DocumentsListQuery.allFoldersUri;
}
/// <summary>
/// base constructor
/// </summary>
public FolderQuery(string folderId)
: base() {
this.baseUri = String.Format(DocumentsListQuery.foldersUriTemplate, folderId);
this.ShowFolders = true;
}
}
/// <summary>
/// a subclass setup to retrieve all changes
/// </summary>
public class ChangesQuery : DocumentsListQuery {
private int startIndex;
private bool expandAcl;
/// <summary>
/// base constructor
/// </summary>
public ChangesQuery()
: this("default") {
}
/// <summary>
/// base constructor
/// </summary>
public ChangesQuery(string userId)
: base() {
this.baseUri = String.Format(DocumentsListQuery.allChangesTemplate, userId);
}
public override int StartIndex {
get {
return this.startIndex;
}
set {
this.startIndex = value;
}
}
public bool ExpandAcl {
get {
return this.expandAcl;
}
set {
this.expandAcl = value;
}
}
protected override string CalculateQuery(string basePath) {
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (this.ExpandAcl) {
paramInsertion = AppendQueryPart("true", "expand-acl", paramInsertion, newPath);
}
return newPath.ToString();
}
}
/// <summary>
/// a subclass setup to retrieve information about a user account
/// </summary>
public class MetadataQuery : DocumentsListQuery {
private int remainingChangestampsFirst;
private int remainingChangestampsLimit;
/// <summary>
/// base constructor
/// </summary>
public MetadataQuery()
: this("default") {
}
/// <summary>
/// base constructor
/// </summary>
public MetadataQuery(string userId)
: base() {
this.baseUri = String.Format(DocumentsListQuery.metadataTemplate, userId);
}
public int RemainingChangestampsFirst {
get {
return this.remainingChangestampsFirst;
}
set {
this.remainingChangestampsFirst = value;
}
}
public int RemainingChangestampsLimit {
get {
return this.remainingChangestampsLimit;
}
set {
this.remainingChangestampsLimit = value;
}
}
protected override string CalculateQuery(string basePath) {
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (this.RemainingChangestampsFirst > 0) {
paramInsertion = AppendQueryPart(
this.RemainingChangestampsFirst.ToString(),
"remaining-changestamps-first",
paramInsertion,
newPath);
}
if (this.RemainingChangestampsLimit > 0) {
paramInsertion = AppendQueryPart(
this.RemainingChangestampsLimit.ToString(),
"remaining-changestamps-limit",
paramInsertion,
newPath);
}
return newPath.ToString();
}
}
/// <summary>
/// a query object used to interact with the Archive feed
/// </summary>
public class ArchiveQuery : DocumentsListQuery {
/// <summary>
/// base constructor
/// </summary>
public ArchiveQuery(string archiveId)
: base() {
this.baseUri = DocumentsListQuery.archiveUri + "/" + archiveId;
}
}
/// <summary>
/// a query object used to interact with the Revision feed
/// </summary>
public class RevisionQuery : DocumentsListQuery {
/// <summary>
/// base constructor
/// </summary>
public RevisionQuery(string revisionUri)
: base() {
this.baseUri = revisionUri;
}
}
}
| |
using System;
using System.Collections.Generic;
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace com.google.zxing.qrcode.detector
{
using DecodeHintType = com.google.zxing.DecodeHintType;
using FormatException = com.google.zxing.FormatException;
using NotFoundException = com.google.zxing.NotFoundException;
using ResultPoint = com.google.zxing.ResultPoint;
using ResultPointCallback = com.google.zxing.ResultPointCallback;
using BitMatrix = com.google.zxing.common.BitMatrix;
using DetectorResult = com.google.zxing.common.DetectorResult;
using GridSampler = com.google.zxing.common.GridSampler;
using PerspectiveTransform = com.google.zxing.common.PerspectiveTransform;
using MathUtils = com.google.zxing.common.detector.MathUtils;
using Version = com.google.zxing.qrcode.decoder.Version;
/// <summary>
/// <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
/// is rotated or skewed, or partially obscured.</p>
///
/// @author Sean Owen
/// </summary>
public class Detector
{
private readonly BitMatrix image;
private ResultPointCallback resultPointCallback;
public Detector(BitMatrix image)
{
this.image = image;
}
protected internal BitMatrix Image
{
get
{
return image;
}
}
protected internal ResultPointCallback ResultPointCallback
{
get
{
return resultPointCallback;
}
}
/// <summary>
/// <p>Detects a QR Code in an image, simply.</p>
/// </summary>
/// <returns> <seealso cref="DetectorResult"/> encapsulating results of detecting a QR Code </returns>
/// <exception cref="NotFoundException"> if no QR Code can be found </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public com.google.zxing.common.DetectorResult detect() throws com.google.zxing.NotFoundException, com.google.zxing.FormatException
public virtual DetectorResult detect()
{
return detect(null);
}
/// <summary>
/// <p>Detects a QR Code in an image, simply.</p>
/// </summary>
/// <param name="hints"> optional hints to detector </param>
/// <returns> <seealso cref="NotFoundException"/> encapsulating results of detecting a QR Code </returns>
/// <exception cref="NotFoundException"> if QR Code cannot be found </exception>
/// <exception cref="FormatException"> if a QR Code cannot be decoded </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public final com.google.zxing.common.DetectorResult detect(java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException
public DetectorResult detect(IDictionary<DecodeHintType, object> hints)
{
//resultPointCallback = hints == null ? null : (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
ResultPointCallback resultPointCallback = null;
if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
resultPointCallback = (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
}
FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback);
FinderPatternInfo info = finder.find(hints);
return processFinderPatternInfo(info);
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected final com.google.zxing.common.DetectorResult processFinderPatternInfo(FinderPatternInfo info) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException
protected internal DetectorResult processFinderPatternInfo(FinderPatternInfo info)
{
FinderPattern topLeft = info.TopLeft;
FinderPattern topRight = info.TopRight;
FinderPattern bottomLeft = info.BottomLeft;
float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
if (moduleSize < 1.0f)
{
throw NotFoundException.NotFoundInstance;
}
int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
int modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7;
AlignmentPattern alignmentPattern = null;
// Anything above version 1 has an alignment pattern
if (provisionalVersion.AlignmentPatternCenters.Length > 0)
{
// Guess where a "bottom right" finder pattern would have been
float bottomRightX = topRight.X - topLeft.X + bottomLeft.X;
float bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y;
// Estimate that alignment pattern is closer by 3 modules
// from "bottom right" to known top left location
float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters;
int estAlignmentX = (int)(topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X));
int estAlignmentY = (int)(topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y));
// Kind of arbitrary -- expand search radius before giving up
for (int i = 4; i <= 16; i <<= 1)
{
try
{
alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float) i);
break;
}
catch (NotFoundException re)
{
// try next round
}
}
// If we didn't find alignment pattern... well try anyway without it
}
PerspectiveTransform transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
BitMatrix bits = sampleGrid(image, transform, dimension);
ResultPoint[] points;
if (alignmentPattern == null)
{
points = new ResultPoint[]{bottomLeft, topLeft, topRight};
}
else
{
points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};
}
return new DetectorResult(bits, points);
}
private static PerspectiveTransform createTransform(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint alignmentPattern, int dimension)
{
float dimMinusThree = (float) dimension - 3.5f;
float bottomRightX;
float bottomRightY;
float sourceBottomRightX;
float sourceBottomRightY;
if (alignmentPattern != null)
{
bottomRightX = alignmentPattern.X;
bottomRightY = alignmentPattern.Y;
sourceBottomRightX = dimMinusThree - 3.0f;
sourceBottomRightY = sourceBottomRightX;
}
else
{
// Don't have an alignment pattern, just make up the bottom-right point
bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X;
bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y;
sourceBottomRightX = dimMinusThree;
sourceBottomRightY = dimMinusThree;
}
return PerspectiveTransform.quadrilateralToQuadrilateral(3.5f, 3.5f, dimMinusThree, 3.5f, sourceBottomRightX, sourceBottomRightY, 3.5f, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y);
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static com.google.zxing.common.BitMatrix sampleGrid(com.google.zxing.common.BitMatrix image, com.google.zxing.common.PerspectiveTransform transform, int dimension) throws com.google.zxing.NotFoundException
private static BitMatrix sampleGrid(BitMatrix image, PerspectiveTransform transform, int dimension)
{
GridSampler sampler = GridSampler.Instance;
return sampler.sampleGrid(image, dimension, dimension, transform);
}
/// <summary>
/// <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
/// of the finder patterns and estimated module size.</p>
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static int computeDimension(com.google.zxing.ResultPoint topLeft, com.google.zxing.ResultPoint topRight, com.google.zxing.ResultPoint bottomLeft, float moduleSize) throws com.google.zxing.NotFoundException
private static int computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, float moduleSize)
{
int tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
int tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
switch (dimension & 0x03) // mod 4
{
case 0:
dimension++;
break;
// 1? do nothing
case 2:
dimension--;
break;
case 3:
throw NotFoundException.NotFoundInstance;
}
return dimension;
}
/// <summary>
/// <p>Computes an average estimated module size based on estimated derived from the positions
/// of the three finder patterns.</p>
/// </summary>
protected internal float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft)
{
// Take the average
return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
}
/// <summary>
/// <p>Estimates module size based on two finder patterns -- it uses
/// <seealso cref="#sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)"/> to figure the
/// width of each, measuring along the axis between their centers.</p>
/// </summary>
private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern)
{
float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.X, (int) pattern.Y, (int) otherPattern.X, (int) otherPattern.Y);
float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.X, (int) otherPattern.Y, (int) pattern.X, (int) pattern.Y);
if (float.IsNaN(moduleSizeEst1))
{
return moduleSizeEst2 / 7.0f;
}
if (float.IsNaN(moduleSizeEst2))
{
return moduleSizeEst1 / 7.0f;
}
// Average them, and divide by 7 since we've counted the width of 3 black modules,
// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
}
/// <summary>
/// See <seealso cref="#sizeOfBlackWhiteBlackRun(int, int, int, int)"/>; computes the total width of
/// a finder pattern by looking for a black-white-black run from the center in the direction
/// of another point (another finder pattern center), and in the opposite direction too.</p>
/// </summary>
private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY)
{
float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
// Now count other way -- don't run off image though of course
float scale = 1.0f;
int otherToX = fromX - (toX - fromX);
if (otherToX < 0)
{
scale = (float) fromX / (float)(fromX - otherToX);
otherToX = 0;
}
else if (otherToX >= image.Width)
{
scale = (float)(image.Width - 1 - fromX) / (float)(otherToX - fromX);
otherToX = image.Width - 1;
}
int otherToY = (int)(fromY - (toY - fromY) * scale);
scale = 1.0f;
if (otherToY < 0)
{
scale = (float) fromY / (float)(fromY - otherToY);
otherToY = 0;
}
else if (otherToY >= image.Height)
{
scale = (float)(image.Height - 1 - fromY) / (float)(otherToY - fromY);
otherToY = image.Height - 1;
}
otherToX = (int)(fromX + (otherToX - fromX) * scale);
result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
// Middle pixel is double-counted this way; subtract 1
return result - 1.0f;
}
/// <summary>
/// <p>This method traces a line from a point in the image, in the direction towards another point.
/// It begins in a black region, and keeps going until it finds white, then black, then white again.
/// It reports the distance from the start to this point.</p>
///
/// <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
/// may be skewed or rotated.</p>
/// </summary>
private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY)
{
// Mild variant of Bresenham's algorithm;
// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX);
if (steep)
{
int temp = fromX;
fromX = fromY;
fromY = temp;
temp = toX;
toX = toY;
toY = temp;
}
int dx = Math.Abs(toX - fromX);
int dy = Math.Abs(toY - fromY);
int error = -dx >> 1;
int xstep = fromX < toX ? 1 : -1;
int ystep = fromY < toY ? 1 : -1;
// In black pixels, looking for white, first or second time.
int state = 0;
// Loop up until x == toX, but not beyond
int xLimit = toX + xstep;
for (int x = fromX, y = fromY; x != xLimit; x += xstep)
{
int realX = steep ? y : x;
int realY = steep ? x : y;
// Does current pixel mean we have moved white to black or vice versa?
// Scanning black in state 0,2 and white in state 1, so if we find the wrong
// color, advance to next state or end if we are in state 2 already
if ((state == 1) == image.get(realX, realY))
{
if (state == 2)
{
return MathUtils.distance(x, y, fromX, fromY);
}
state++;
}
error += dy;
if (error > 0)
{
if (y == toY)
{
break;
}
y += ystep;
error -= dx;
}
}
// Found black-white-black; give the benefit of the doubt that the next pixel outside the image
// is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
if (state == 2)
{
return MathUtils.distance(toX + xstep, toY, fromX, fromY);
}
// else we didn't find even black-white-black; no estimate is really possible
return float.NaN;
}
/// <summary>
/// <p>Attempts to locate an alignment pattern in a limited region of the image, which is
/// guessed to contain it. This method uses <seealso cref="AlignmentPattern"/>.</p>
/// </summary>
/// <param name="overallEstModuleSize"> estimated module size so far </param>
/// <param name="estAlignmentX"> x coordinate of center of area probably containing alignment pattern </param>
/// <param name="estAlignmentY"> y coordinate of above </param>
/// <param name="allowanceFactor"> number of pixels in all directions to search from the center </param>
/// <returns> <seealso cref="AlignmentPattern"/> if found, or null otherwise </returns>
/// <exception cref="NotFoundException"> if an unexpected error occurs during detection </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected final AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor) throws com.google.zxing.NotFoundException
protected internal AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor)
{
// Look for an alignment pattern (3 modules in size) around where it
// should be
int allowance = (int)(allowanceFactor * overallEstModuleSize);
int alignmentAreaLeftX = Math.Max(0, estAlignmentX - allowance);
int alignmentAreaRightX = Math.Min(image.Width - 1, estAlignmentX + allowance);
if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3)
{
throw NotFoundException.NotFoundInstance;
}
int alignmentAreaTopY = Math.Max(0, estAlignmentY - allowance);
int alignmentAreaBottomY = Math.Min(image.Height - 1, estAlignmentY + allowance);
if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3)
{
throw NotFoundException.NotFoundInstance;
}
AlignmentPatternFinder alignmentFinder = new AlignmentPatternFinder(image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, resultPointCallback);
return alignmentFinder.find();
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
internal sealed partial class RenameTrackingTaggerProvider
{
internal enum TriggerIdentifierKind
{
NotRenamable,
RenamableDeclaration,
RenamableReference,
}
/// <summary>
/// Determines whether the original token was a renameable identifier on a background thread
/// </summary>
private class TrackingSession : ForegroundThreadAffinitizedObject
{
private static readonly Task<TriggerIdentifierKind> s_notRenamableTask = Task.FromResult(TriggerIdentifierKind.NotRenamable);
private readonly Task<TriggerIdentifierKind> _isRenamableIdentifierTask;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly CancellationToken _cancellationToken;
private readonly IAsynchronousOperationListener _asyncListener;
private Task<bool> _newIdentifierBindsTask = SpecializedTasks.False;
private readonly string _originalName;
public string OriginalName { get { return _originalName; } }
private readonly ITrackingSpan _trackingSpan;
public ITrackingSpan TrackingSpan { get { return _trackingSpan; } }
private bool _forceRenameOverloads;
public bool ForceRenameOverloads { get { return _forceRenameOverloads; } }
public TrackingSession(StateMachine stateMachine, SnapshotSpan snapshotSpan, IAsynchronousOperationListener asyncListener)
{
AssertIsForeground();
_asyncListener = asyncListener;
_trackingSpan = snapshotSpan.Snapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeInclusive);
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
if (snapshotSpan.Length > 0)
{
// If the snapshotSpan is nonempty, then the session began with a change that
// was touching a word. Asynchronously determine whether that word was a
// renameable identifier. If it is, alert the state machine so it can trigger
// tagging.
_originalName = snapshotSpan.GetText();
_isRenamableIdentifierTask = Task.Factory.SafeStartNewFromAsync(
() => DetermineIfRenamableIdentifierAsync(snapshotSpan, initialCheck: true),
_cancellationToken,
TaskScheduler.Default);
var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateTrackingSessionAfterIsRenamableIdentifierTask");
_isRenamableIdentifierTask.SafeContinueWith(
t => stateMachine.UpdateTrackingSessionIfRenamable(),
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken);
QueueUpdateToStateMachine(stateMachine, _isRenamableIdentifierTask);
}
else
{
// If the snapshotSpan is empty, that means text was added in a location that is
// not touching an existing word, which happens a fair amount when writing new
// code. In this case we already know that the user is not renaming an
// identifier.
_isRenamableIdentifierTask = s_notRenamableTask;
}
}
private void QueueUpdateToStateMachine(StateMachine stateMachine, Task task)
{
var asyncToken = _asyncListener.BeginAsyncOperation($"{GetType().Name}.{nameof(QueueUpdateToStateMachine)}");
task.SafeContinueWith(t =>
{
AssertIsForeground();
if (_isRenamableIdentifierTask.Result != TriggerIdentifierKind.NotRenamable)
{
stateMachine.OnTrackingSessionUpdated(this);
}
},
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken);
}
internal void CheckNewIdentifier(StateMachine stateMachine, ITextSnapshot snapshot)
{
AssertIsForeground();
_newIdentifierBindsTask = _isRenamableIdentifierTask.SafeContinueWithFromAsync(
async t => t.Result != TriggerIdentifierKind.NotRenamable &&
TriggerIdentifierKind.RenamableReference ==
await DetermineIfRenamableIdentifierAsync(
TrackingSpan.GetSpan(snapshot),
initialCheck: false).ConfigureAwait(false),
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.Default);
QueueUpdateToStateMachine(stateMachine, _newIdentifierBindsTask);
}
internal bool IsDefinitelyRenamableIdentifier()
{
// This needs to be able to run on a background thread for the CodeFix
return IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult: false, cancellationToken: CancellationToken.None);
}
public void Cancel()
{
AssertIsForeground();
_cancellationTokenSource.Cancel();
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableIdentifierAsync(SnapshotSpan snapshotSpan, bool initialCheck)
{
AssertIsBackground();
var document = snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var syntaxTree = await document.GetSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false);
var token = await syntaxTree.GetTouchingWordAsync(snapshotSpan.Start.Position, syntaxFactsService, _cancellationToken).ConfigureAwait(false);
// The OriginalName is determined with a simple textual check, so for a
// statement such as "Dim [x = 1" the textual check will return a name of "[x".
// The token found for "[x" is an identifier token, but only due to error
// recovery (the "[x" is actually in the trailing trivia). If the OriginalName
// found through the textual check has a different length than the span of the
// touching word, then we cannot perform a rename.
if (initialCheck && token.Span.Length != this.OriginalName.Length)
{
return TriggerIdentifierKind.NotRenamable;
}
var languageHeuristicsService = document.Project.LanguageServices.GetService<IRenameTrackingLanguageHeuristicsService>();
if (syntaxFactsService.IsIdentifier(token) && languageHeuristicsService.IsIdentifierValidForRenameTracking(token.Text))
{
var semanticModel = await document.GetSemanticModelForNodeAsync(token.Parent, _cancellationToken).ConfigureAwait(false);
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var renameSymbolInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, token, _cancellationToken);
if (!renameSymbolInfo.HasSymbols)
{
return TriggerIdentifierKind.NotRenamable;
}
if (renameSymbolInfo.IsMemberGroup)
{
// This is a reference from a nameof expression. Allow the rename but set the RenameOverloads option
_forceRenameOverloads = true;
return await DetermineIfRenamableSymbolsAsync(renameSymbolInfo.Symbols, document, token).ConfigureAwait(false);
}
else
{
return await DetermineIfRenamableSymbolAsync(renameSymbolInfo.Symbols.Single(), document, token).ConfigureAwait(false);
}
}
}
return TriggerIdentifierKind.NotRenamable;
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableSymbolsAsync(IEnumerable<ISymbol> symbols, Document document, SyntaxToken token)
{
foreach (var symbol in symbols)
{
// Get the source symbol if possible
var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol;
if (!sourceSymbol.Locations.All(loc => loc.IsInSource))
{
return TriggerIdentifierKind.NotRenamable;
}
}
return TriggerIdentifierKind.RenamableReference;
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableSymbolAsync(ISymbol symbol, Document document, SyntaxToken token)
{
// Get the source symbol if possible
var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol;
if (sourceSymbol.Kind == SymbolKind.Field &&
((IFieldSymbol)sourceSymbol).ContainingType.IsTupleType &&
sourceSymbol.IsImplicitlyDeclared)
{
// should not rename Item1, Item2...
// when user did not declare them in source.
return TriggerIdentifierKind.NotRenamable;
}
if (!sourceSymbol.Locations.All(loc => loc.IsInSource))
{
return TriggerIdentifierKind.NotRenamable;
}
return sourceSymbol.Locations.Any(loc => loc == token.GetLocation())
? TriggerIdentifierKind.RenamableDeclaration
: TriggerIdentifierKind.RenamableReference;
}
internal bool CanInvokeRename(
ISyntaxFactsService syntaxFactsService,
IRenameTrackingLanguageHeuristicsService languageHeuristicsService,
bool isSmartTagCheck,
bool waitForResult,
CancellationToken cancellationToken)
{
if (IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult, cancellationToken))
{
var isRenamingDeclaration = _isRenamableIdentifierTask.Result == TriggerIdentifierKind.RenamableDeclaration;
var newName = TrackingSpan.GetText(TrackingSpan.TextBuffer.CurrentSnapshot);
var comparison = isRenamingDeclaration || syntaxFactsService.IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
if (!string.Equals(OriginalName, newName, comparison) &&
syntaxFactsService.IsValidIdentifier(newName) &&
languageHeuristicsService.IsIdentifierValidForRenameTracking(newName))
{
// At this point, we want to allow renaming if the user invoked Ctrl+. explicitly, but we
// want to avoid showing a smart tag if we're renaming a reference that binds to an existing
// symbol.
if (!isSmartTagCheck || isRenamingDeclaration || !NewIdentifierDefinitelyBindsToReference())
{
return true;
}
}
}
return false;
}
private bool NewIdentifierDefinitelyBindsToReference()
{
return _newIdentifierBindsTask.Status == TaskStatus.RanToCompletion && _newIdentifierBindsTask.Result;
}
}
}
}
| |
// $Id: GroestlSmallCore.java 256 2011-07-15 19:07:16Z tp $
using System;
namespace NBitcoin.Altcoins.GroestlcoinInternals
{
/**
* This class implements Groestl-224 and Groestl-256.
*
* <pre>
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* 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.
*
* ===========================(LICENSE END)=============================
* </pre>
*
* @version $Revision: 256 $
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
internal abstract class GroestlSmallCore : DigestEngine {
private ulong[] H, G, M;
/**
* Create the object.
*/
public GroestlSmallCore()
{
}
private static readonly ulong[] T0 = {
0xc632f4a5f497a5c6L, 0xf86f978497eb84f8L,
0xee5eb099b0c799eeL, 0xf67a8c8d8cf78df6L,
0xffe8170d17e50dffL, 0xd60adcbddcb7bdd6L,
0xde16c8b1c8a7b1deL, 0x916dfc54fc395491L,
0x6090f050f0c05060L, 0x0207050305040302L,
0xce2ee0a9e087a9ceL, 0x56d1877d87ac7d56L,
0xe7cc2b192bd519e7L, 0xb513a662a67162b5L,
0x4d7c31e6319ae64dL, 0xec59b59ab5c39aecL,
0x8f40cf45cf05458fL, 0x1fa3bc9dbc3e9d1fL,
0x8949c040c0094089L, 0xfa68928792ef87faL,
0xefd03f153fc515efL, 0xb29426eb267febb2L,
0x8ece40c94007c98eL, 0xfbe61d0b1ded0bfbL,
0x416e2fec2f82ec41L, 0xb31aa967a97d67b3L,
0x5f431cfd1cbefd5fL, 0x456025ea258aea45L,
0x23f9dabfda46bf23L, 0x535102f702a6f753L,
0xe445a196a1d396e4L, 0x9b76ed5bed2d5b9bL,
0x75285dc25deac275L, 0xe1c5241c24d91ce1L,
0x3dd4e9aee97aae3dL, 0x4cf2be6abe986a4cL,
0x6c82ee5aeed85a6cL, 0x7ebdc341c3fc417eL,
0xf5f3060206f102f5L, 0x8352d14fd11d4f83L,
0x688ce45ce4d05c68L, 0x515607f407a2f451L,
0xd18d5c345cb934d1L, 0xf9e1180818e908f9L,
0xe24cae93aedf93e2L, 0xab3e9573954d73abL,
0x6297f553f5c45362L, 0x2a6b413f41543f2aL,
0x081c140c14100c08L, 0x9563f652f6315295L,
0x46e9af65af8c6546L, 0x9d7fe25ee2215e9dL,
0x3048782878602830L, 0x37cff8a1f86ea137L,
0x0a1b110f11140f0aL, 0x2febc4b5c45eb52fL,
0x0e151b091b1c090eL, 0x247e5a365a483624L,
0x1badb69bb6369b1bL, 0xdf98473d47a53ddfL,
0xcda76a266a8126cdL, 0x4ef5bb69bb9c694eL,
0x7f334ccd4cfecd7fL, 0xea50ba9fbacf9feaL,
0x123f2d1b2d241b12L, 0x1da4b99eb93a9e1dL,
0x58c49c749cb07458L, 0x3446722e72682e34L,
0x3641772d776c2d36L, 0xdc11cdb2cda3b2dcL,
0xb49d29ee2973eeb4L, 0x5b4d16fb16b6fb5bL,
0xa4a501f60153f6a4L, 0x76a1d74dd7ec4d76L,
0xb714a361a37561b7L, 0x7d3449ce49face7dL,
0x52df8d7b8da47b52L, 0xdd9f423e42a13eddL,
0x5ecd937193bc715eL, 0x13b1a297a2269713L,
0xa6a204f50457f5a6L, 0xb901b868b86968b9L,
0x0000000000000000L, 0xc1b5742c74992cc1L,
0x40e0a060a0806040L, 0xe3c2211f21dd1fe3L,
0x793a43c843f2c879L, 0xb69a2ced2c77edb6L,
0xd40dd9bed9b3bed4L, 0x8d47ca46ca01468dL,
0x671770d970ced967L, 0x72afdd4bdde44b72L,
0x94ed79de7933de94L, 0x98ff67d4672bd498L,
0xb09323e8237be8b0L, 0x855bde4ade114a85L,
0xbb06bd6bbd6d6bbbL, 0xc5bb7e2a7e912ac5L,
0x4f7b34e5349ee54fL, 0xedd73a163ac116edL,
0x86d254c55417c586L, 0x9af862d7622fd79aL,
0x6699ff55ffcc5566L, 0x11b6a794a7229411L,
0x8ac04acf4a0fcf8aL, 0xe9d9301030c910e9L,
0x040e0a060a080604L, 0xfe66988198e781feL,
0xa0ab0bf00b5bf0a0L, 0x78b4cc44ccf04478L,
0x25f0d5bad54aba25L, 0x4b753ee33e96e34bL,
0xa2ac0ef30e5ff3a2L, 0x5d4419fe19bafe5dL,
0x80db5bc05b1bc080L, 0x0580858a850a8a05L,
0x3fd3ecadec7ead3fL, 0x21fedfbcdf42bc21L,
0x70a8d848d8e04870L, 0xf1fd0c040cf904f1L,
0x63197adf7ac6df63L, 0x772f58c158eec177L,
0xaf309f759f4575afL, 0x42e7a563a5846342L,
0x2070503050403020L, 0xe5cb2e1a2ed11ae5L,
0xfdef120e12e10efdL, 0xbf08b76db7656dbfL,
0x8155d44cd4194c81L, 0x18243c143c301418L,
0x26795f355f4c3526L, 0xc3b2712f719d2fc3L,
0xbe8638e13867e1beL, 0x35c8fda2fd6aa235L,
0x88c74fcc4f0bcc88L, 0x2e654b394b5c392eL,
0x936af957f93d5793L, 0x55580df20daaf255L,
0xfc619d829de382fcL, 0x7ab3c947c9f4477aL,
0xc827efacef8bacc8L, 0xba8832e7326fe7baL,
0x324f7d2b7d642b32L, 0xe642a495a4d795e6L,
0xc03bfba0fb9ba0c0L, 0x19aab398b3329819L,
0x9ef668d16827d19eL, 0xa322817f815d7fa3L,
0x44eeaa66aa886644L, 0x54d6827e82a87e54L,
0x3bdde6abe676ab3bL, 0x0b959e839e16830bL,
0x8cc945ca4503ca8cL, 0xc7bc7b297b9529c7L,
0x6b056ed36ed6d36bL, 0x286c443c44503c28L,
0xa72c8b798b5579a7L, 0xbc813de23d63e2bcL,
0x1631271d272c1d16L, 0xad379a769a4176adL,
0xdb964d3b4dad3bdbL, 0x649efa56fac85664L,
0x74a6d24ed2e84e74L, 0x1436221e22281e14L,
0x92e476db763fdb92L, 0x0c121e0a1e180a0cL,
0x48fcb46cb4906c48L, 0xb88f37e4376be4b8L,
0x9f78e75de7255d9fL, 0xbd0fb26eb2616ebdL,
0x43692aef2a86ef43L, 0xc435f1a6f193a6c4L,
0x39dae3a8e372a839L, 0x31c6f7a4f762a431L,
0xd38a593759bd37d3L, 0xf274868b86ff8bf2L,
0xd583563256b132d5L, 0x8b4ec543c50d438bL,
0x6e85eb59ebdc596eL, 0xda18c2b7c2afb7daL,
0x018e8f8c8f028c01L, 0xb11dac64ac7964b1L,
0x9cf16dd26d23d29cL, 0x49723be03b92e049L,
0xd81fc7b4c7abb4d8L, 0xacb915fa1543faacL,
0xf3fa090709fd07f3L, 0xcfa06f256f8525cfL,
0xca20eaafea8fafcaL, 0xf47d898e89f38ef4L,
0x476720e9208ee947L, 0x1038281828201810L,
0x6f0b64d564ded56fL, 0xf073838883fb88f0L,
0x4afbb16fb1946f4aL, 0x5cca967296b8725cL,
0x38546c246c702438L, 0x575f08f108aef157L,
0x732152c752e6c773L, 0x9764f351f3355197L,
0xcbae6523658d23cbL, 0xa125847c84597ca1L,
0xe857bf9cbfcb9ce8L, 0x3e5d6321637c213eL,
0x96ea7cdd7c37dd96L, 0x611e7fdc7fc2dc61L,
0x0d9c9186911a860dL, 0x0f9b9485941e850fL,
0xe04bab90abdb90e0L, 0x7cbac642c6f8427cL,
0x712657c457e2c471L, 0xcc29e5aae583aaccL,
0x90e373d8733bd890L, 0x06090f050f0c0506L,
0xf7f4030103f501f7L, 0x1c2a36123638121cL,
0xc23cfea3fe9fa3c2L, 0x6a8be15fe1d45f6aL,
0xaebe10f91047f9aeL, 0x69026bd06bd2d069L,
0x17bfa891a82e9117L, 0x9971e858e8295899L,
0x3a5369276974273aL, 0x27f7d0b9d04eb927L,
0xd991483848a938d9L, 0xebde351335cd13ebL,
0x2be5ceb3ce56b32bL, 0x2277553355443322L,
0xd204d6bbd6bfbbd2L, 0xa9399070904970a9L,
0x07878089800e8907L, 0x33c1f2a7f266a733L,
0x2decc1b6c15ab62dL, 0x3c5a66226678223cL,
0x15b8ad92ad2a9215L, 0xc9a96020608920c9L,
0x875cdb49db154987L, 0xaab01aff1a4fffaaL,
0x50d8887888a07850L, 0xa52b8e7a8e517aa5L,
0x03898a8f8a068f03L, 0x594a13f813b2f859L,
0x09929b809b128009L, 0x1a2339173934171aL,
0x651075da75cada65L, 0xd784533153b531d7L,
0x84d551c65113c684L, 0xd003d3b8d3bbb8d0L,
0x82dc5ec35e1fc382L, 0x29e2cbb0cb52b029L,
0x5ac3997799b4775aL, 0x1e2d3311333c111eL,
0x7b3d46cb46f6cb7bL, 0xa8b71ffc1f4bfca8L,
0x6d0c61d661dad66dL, 0x2c624e3a4e583a2cL
};
private static readonly ulong[] T1 = new ulong[(uint)T0.Length];
private static readonly ulong[] T2 = new ulong[(uint)T0.Length];
private static readonly ulong[] T3 = new ulong[(uint)T0.Length];
private static readonly ulong[] T4 = new ulong[(uint)T0.Length];
private static readonly ulong[] T5 = new ulong[(uint)T0.Length];
private static readonly ulong[] T6 = new ulong[(uint)T0.Length];
private static readonly ulong[] T7 = new ulong[(uint)T0.Length];
static GroestlSmallCore() {
for (uint i = 0; i < (uint)T0.Length; i ++) {
ulong v = T0[i];
T1[i] = circularLeft(v, 56);
T2[i] = circularLeft(v, 48);
T3[i] = circularLeft(v, 40);
T4[i] = circularLeft(v, 32);
T5[i] = circularLeft(v, 24);
T6[i] = circularLeft(v, 16);
T7[i] = circularLeft(v, 8);
}
}
/* obsolete
private static readonly ulong[] CP = {
0x0000000000000000L, 0x0100000000000000L,
0x0200000000000000L, 0x0300000000000000L,
0x0400000000000000L, 0x0500000000000000L,
0x0600000000000000L, 0x0700000000000000L,
0x0800000000000000L, 0x0900000000000000L,
0x0A00000000000000L, 0x0B00000000000000L,
0x0C00000000000000L, 0x0D00000000000000L
};
private static readonly ulong[] CQ = {
0x00000000000000FFL, 0x00000000000000FEL,
0x00000000000000FDL, 0x00000000000000FCL,
0x00000000000000FBL, 0x00000000000000FAL,
0x00000000000000F9L, 0x00000000000000F8L,
0x00000000000000F7L, 0x00000000000000F6L,
0x00000000000000F5L, 0x00000000000000F4L,
0x00000000000000F3L, 0x00000000000000F2L
};
*/
/** @see Digest */
public override int getBlockLength()
{
return 64;
}
/** @see DigestEngine */
protected Digest copyState(GroestlSmallCore dst)
{
Array.Copy(H, 0, dst.H, 0, H.Length);
return base.copyState(dst);
}
/** @see DigestEngine */
protected override void engineReset()
{
for (uint i = 0; i < 7; i ++)
H[i] = 0L;
H[7] = (ulong)(getDigestLength() << 3);
}
/** @see DigestEngine */
protected override void doPadding(byte[] output, int outputOffset)
{
byte[] buf = getBlockBuffer();
int ptr = flush();
buf[ptr ++] = 0x80;
ulong count = getBlockCount();
if (ptr <= 56) {
for (int i = ptr; i < 56; i ++)
buf[i] = 0;
count ++;
} else {
for (int i = ptr; i < 64; i ++)
buf[i] = 0;
processBlock(buf);
for (uint i = 0; i < 56; i ++)
buf[i] = 0;
count += 2;
}
encodeBELong(count, buf, 56);
processBlock(buf);
Array.Copy(H, 0, G, 0, H.Length);
doPermP(G);
for (uint i = 0; i < 4; i ++)
encodeBELong(H[i + 4] ^ G[i + 4], buf, 8 * i);
int outLen = getDigestLength();
Array.Copy(buf, 32 - outLen,
output, outputOffset, outLen);
}
/** @see DigestEngine */
protected override void doInit()
{
H = new ulong[8];
G = new ulong[8];
M = new ulong[8];
engineReset();
}
/**
* Encode the 64-bit word {@code val} into the array
* {@code buf} at offset {@code off}, in big-endian
* convention (most significant byte first).
*
* @param val the value to encode
* @param buf the destination buffer
* @param off the destination offset
*/
private static void encodeBELong(ulong val, byte[] buf, uint off)
{
buf[(int)off + 0] = (byte)(val >> 56);
buf[(int)off + 1] = (byte)(val >> 48);
buf[(int)off + 2] = (byte)(val >> 40);
buf[(int)off + 3] = (byte)(val >> 32);
buf[(int)off + 4] = (byte)(val >> 24);
buf[(int)off + 5] = (byte)(val >> 16);
buf[(int)off + 6] = (byte)(val >> 8);
buf[(int)off + 7] = (byte)val;
}
/**
* Decode a 64-bit big-endian word from the array {@code buf}
* at offset {@code off}.
*
* @param buf the source buffer
* @param off the source offset
* @return the decoded value
*/
private static ulong decodeBELong(byte[] buf, uint off)
{
return ((buf[(int)off] & 0xFFUL) << 56)
| ((buf[(int)off + 1] & 0xFFUL) << 48)
| ((buf[(int)off + 2] & 0xFFUL) << 40)
| ((buf[(int)off + 3] & 0xFFUL) << 32)
| ((buf[(int)off + 4] & 0xFFUL) << 24)
| ((buf[(int)off + 5] & 0xFFUL) << 16)
| ((buf[(int)off + 6] & 0xFFUL) << 8)
| (buf[(int)off + 7] & 0xFFUL);
}
/**
* Perform a circular rotation by {@code n} to the left
* of the 64-bit word {@code x}. The {@code n} parameter
* must lie between 1 and 63 (inclusive).
*
* @param x the value to rotate
* @param n the rotation count (between 1 and 63)
* @return the rotated value
*/
static private ulong circularLeft(ulong x, uint n)
{
return (x << (int)n) | (x >> (64 - (int)n));
}
private void doPermP(ulong[] x)
{
for (uint r = 0; r < 10; r += 2) {
x[0] ^= (ulong)(r) << 56;
x[1] ^= (ulong)(0x10 + r) << 56;
x[2] ^= (ulong)(0x20 + r) << 56;
x[3] ^= (ulong)(0x30 + r) << 56;
x[4] ^= (ulong)(0x40 + r) << 56;
x[5] ^= (ulong)(0x50 + r) << 56;
x[6] ^= (ulong)(0x60 + r) << 56;
x[7] ^= (ulong)(0x70 + r) << 56;
ulong t0 = T0[(uint)(x[0] >> 56)]
^ T1[(uint)(x[1] >> 48) & 0xFF]
^ T2[(uint)(x[2] >> 40) & 0xFF]
^ T3[(uint)(x[3] >> 32) & 0xFF]
^ T4[((uint)x[4] >> 24)]
^ T5[((uint)x[5] >> 16) & 0xFF]
^ T6[((uint)x[6] >> 8) & 0xFF]
^ T7[(uint)x[7] & 0xFF];
ulong t1 = T0[(uint)(x[1] >> 56)]
^ T1[(uint)(x[2] >> 48) & 0xFF]
^ T2[(uint)(x[3] >> 40) & 0xFF]
^ T3[(uint)(x[4] >> 32) & 0xFF]
^ T4[((uint)x[5] >> 24)]
^ T5[((uint)x[6] >> 16) & 0xFF]
^ T6[((uint)x[7] >> 8) & 0xFF]
^ T7[(uint)x[0] & 0xFF];
ulong t2 = T0[(uint)(x[2] >> 56)]
^ T1[(uint)(x[3] >> 48) & 0xFF]
^ T2[(uint)(x[4] >> 40) & 0xFF]
^ T3[(uint)(x[5] >> 32) & 0xFF]
^ T4[((uint)x[6] >> 24)]
^ T5[((uint)x[7] >> 16) & 0xFF]
^ T6[((uint)x[0] >> 8) & 0xFF]
^ T7[(uint)x[1] & 0xFF];
ulong t3 = T0[(uint)(x[3] >> 56)]
^ T1[(uint)(x[4] >> 48) & 0xFF]
^ T2[(uint)(x[5] >> 40) & 0xFF]
^ T3[(uint)(x[6] >> 32) & 0xFF]
^ T4[((uint)x[7] >> 24)]
^ T5[((uint)x[0] >> 16) & 0xFF]
^ T6[((uint)x[1] >> 8) & 0xFF]
^ T7[(uint)x[2] & 0xFF];
ulong t4 = T0[(uint)(x[4] >> 56)]
^ T1[(uint)(x[5] >> 48) & 0xFF]
^ T2[(uint)(x[6] >> 40) & 0xFF]
^ T3[(uint)(x[7] >> 32) & 0xFF]
^ T4[((uint)x[0] >> 24)]
^ T5[((uint)x[1] >> 16) & 0xFF]
^ T6[((uint)x[2] >> 8) & 0xFF]
^ T7[(uint)x[3] & 0xFF];
ulong t5 = T0[(uint)(x[5] >> 56)]
^ T1[(uint)(x[6] >> 48) & 0xFF]
^ T2[(uint)(x[7] >> 40) & 0xFF]
^ T3[(uint)(x[0] >> 32) & 0xFF]
^ T4[((uint)x[1] >> 24)]
^ T5[((uint)x[2] >> 16) & 0xFF]
^ T6[((uint)x[3] >> 8) & 0xFF]
^ T7[(uint)x[4] & 0xFF];
ulong t6 = T0[(uint)(x[6] >> 56)]
^ T1[(uint)(x[7] >> 48) & 0xFF]
^ T2[(uint)(x[0] >> 40) & 0xFF]
^ T3[(uint)(x[1] >> 32) & 0xFF]
^ T4[((uint)x[2] >> 24)]
^ T5[((uint)x[3] >> 16) & 0xFF]
^ T6[((uint)x[4] >> 8) & 0xFF]
^ T7[(uint)x[5] & 0xFF];
ulong t7 = T0[(uint)(x[7] >> 56)]
^ T1[(uint)(x[0] >> 48) & 0xFF]
^ T2[(uint)(x[1] >> 40) & 0xFF]
^ T3[(uint)(x[2] >> 32) & 0xFF]
^ T4[((uint)x[3] >> 24)]
^ T5[((uint)x[4] >> 16) & 0xFF]
^ T6[((uint)x[5] >> 8) & 0xFF]
^ T7[(uint)x[6] & 0xFF];
t0 ^= (ulong)(r + 1) << 56;
t1 ^= (ulong)(0x10 + (r + 1)) << 56;
t2 ^= (ulong)(0x20 + (r + 1)) << 56;
t3 ^= (ulong)(0x30 + (r + 1)) << 56;
t4 ^= (ulong)(0x40 + (r + 1)) << 56;
t5 ^= (ulong)(0x50 + (r + 1)) << 56;
t6 ^= (ulong)(0x60 + (r + 1)) << 56;
t7 ^= (ulong)(0x70 + (r + 1)) << 56;
x[0] = T0[(uint)(t0 >> 56)]
^ T1[(uint)(t1 >> 48) & 0xFF]
^ T2[(uint)(t2 >> 40) & 0xFF]
^ T3[(uint)(t3 >> 32) & 0xFF]
^ T4[((uint)t4 >> 24)]
^ T5[((uint)t5 >> 16) & 0xFF]
^ T6[((uint)t6 >> 8) & 0xFF]
^ T7[(uint)t7 & 0xFF];
x[1] = T0[(uint)(t1 >> 56)]
^ T1[(uint)(t2 >> 48) & 0xFF]
^ T2[(uint)(t3 >> 40) & 0xFF]
^ T3[(uint)(t4 >> 32) & 0xFF]
^ T4[((uint)t5 >> 24)]
^ T5[((uint)t6 >> 16) & 0xFF]
^ T6[((uint)t7 >> 8) & 0xFF]
^ T7[(uint)t0 & 0xFF];
x[2] = T0[(uint)(t2 >> 56)]
^ T1[(uint)(t3 >> 48) & 0xFF]
^ T2[(uint)(t4 >> 40) & 0xFF]
^ T3[(uint)(t5 >> 32) & 0xFF]
^ T4[((uint)t6 >> 24)]
^ T5[((uint)t7 >> 16) & 0xFF]
^ T6[((uint)t0 >> 8) & 0xFF]
^ T7[(uint)t1 & 0xFF];
x[3] = T0[(uint)(t3 >> 56)]
^ T1[(uint)(t4 >> 48) & 0xFF]
^ T2[(uint)(t5 >> 40) & 0xFF]
^ T3[(uint)(t6 >> 32) & 0xFF]
^ T4[((uint)t7 >> 24)]
^ T5[((uint)t0 >> 16) & 0xFF]
^ T6[((uint)t1 >> 8) & 0xFF]
^ T7[(uint)t2 & 0xFF];
x[4] = T0[(uint)(t4 >> 56)]
^ T1[(uint)(t5 >> 48) & 0xFF]
^ T2[(uint)(t6 >> 40) & 0xFF]
^ T3[(uint)(t7 >> 32) & 0xFF]
^ T4[((uint)t0 >> 24)]
^ T5[((uint)t1 >> 16) & 0xFF]
^ T6[((uint)t2 >> 8) & 0xFF]
^ T7[(uint)t3 & 0xFF];
x[5] = T0[(uint)(t5 >> 56)]
^ T1[(uint)(t6 >> 48) & 0xFF]
^ T2[(uint)(t7 >> 40) & 0xFF]
^ T3[(uint)(t0 >> 32) & 0xFF]
^ T4[((uint)t1 >> 24)]
^ T5[((uint)t2 >> 16) & 0xFF]
^ T6[((uint)t3 >> 8) & 0xFF]
^ T7[(uint)t4 & 0xFF];
x[6] = T0[(uint)(t6 >> 56)]
^ T1[(uint)(t7 >> 48) & 0xFF]
^ T2[(uint)(t0 >> 40) & 0xFF]
^ T3[(uint)(t1 >> 32) & 0xFF]
^ T4[((uint)t2 >> 24)]
^ T5[((uint)t3 >> 16) & 0xFF]
^ T6[((uint)t4 >> 8) & 0xFF]
^ T7[(uint)t5 & 0xFF];
x[7] = T0[(uint)(t7 >> 56)]
^ T1[(uint)(t0 >> 48) & 0xFF]
^ T2[(uint)(t1 >> 40) & 0xFF]
^ T3[(uint)(t2 >> 32) & 0xFF]
^ T4[((uint)t3 >> 24)]
^ T5[((uint)t4 >> 16) & 0xFF]
^ T6[((uint)t5 >> 8) & 0xFF]
^ T7[(uint)t6 & 0xFF];
}
}
private void doPermQ(ulong[] x)
{
for (uint r = 0; r < 10; r += 2) {
x[0] ^= r ^ unchecked((ulong)-0x01L);
x[1] ^= r ^ unchecked((ulong)-0x11L);
x[2] ^= r ^ unchecked((ulong)-0x21L);
x[3] ^= r ^ unchecked((ulong)-0x31L);
x[4] ^= r ^ unchecked((ulong)-0x41L);
x[5] ^= r ^ unchecked((ulong)-0x51L);
x[6] ^= r ^ unchecked((ulong)-0x61L);
x[7] ^= r ^ unchecked((ulong)-0x71L);
ulong t0 = T0[(uint)(x[1] >> 56)]
^ T1[(uint)(x[3] >> 48) & 0xFF]
^ T2[(uint)(x[5] >> 40) & 0xFF]
^ T3[(uint)(x[7] >> 32) & 0xFF]
^ T4[((uint)x[0] >> 24)]
^ T5[((uint)x[2] >> 16) & 0xFF]
^ T6[((uint)x[4] >> 8) & 0xFF]
^ T7[(uint)x[6] & 0xFF];
ulong t1 = T0[(uint)(x[2] >> 56)]
^ T1[(uint)(x[4] >> 48) & 0xFF]
^ T2[(uint)(x[6] >> 40) & 0xFF]
^ T3[(uint)(x[0] >> 32) & 0xFF]
^ T4[((uint)x[1] >> 24)]
^ T5[((uint)x[3] >> 16) & 0xFF]
^ T6[((uint)x[5] >> 8) & 0xFF]
^ T7[(uint)x[7] & 0xFF];
ulong t2 = T0[(uint)(x[3] >> 56)]
^ T1[(uint)(x[5] >> 48) & 0xFF]
^ T2[(uint)(x[7] >> 40) & 0xFF]
^ T3[(uint)(x[1] >> 32) & 0xFF]
^ T4[((uint)x[2] >> 24)]
^ T5[((uint)x[4] >> 16) & 0xFF]
^ T6[((uint)x[6] >> 8) & 0xFF]
^ T7[(uint)x[0] & 0xFF];
ulong t3 = T0[(uint)(x[4] >> 56)]
^ T1[(uint)(x[6] >> 48) & 0xFF]
^ T2[(uint)(x[0] >> 40) & 0xFF]
^ T3[(uint)(x[2] >> 32) & 0xFF]
^ T4[((uint)x[3] >> 24)]
^ T5[((uint)x[5] >> 16) & 0xFF]
^ T6[((uint)x[7] >> 8) & 0xFF]
^ T7[(uint)x[1] & 0xFF];
ulong t4 = T0[(uint)(x[5] >> 56)]
^ T1[(uint)(x[7] >> 48) & 0xFF]
^ T2[(uint)(x[1] >> 40) & 0xFF]
^ T3[(uint)(x[3] >> 32) & 0xFF]
^ T4[((uint)x[4] >> 24)]
^ T5[((uint)x[6] >> 16) & 0xFF]
^ T6[((uint)x[0] >> 8) & 0xFF]
^ T7[(uint)x[2] & 0xFF];
ulong t5 = T0[(uint)(x[6] >> 56)]
^ T1[(uint)(x[0] >> 48) & 0xFF]
^ T2[(uint)(x[2] >> 40) & 0xFF]
^ T3[(uint)(x[4] >> 32) & 0xFF]
^ T4[((uint)x[5] >> 24)]
^ T5[((uint)x[7] >> 16) & 0xFF]
^ T6[((uint)x[1] >> 8) & 0xFF]
^ T7[(uint)x[3] & 0xFF];
ulong t6 = T0[(uint)(x[7] >> 56)]
^ T1[(uint)(x[1] >> 48) & 0xFF]
^ T2[(uint)(x[3] >> 40) & 0xFF]
^ T3[(uint)(x[5] >> 32) & 0xFF]
^ T4[((uint)x[6] >> 24)]
^ T5[((uint)x[0] >> 16) & 0xFF]
^ T6[((uint)x[2] >> 8) & 0xFF]
^ T7[(uint)x[4] & 0xFF];
ulong t7 = T0[(uint)(x[0] >> 56)]
^ T1[(uint)(x[2] >> 48) & 0xFF]
^ T2[(uint)(x[4] >> 40) & 0xFF]
^ T3[(uint)(x[6] >> 32) & 0xFF]
^ T4[((uint)x[7] >> 24)]
^ T5[((uint)x[1] >> 16) & 0xFF]
^ T6[((uint)x[3] >> 8) & 0xFF]
^ T7[(uint)x[5] & 0xFF];
t0 ^= r + 1 ^ unchecked((ulong)-0x01L);
t1 ^= r + 1 ^ unchecked((ulong)-0x11L);
t2 ^= r + 1 ^ unchecked((ulong)-0x21L);
t3 ^= r + 1 ^ unchecked((ulong)-0x31L);
t4 ^= r + 1 ^ unchecked((ulong)-0x41L);
t5 ^= r + 1 ^ unchecked((ulong)-0x51L);
t6 ^= r + 1 ^ unchecked((ulong)-0x61L);
t7 ^= r + 1 ^ unchecked((ulong)-0x71L);
x[0] = T0[(uint)(t1 >> 56)]
^ T1[(uint)(t3 >> 48) & 0xFF]
^ T2[(uint)(t5 >> 40) & 0xFF]
^ T3[(uint)(t7 >> 32) & 0xFF]
^ T4[((uint)t0 >> 24)]
^ T5[((uint)t2 >> 16) & 0xFF]
^ T6[((uint)t4 >> 8) & 0xFF]
^ T7[(uint)t6 & 0xFF];
x[1] = T0[(uint)(t2 >> 56)]
^ T1[(uint)(t4 >> 48) & 0xFF]
^ T2[(uint)(t6 >> 40) & 0xFF]
^ T3[(uint)(t0 >> 32) & 0xFF]
^ T4[((uint)t1 >> 24)]
^ T5[((uint)t3 >> 16) & 0xFF]
^ T6[((uint)t5 >> 8) & 0xFF]
^ T7[(uint)t7 & 0xFF];
x[2] = T0[(uint)(t3 >> 56)]
^ T1[(uint)(t5 >> 48) & 0xFF]
^ T2[(uint)(t7 >> 40) & 0xFF]
^ T3[(uint)(t1 >> 32) & 0xFF]
^ T4[((uint)t2 >> 24)]
^ T5[((uint)t4 >> 16) & 0xFF]
^ T6[((uint)t6 >> 8) & 0xFF]
^ T7[(uint)t0 & 0xFF];
x[3] = T0[(uint)(t4 >> 56)]
^ T1[(uint)(t6 >> 48) & 0xFF]
^ T2[(uint)(t0 >> 40) & 0xFF]
^ T3[(uint)(t2 >> 32) & 0xFF]
^ T4[((uint)t3 >> 24)]
^ T5[((uint)t5 >> 16) & 0xFF]
^ T6[((uint)t7 >> 8) & 0xFF]
^ T7[(uint)t1 & 0xFF];
x[4] = T0[(uint)(t5 >> 56)]
^ T1[(uint)(t7 >> 48) & 0xFF]
^ T2[(uint)(t1 >> 40) & 0xFF]
^ T3[(uint)(t3 >> 32) & 0xFF]
^ T4[((uint)t4 >> 24)]
^ T5[((uint)t6 >> 16) & 0xFF]
^ T6[((uint)t0 >> 8) & 0xFF]
^ T7[(uint)t2 & 0xFF];
x[5] = T0[(uint)(t6 >> 56)]
^ T1[(uint)(t0 >> 48) & 0xFF]
^ T2[(uint)(t2 >> 40) & 0xFF]
^ T3[(uint)(t4 >> 32) & 0xFF]
^ T4[((uint)t5 >> 24)]
^ T5[((uint)t7 >> 16) & 0xFF]
^ T6[((uint)t1 >> 8) & 0xFF]
^ T7[(uint)t3 & 0xFF];
x[6] = T0[(uint)(t7 >> 56)]
^ T1[(uint)(t1 >> 48) & 0xFF]
^ T2[(uint)(t3 >> 40) & 0xFF]
^ T3[(uint)(t5 >> 32) & 0xFF]
^ T4[((uint)t6 >> 24)]
^ T5[((uint)t0 >> 16) & 0xFF]
^ T6[((uint)t2 >> 8) & 0xFF]
^ T7[(uint)t4 & 0xFF];
x[7] = T0[(uint)(t0 >> 56)]
^ T1[(uint)(t2 >> 48) & 0xFF]
^ T2[(uint)(t4 >> 40) & 0xFF]
^ T3[(uint)(t6 >> 32) & 0xFF]
^ T4[((uint)t7 >> 24)]
^ T5[((uint)t1 >> 16) & 0xFF]
^ T6[((uint)t3 >> 8) & 0xFF]
^ T7[(uint)t5 & 0xFF];
}
}
/** @see DigestEngine */
protected override void processBlock(byte[] data)
{
for (uint i = 0; i < 8; i ++) {
M[i] = decodeBELong(data, i * 8);
G[i] = M[i] ^ H[i];
}
doPermP(G);
doPermQ(M);
for (uint i = 0; i < 8; i ++)
H[i] ^= G[i] ^ M[i];
}
/** @see Digest */
public override string toString()
{
return "Groestl-" + (getDigestLength() << 3);
}
}
}
| |
using System;
using Duality.Resources;
using Duality.Editor;
using Duality.Properties;
using Duality.Cloning;
using Duality.Drawing;
namespace Duality.Components.Renderers
{
/// <summary>
/// Renders a sprite to represent the <see cref="GameObject"/>.
/// </summary>
[ManuallyCloned]
[EditorHintCategory(CoreResNames.CategoryGraphics)]
[EditorHintImage(CoreResNames.ImageSpriteRenderer)]
public class SpriteRenderer : Renderer
{
/// <summary>
/// Specifies how the sprites uv-Coordinates are calculated.
/// </summary>
[Flags]
public enum UVMode
{
/// <summary>
/// The uv-Coordinates are constant, stretching the supplied texture to fit the SpriteRenderers dimensions.
/// </summary>
Stretch = 0x0,
/// <summary>
/// The u-Coordinate is calculated based on the available horizontal space, allowing the supplied texture to be
/// tiled across the SpriteRenderers width.
/// </summary>
WrapHorizontal = 0x1,
/// <summary>
/// The v-Coordinate is calculated based on the available vertical space, allowing the supplied texture to be
/// tiled across the SpriteRenderers height.
/// </summary>
WrapVertical = 0x2,
/// <summary>
/// The uv-Coordinates are calculated based on the available space, allowing the supplied texture to be
/// tiled across the SpriteRenderers size.
/// </summary>
WrapBoth = WrapHorizontal | WrapVertical
}
/// <summary>
/// Specifies whether the sprite should be flipped on a given axis.
/// </summary>
[Flags]
public enum FlipMode
{
/// <summary>
/// The sprite will not be flipped at all.
/// </summary>
None = 0x0,
/// <summary>
/// The sprite will be flipped on its horizontal axis.
/// </summary>
Horizontal = 0x1,
/// <summary>
/// The sprite will be flipped on its vertical axis.
/// </summary>
Vertical = 0x2
}
protected Rect rect = Rect.Align(Alignment.Center, 0, 0, 256, 256);
protected ContentRef<Material> sharedMat = Material.DualityIcon;
protected BatchInfo customMat = null;
protected ColorRgba colorTint = ColorRgba.White;
protected UVMode rectMode = UVMode.Stretch;
protected bool pixelGrid = false;
protected int offset = 0;
protected FlipMode flipMode = FlipMode.None;
[DontSerialize] protected VertexC1P3T2[] vertices = null;
[EditorHintFlags(MemberFlags.Invisible)]
public override float BoundRadius
{
get { return this.rect.Transformed(this.gameobj.Transform.Scale, this.gameobj.Transform.Scale).BoundingRadius; }
}
/// <summary>
/// [GET / SET] The rectangular area the sprite occupies. Relative to the <see cref="GameObject"/>.
/// </summary>
[EditorHintDecimalPlaces(1)]
public Rect Rect
{
get { return this.rect; }
set { this.rect = value; }
}
/// <summary>
/// [GET / SET] The <see cref="Duality.Resources.Material"/> that is used for rendering the sprite.
/// </summary>
public ContentRef<Material> SharedMaterial
{
get { return this.sharedMat; }
set { this.sharedMat = value; }
}
/// <summary>
/// [GET / SET] A custom, local <see cref="Duality.Drawing.BatchInfo"/> overriding the <see cref="SharedMaterial"/>,
/// allowing this sprite to look unique without having to create its own <see cref="Duality.Resources.Material"/> Resource.
/// However, this feature should be used with caution: Performance is better using <see cref="SharedMaterial">shared Materials</see>.
/// </summary>
public BatchInfo CustomMaterial
{
get { return this.customMat; }
set { this.customMat = value; }
}
/// <summary>
/// [GET / SET] A color by which the sprite is tinted.
/// </summary>
public ColorRgba ColorTint
{
get { return this.colorTint; }
set { this.colorTint = value; }
}
/// <summary>
/// [GET / SET] Specifies how the sprites uv-Coordinates are calculated.
/// </summary>
public UVMode RectMode
{
get { return this.rectMode; }
set { this.rectMode = value; }
}
/// <summary>
/// [GET / SET] Specified whether or not the rendered sprite will be aligned to actual screen pixels.
/// </summary>
public bool AlignToPixelGrid
{
get { return this.pixelGrid; }
set { this.pixelGrid = value; }
}
/// <summary>
/// [GET / SET] A virtual Z offset that affects the order in which objects are drawn. If you want to assure an object is drawn after another one,
/// just assign a higher Offset value to the background object.
/// </summary>
public int Offset
{
get { return this.offset; }
set { this.offset = value; }
}
/// <summary>
/// [GET] The internal Z-Offset added to the renderers vertices based on its <see cref="Offset"/> value.
/// </summary>
[EditorHintFlags(MemberFlags.Invisible)]
public float VertexZOffset
{
get { return this.offset * 0.01f; }
}
/// <summary>
/// [GET / SET] Specifies whether the sprite should be flipped on a given axis when redered.
/// </summary>
public FlipMode Flip
{
get { return this.flipMode; }
set { this.flipMode = value; }
}
public SpriteRenderer() {}
public SpriteRenderer(Rect rect, ContentRef<Material> mainMat)
{
this.rect = rect;
this.sharedMat = mainMat;
}
protected Texture RetrieveMainTex()
{
if (this.customMat != null)
return this.customMat.MainTexture.Res;
else if (this.sharedMat.IsAvailable)
return this.sharedMat.Res.MainTexture.Res;
else
return null;
}
protected ColorRgba RetrieveMainColor()
{
if (this.customMat != null)
return this.customMat.MainColor * this.colorTint;
else if (this.sharedMat.IsAvailable)
return this.sharedMat.Res.MainColor * this.colorTint;
else
return this.colorTint;
}
protected DrawTechnique RetrieveDrawTechnique()
{
if (this.customMat != null)
return this.customMat.Technique.Res;
else if (this.sharedMat.IsAvailable)
return this.sharedMat.Res.Technique.Res;
else
return null;
}
protected void PrepareVertices(ref VertexC1P3T2[] vertices, IDrawDevice device, ColorRgba mainClr, Rect uvRect)
{
Vector3 posTemp = this.gameobj.Transform.Pos;
float scaleTemp = 1.0f;
device.PreprocessCoords(ref posTemp, ref scaleTemp);
Vector2 xDot, yDot;
MathF.GetTransformDotVec(this.GameObj.Transform.Angle, scaleTemp, out xDot, out yDot);
Rect rectTemp = this.rect.Transformed(this.gameobj.Transform.Scale, this.gameobj.Transform.Scale);
Vector2 edge1 = rectTemp.TopLeft;
Vector2 edge2 = rectTemp.BottomLeft;
Vector2 edge3 = rectTemp.BottomRight;
Vector2 edge4 = rectTemp.TopRight;
MathF.TransformDotVec(ref edge1, ref xDot, ref yDot);
MathF.TransformDotVec(ref edge2, ref xDot, ref yDot);
MathF.TransformDotVec(ref edge3, ref xDot, ref yDot);
MathF.TransformDotVec(ref edge4, ref xDot, ref yDot);
float left = uvRect.X;
float right = uvRect.RightX;
float top = uvRect.Y;
float bottom = uvRect.BottomY;
if ((this.flipMode & FlipMode.Horizontal) != FlipMode.None)
{
edge1.X = -edge1.X;
edge2.X = -edge2.X;
edge3.X = -edge3.X;
edge4.X = -edge4.X;
}
if ((this.flipMode & FlipMode.Vertical) != FlipMode.None)
{
edge1.Y = -edge1.Y;
edge2.Y = -edge2.Y;
edge3.Y = -edge3.Y;
edge4.Y = -edge4.Y;
}
if (vertices == null || vertices.Length != 4) vertices = new VertexC1P3T2[4];
vertices[0].Pos.X = posTemp.X + edge1.X;
vertices[0].Pos.Y = posTemp.Y + edge1.Y;
vertices[0].Pos.Z = posTemp.Z + this.VertexZOffset;
vertices[0].TexCoord.X = left;
vertices[0].TexCoord.Y = top;
vertices[0].Color = mainClr;
vertices[1].Pos.X = posTemp.X + edge2.X;
vertices[1].Pos.Y = posTemp.Y + edge2.Y;
vertices[1].Pos.Z = posTemp.Z + this.VertexZOffset;
vertices[1].TexCoord.X = left;
vertices[1].TexCoord.Y = bottom;
vertices[1].Color = mainClr;
vertices[2].Pos.X = posTemp.X + edge3.X;
vertices[2].Pos.Y = posTemp.Y + edge3.Y;
vertices[2].Pos.Z = posTemp.Z + this.VertexZOffset;
vertices[2].TexCoord.X = right;
vertices[2].TexCoord.Y = bottom;
vertices[2].Color = mainClr;
vertices[3].Pos.X = posTemp.X + edge4.X;
vertices[3].Pos.Y = posTemp.Y + edge4.Y;
vertices[3].Pos.Z = posTemp.Z + this.VertexZOffset;
vertices[3].TexCoord.X = right;
vertices[3].TexCoord.Y = top;
vertices[3].Color = mainClr;
if (this.pixelGrid)
{
vertices[0].Pos.X = MathF.Round(vertices[0].Pos.X);
vertices[1].Pos.X = MathF.Round(vertices[1].Pos.X);
vertices[2].Pos.X = MathF.Round(vertices[2].Pos.X);
vertices[3].Pos.X = MathF.Round(vertices[3].Pos.X);
if (MathF.RoundToInt(device.TargetSize.X) != (MathF.RoundToInt(device.TargetSize.X) / 2) * 2)
{
vertices[0].Pos.X += 0.5f;
vertices[1].Pos.X += 0.5f;
vertices[2].Pos.X += 0.5f;
vertices[3].Pos.X += 0.5f;
}
vertices[0].Pos.Y = MathF.Round(vertices[0].Pos.Y);
vertices[1].Pos.Y = MathF.Round(vertices[1].Pos.Y);
vertices[2].Pos.Y = MathF.Round(vertices[2].Pos.Y);
vertices[3].Pos.Y = MathF.Round(vertices[3].Pos.Y);
if (MathF.RoundToInt(device.TargetSize.Y) != (MathF.RoundToInt(device.TargetSize.Y) / 2) * 2)
{
vertices[0].Pos.Y += 0.5f;
vertices[1].Pos.Y += 0.5f;
vertices[2].Pos.Y += 0.5f;
vertices[3].Pos.Y += 0.5f;
}
}
}
public override void Draw(IDrawDevice device)
{
Texture mainTex = this.RetrieveMainTex();
ColorRgba mainClr = this.RetrieveMainColor();
Rect uvRect;
if (mainTex != null)
{
if (this.rectMode == UVMode.WrapBoth)
uvRect = new Rect(mainTex.UVRatio.X * this.rect.W / mainTex.PixelWidth, mainTex.UVRatio.Y * this.rect.H / mainTex.PixelHeight);
else if (this.rectMode == UVMode.WrapHorizontal)
uvRect = new Rect(mainTex.UVRatio.X * this.rect.W / mainTex.PixelWidth, mainTex.UVRatio.Y);
else if (this.rectMode == UVMode.WrapVertical)
uvRect = new Rect(mainTex.UVRatio.X, mainTex.UVRatio.Y * this.rect.H / mainTex.PixelHeight);
else
uvRect = new Rect(mainTex.UVRatio.X, mainTex.UVRatio.Y);
}
else
uvRect = new Rect(1.0f, 1.0f);
this.PrepareVertices(ref this.vertices, device, mainClr, uvRect);
if (this.customMat != null)
device.AddVertices(this.customMat, VertexMode.Quads, this.vertices);
else
device.AddVertices(this.sharedMat, VertexMode.Quads, this.vertices);
}
protected override void OnSetupCloneTargets(object targetObj, ICloneTargetSetup setup)
{
base.OnSetupCloneTargets(targetObj, setup);
SpriteRenderer target = targetObj as SpriteRenderer;
setup.HandleObject(this.customMat, target.customMat);
}
protected override void OnCopyDataTo(object targetObj, ICloneOperation operation)
{
base.OnCopyDataTo(targetObj, operation);
SpriteRenderer target = targetObj as SpriteRenderer;
target.rect = this.rect;
target.colorTint = this.colorTint;
target.rectMode = this.rectMode;
target.offset = this.offset;
operation.HandleValue(ref this.sharedMat, ref target.sharedMat);
operation.HandleObject(this.customMat, ref target.customMat);
}
}
}
| |
using System;
using System.Windows.Input;
using Xunit;
using Prism.Commands;
using System.Threading.Tasks;
using Prism.Tests.Mocks.Commands;
using Prism.Mvvm;
namespace Prism.Tests.Mvvm
{
/// <summary>
/// Summary description for DelegateCommandFixture
/// </summary>
public class DelegateCommandFixture : BindableBase
{
[Fact]
public void WhenConstructedWithGenericTypeOfObject_InitializesValues()
{
// Prepare
// Act
var actual = new DelegateCommand<object>(param => { });
// verify
Assert.NotNull(actual);
}
[Fact]
public void WhenConstructedWithGenericTypeOfNullable_InitializesValues()
{
// Prepare
// Act
var actual = new DelegateCommand<int?>(param => { });
// verify
Assert.NotNull(actual);
}
[Fact]
public void WhenConstructedWithGenericTypeIsNonNullableValueType_Throws()
{
Assert.Throws<InvalidCastException>(() =>
{
var actual = new DelegateCommand<int>(param => { });
});
}
[Fact]
public async Task ExecuteCallsPassedInExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
object parameter = new object();
await command.Execute(parameter);
Assert.Same(parameter, handlers.ExecuteParameter);
}
[Fact]
public void CanExecuteCallsPassedInCanExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute, handlers.CanExecute);
object parameter = new object();
handlers.CanExecuteReturnValue = true;
bool retVal = command.CanExecute(parameter);
Assert.Same(parameter, handlers.CanExecuteParameter);
Assert.Equal(handlers.CanExecuteReturnValue, retVal);
}
[Fact]
public void CanExecuteReturnsTrueWithouthCanExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
bool retVal = command.CanExecute(null);
Assert.Equal(true, retVal);
}
[Fact]
public void RaiseCanExecuteChangedRaisesCanExecuteChanged()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
bool canExecuteChangedRaised = false;
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
command.RaiseCanExecuteChanged();
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void CanRemoveCanExecuteChangedHandler()
{
var command = new DelegateCommand<object>((o) => { });
bool canExecuteChangedRaised = false;
EventHandler handler = (s, e) => canExecuteChangedRaised = true;
command.CanExecuteChanged += handler;
command.CanExecuteChanged -= handler;
command.RaiseCanExecuteChanged();
Assert.False(canExecuteChangedRaised);
}
[Fact]
public void ShouldPassParameterInstanceOnExecute()
{
bool executeCalled = false;
MyClass testClass = new MyClass();
ICommand command = new DelegateCommand<MyClass>(delegate(MyClass parameter)
{
Assert.Same(testClass, parameter);
executeCalled = true;
});
command.Execute(testClass);
Assert.True(executeCalled);
}
[Fact]
public void ShouldPassParameterInstanceOnCanExecute()
{
bool canExecuteCalled = false;
MyClass testClass = new MyClass();
ICommand command = new DelegateCommand<MyClass>((p) => { }, delegate(MyClass parameter)
{
Assert.Same(testClass, parameter);
canExecuteCalled = true;
return true;
});
command.CanExecute(testClass);
Assert.True(canExecuteCalled);
}
[Fact]
public void ShouldThrowIfAllDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>(null, null);
});
}
[Fact]
public void ShouldThrowIfExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>(null);
});
}
[Fact]
public void ShouldThrowIfCanExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>((o) => { }, null);
});
}
[Fact]
public void DelegateCommandBaseShouldThrowIfAllDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommandMock(null, null);
});
}
[Fact]
public void DelegateCommandBaseShouldThrowIfExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommandMock(null);
});
}
[Fact]
public void DelegateCommandBaseShouldThrowIfCanExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommandMock((o) => { }, null);
});
}
//TODO: BBL: This test fails intermittently. The cause is unknown, but we think it may be a race condition issue.
//In order to reduce the friction of our automated build processes, we are commenting out this test.
//[Fact]
//public void NonGenericDelegateCommandShouldInvokeExplicitExecuteFunc()
//{
// bool executed = false;
// ICommand command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { executed = true; }));
// command.Execute(null);
// Assert.True(executed);
//}
[Fact]
public void IsActivePropertyIsFalseByDeafult()
{
var command = new DelegateCommand<object>(DoNothing);
Assert.False(command.IsActive);
}
[Fact]
public void IsActivePropertyChangeFiresEvent()
{
bool fired = false;
var command = new DelegateCommand<object>(DoNothing);
command.IsActiveChanged += delegate { fired = true; };
command.IsActive = true;
Assert.True(fired);
}
[Fact]
public async Task NonGenericDelegateCommandExecuteShouldInvokeExecuteAction()
{
bool executed = false;
var command = new DelegateCommand(() => { executed = true; });
await command.Execute();
Assert.True(executed);
}
[Fact]
public void NonGenericDelegateCommandCanExecuteShouldInvokeCanExecuteFunc()
{
bool invoked = false;
var command = new DelegateCommand(() => { }, () => { invoked = true; return true; });
bool canExecute = command.CanExecute();
Assert.True(invoked);
Assert.True(canExecute);
}
[Fact]
public void NonGenericDelegateCommandShouldDefaultCanExecuteToTrue()
{
var command = new DelegateCommand(() => { });
Assert.True(command.CanExecute());
}
[Fact]
public void NonGenericDelegateThrowsIfDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(null, null);
});
}
[Fact]
public void NonGenericDelegateCommandThrowsIfExecuteDelegateIsNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(null);
});
}
[Fact]
public void NonGenericDelegateCommandThrowsIfCanExecuteDelegateIsNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(() => { }, null);
});
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerWithExecuteFuncShouldNotBeNull()
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }));
Assert.NotNull(command);
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerWithExecuteAndCanExecuteFuncShouldNotBeNull()
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }), (o) => true);
Assert.NotNull(command);
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerCanExecuteShouldBeTrueByDefault()
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }));
var canExecute = command.CanExecute(null);
Assert.True(canExecute);
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerWithNullExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand<object>.FromAsyncHandler(null);
});
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerWithNullCanExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }), null);
});
}
[Fact]
public void DelegateCommandBaseWithNullExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommandMock.FromAsyncHandler(null);
});
}
[Fact]
public void DelegateCommandBaseWithNullCanExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }), null);
});
}
[Fact]
public async Task GenericDelegateCommandFromAsyncHandlerExecuteShouldInvokeExecuteFunc()
{
bool executed = false;
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => executed = true));
await command.Execute(null);
Assert.True(executed);
}
[Fact]
public void DelegateCommandFromAsyncHandlerWithExecuteFuncShouldNotBeNull()
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }));
Assert.NotNull(command);
}
[Fact]
public void DelegateCommandFromAsyncHandlerCanExecuteShouldBeTrueByDefault()
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }));
var canExecute = command.CanExecute();
Assert.True(canExecute);
}
[Fact]
public void DelegateCommandFromAsyncHandlerWithNullExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand.FromAsyncHandler(null);
});
}
[Fact]
public void DelegateCommandFromAsyncHandlerWithExecuteAndCanExecuteFuncShouldNotBeNull()
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }), () => true);
Assert.NotNull(command);
}
[Fact]
public void DelegateCommandFromAsyncHandlerWithNullCanExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }), null);
});
}
[Fact]
public async Task DelegateCommandFromAsyncHandlerExecuteShouldInvokeExecuteFunc()
{
bool executed = false;
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => executed = true));
await command.Execute();
Assert.True(executed);
}
[Fact]
public void DelegateCommandFromAsyncHandlerCanExecuteShouldInvokeCanExecuteFunc()
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }), () => true);
var canExecute = command.CanExecute();
Assert.True(canExecute);
}
[Fact]
public void NonGenericDelegateCommandShouldObserveCanExecute()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute((o) => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void NonGenericDelegateCommandShouldObserveCanExecuteAndObserveOtherProperties()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute((o) => BoolProperty).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
canExecuteChangedRaised = false;
Assert.False(canExecuteChangedRaised);
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void NonGenericDelegateCommandShouldNotObserveDuplicateCanExecute()
{
Assert.Throws<ArgumentException>(() =>
{
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute((o) => BoolProperty).ObservesCanExecute((o) => BoolProperty);
});
}
[Fact]
public void NonGenericDelegateCommandShouldObserveOneProperty()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandShouldObserveMultipleProperties()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
canExecuteChangedRaised = false;
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandShouldNotObserveDuplicateProperties()
{
Assert.Throws<ArgumentException>(() =>
{
DelegateCommand command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => IntProperty);
});
}
[Fact]
public void GenericDelegateCommandShouldObserveCanExecute()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand<object>((o) => { }).ObservesCanExecute((o) => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void GenericDelegateCommandShouldObserveCanExecuteAndObserveOtherProperties()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand<object>((o) => { }).ObservesCanExecute((o) => BoolProperty).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
canExecuteChangedRaised = false;
Assert.False(canExecuteChangedRaised);
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void GenericDelegateCommandShouldNotObserveDuplicateCanExecute()
{
Assert.Throws<ArgumentException>(() =>
{
ICommand command =
new DelegateCommand<object>((o) => { }).ObservesCanExecute((o) => BoolProperty)
.ObservesCanExecute((o) => BoolProperty);
});
}
[Fact]
public void GenericDelegateCommandShouldObserveOneProperty()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandShouldObserveMultipleProperties()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
canExecuteChangedRaised = false;
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandShouldNotObserveDuplicateProperties()
{
Assert.Throws<ArgumentException>(() =>
{
DelegateCommand<object> command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => IntProperty);
});
}
private bool _boolProperty;
public bool BoolProperty
{
get { return _boolProperty; }
set { SetProperty(ref _boolProperty, value); }
}
private int _intProperty;
public int IntProperty
{
get { return _intProperty; }
set { SetProperty(ref _intProperty, value); }
}
class CanExecutChangeHandler
{
public bool CanExeucteChangedHandlerCalled;
public void CanExecuteChangeHandler(object sender, EventArgs e)
{
CanExeucteChangedHandlerCalled = true;
}
}
public void DoNothing(object param)
{ }
class DelegateHandlers
{
public bool CanExecuteReturnValue = true;
public object CanExecuteParameter;
public object ExecuteParameter;
public bool CanExecute(object parameter)
{
CanExecuteParameter = parameter;
return CanExecuteReturnValue;
}
public void Execute(object parameter)
{
ExecuteParameter = parameter;
}
}
}
internal class MyClass
{
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using Microsoft.AspNetCore.Internal;
namespace Microsoft.AspNetCore.Http.Connections
{
/// <summary>
/// The protocol for reading and writing negotiate requests and responses.
/// </summary>
public static class NegotiateProtocol
{
private const string ConnectionIdPropertyName = "connectionId";
private static readonly JsonEncodedText ConnectionIdPropertyNameBytes = JsonEncodedText.Encode(ConnectionIdPropertyName);
private const string ConnectionTokenPropertyName = "connectionToken";
private static readonly JsonEncodedText ConnectionTokenPropertyNameBytes = JsonEncodedText.Encode(ConnectionTokenPropertyName);
private const string UrlPropertyName = "url";
private static readonly JsonEncodedText UrlPropertyNameBytes = JsonEncodedText.Encode(UrlPropertyName);
private const string AccessTokenPropertyName = "accessToken";
private static readonly JsonEncodedText AccessTokenPropertyNameBytes = JsonEncodedText.Encode(AccessTokenPropertyName);
private const string AvailableTransportsPropertyName = "availableTransports";
private static readonly JsonEncodedText AvailableTransportsPropertyNameBytes = JsonEncodedText.Encode(AvailableTransportsPropertyName);
private const string TransportPropertyName = "transport";
private static readonly JsonEncodedText TransportPropertyNameBytes = JsonEncodedText.Encode(TransportPropertyName);
private const string TransferFormatsPropertyName = "transferFormats";
private static readonly JsonEncodedText TransferFormatsPropertyNameBytes = JsonEncodedText.Encode(TransferFormatsPropertyName);
private const string ErrorPropertyName = "error";
private static readonly JsonEncodedText ErrorPropertyNameBytes = JsonEncodedText.Encode(ErrorPropertyName);
private const string NegotiateVersionPropertyName = "negotiateVersion";
private static readonly JsonEncodedText NegotiateVersionPropertyNameBytes = JsonEncodedText.Encode(NegotiateVersionPropertyName);
// Use C#7.3's ReadOnlySpan<byte> optimization for static data https://vcsjones.com/2019/02/01/csharp-readonly-span-bytes-static/
// Used to detect ASP.NET SignalR Server connection attempt
private static ReadOnlySpan<byte> ProtocolVersionPropertyNameBytes => new byte[] { (byte)'P', (byte)'r', (byte)'o', (byte)'t', (byte)'o', (byte)'c', (byte)'o', (byte)'l', (byte)'V', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n' };
/// <summary>
/// Writes the <paramref name="response"/> to the <paramref name="output"/>.
/// </summary>
/// <param name="response">The negotiation response generated in response to a negotiation request.</param>
/// <param name="output">Where the <paramref name="response"/> is written to as Json.</param>
public static void WriteResponse(NegotiationResponse response, IBufferWriter<byte> output)
{
var reusableWriter = ReusableUtf8JsonWriter.Get(output);
try
{
var writer = reusableWriter.GetJsonWriter();
writer.WriteStartObject();
// If we already have an error its due to a protocol version incompatibility.
// We can just write the error and complete the JSON object and return.
if (!string.IsNullOrEmpty(response.Error))
{
writer.WriteString(ErrorPropertyNameBytes, response.Error);
writer.WriteEndObject();
writer.Flush();
Debug.Assert(writer.CurrentDepth == 0);
return;
}
writer.WriteNumber(NegotiateVersionPropertyNameBytes, response.Version);
if (!string.IsNullOrEmpty(response.Url))
{
writer.WriteString(UrlPropertyNameBytes, response.Url);
}
if (!string.IsNullOrEmpty(response.AccessToken))
{
writer.WriteString(AccessTokenPropertyNameBytes, response.AccessToken);
}
if (!string.IsNullOrEmpty(response.ConnectionId))
{
writer.WriteString(ConnectionIdPropertyNameBytes, response.ConnectionId);
}
if (response.Version > 0 && !string.IsNullOrEmpty(response.ConnectionToken))
{
writer.WriteString(ConnectionTokenPropertyNameBytes, response.ConnectionToken);
}
writer.WriteStartArray(AvailableTransportsPropertyNameBytes);
if (response.AvailableTransports != null)
{
var transportCount = response.AvailableTransports.Count;
for (var i = 0; i < transportCount; ++i)
{
var availableTransport = response.AvailableTransports[i];
writer.WriteStartObject();
if (availableTransport.Transport != null)
{
writer.WriteString(TransportPropertyNameBytes, availableTransport.Transport);
}
else
{
// Might be able to remove this after https://github.com/dotnet/corefx/issues/34632 is resolved
writer.WriteNull(TransportPropertyNameBytes);
}
writer.WriteStartArray(TransferFormatsPropertyNameBytes);
if (availableTransport.TransferFormats != null)
{
var formatCount = availableTransport.TransferFormats.Count;
for (var j = 0; j < formatCount; ++j)
{
writer.WriteStringValue(availableTransport.TransferFormats[j]);
}
}
writer.WriteEndArray();
writer.WriteEndObject();
}
}
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();
Debug.Assert(writer.CurrentDepth == 0);
}
finally
{
ReusableUtf8JsonWriter.Return(reusableWriter);
}
}
/// <summary>
/// Parses a <see cref="NegotiationResponse"/> from the <paramref name="content"/> as Json.
/// </summary>
/// <param name="content">The bytes of a Json payload that represents a <see cref="NegotiationResponse"/>.</param>
/// <returns>The parsed <see cref="NegotiationResponse"/>.</returns>
public static NegotiationResponse ParseResponse(ReadOnlySpan<byte> content)
{
try
{
var reader = new Utf8JsonReader(content, isFinalBlock: true, state: default);
reader.CheckRead();
reader.EnsureObjectStart();
string? connectionId = null;
string? connectionToken = null;
string? url = null;
string? accessToken = null;
List<AvailableTransport>? availableTransports = null;
string? error = null;
int version = 0;
var completed = false;
while (!completed && reader.CheckRead())
{
switch (reader.TokenType)
{
case JsonTokenType.PropertyName:
if (reader.ValueTextEquals(UrlPropertyNameBytes.EncodedUtf8Bytes))
{
url = reader.ReadAsString(UrlPropertyName);
}
else if (reader.ValueTextEquals(AccessTokenPropertyNameBytes.EncodedUtf8Bytes))
{
accessToken = reader.ReadAsString(AccessTokenPropertyName);
}
else if (reader.ValueTextEquals(ConnectionIdPropertyNameBytes.EncodedUtf8Bytes))
{
connectionId = reader.ReadAsString(ConnectionIdPropertyName);
}
else if (reader.ValueTextEquals(ConnectionTokenPropertyNameBytes.EncodedUtf8Bytes))
{
connectionToken = reader.ReadAsString(ConnectionTokenPropertyName);
}
else if (reader.ValueTextEquals(NegotiateVersionPropertyNameBytes.EncodedUtf8Bytes))
{
version = reader.ReadAsInt32(NegotiateVersionPropertyName).GetValueOrDefault();
}
else if (reader.ValueTextEquals(AvailableTransportsPropertyNameBytes.EncodedUtf8Bytes))
{
reader.CheckRead();
reader.EnsureArrayStart();
availableTransports = new List<AvailableTransport>();
while (reader.CheckRead())
{
if (reader.TokenType == JsonTokenType.StartObject)
{
availableTransports.Add(ParseAvailableTransport(ref reader));
}
else if (reader.TokenType == JsonTokenType.EndArray)
{
break;
}
}
}
else if (reader.ValueTextEquals(ErrorPropertyNameBytes.EncodedUtf8Bytes))
{
error = reader.ReadAsString(ErrorPropertyName);
}
else if (reader.ValueTextEquals(ProtocolVersionPropertyNameBytes))
{
throw new InvalidOperationException("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");
}
else
{
reader.Skip();
}
break;
case JsonTokenType.EndObject:
completed = true;
break;
default:
throw new InvalidDataException($"Unexpected token '{reader.TokenType}' when reading negotiation response JSON.");
}
}
if (url == null && error == null)
{
// if url isn't specified or there isn't an error, connectionId and available transports are required
if (connectionId == null)
{
throw new InvalidDataException($"Missing required property '{ConnectionIdPropertyName}'.");
}
if (version > 0)
{
if (connectionToken == null)
{
throw new InvalidDataException($"Missing required property '{ConnectionTokenPropertyName}'.");
}
}
if (availableTransports == null)
{
throw new InvalidDataException($"Missing required property '{AvailableTransportsPropertyName}'.");
}
}
return new NegotiationResponse
{
ConnectionId = connectionId,
ConnectionToken = connectionToken,
Url = url,
AccessToken = accessToken,
AvailableTransports = availableTransports,
Error = error,
Version = version
};
}
catch (Exception ex)
{
throw new InvalidDataException("Invalid negotiation response received.", ex);
}
}
private static AvailableTransport ParseAvailableTransport(ref Utf8JsonReader reader)
{
var availableTransport = new AvailableTransport();
while (reader.CheckRead())
{
switch (reader.TokenType)
{
case JsonTokenType.PropertyName:
if (reader.ValueTextEquals(TransportPropertyNameBytes.EncodedUtf8Bytes))
{
availableTransport.Transport = reader.ReadAsString(TransportPropertyName);
}
else if (reader.ValueTextEquals(TransferFormatsPropertyNameBytes.EncodedUtf8Bytes))
{
reader.CheckRead();
reader.EnsureArrayStart();
var completed = false;
availableTransport.TransferFormats = new List<string>();
while (!completed && reader.CheckRead())
{
switch (reader.TokenType)
{
case JsonTokenType.String:
availableTransport.TransferFormats.Add(reader.GetString()!);
break;
case JsonTokenType.EndArray:
completed = true;
break;
default:
throw new InvalidDataException($"Unexpected token '{reader.TokenType}' when reading transfer formats JSON.");
}
}
}
else
{
reader.Skip();
}
break;
case JsonTokenType.EndObject:
if (availableTransport.Transport == null)
{
throw new InvalidDataException($"Missing required property '{TransportPropertyName}'.");
}
if (availableTransport.TransferFormats == null)
{
throw new InvalidDataException($"Missing required property '{TransferFormatsPropertyName}'.");
}
return availableTransport;
default:
throw new InvalidDataException($"Unexpected token '{reader.TokenType}' when reading available transport JSON.");
}
}
throw new InvalidDataException("Unexpected end when reading JSON.");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.IndicesPutMapping2
{
public partial class IndicesPutMapping2YamlTests
{
public class IndicesPutMapping2AllPathOptionsYamlBase : YamlTestsBase
{
public IndicesPutMapping2AllPathOptionsYamlBase() : base()
{
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index1", null));
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index2", null));
//do indices.create
this.Do(()=> _client.IndicesCreate("foo", null));
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutOneMappingPerIndex2Tests : IndicesPutMapping2AllPathOptionsYamlBase
{
[Test]
public void PutOneMappingPerIndex2Test()
{
//do indices.put_mapping
_body = new {
test_type= new {
properties= new {
text= new {
type= "string",
analyzer= "whitespace"
}
}
}
};
this.Do(()=> _client.IndicesPutMapping("test_index1", "test_type", _body));
//do indices.put_mapping
_body = new {
test_type= new {
properties= new {
text= new {
type= "string",
analyzer= "whitespace"
}
}
}
};
this.Do(()=> _client.IndicesPutMapping("test_index2", "test_type", _body));
//do indices.get_mapping
this.Do(()=> _client.IndicesGetMappingForAll());
//match _response.test_index1.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.type, @"string");
//match _response.test_index1.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.test_index2.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.type, @"string");
//match _response.test_index2.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.analyzer, @"whitespace");
//is_false _response.foo;
this.IsFalse(_response.foo);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutMappingInAllIndex3Tests : IndicesPutMapping2AllPathOptionsYamlBase
{
[Test]
public void PutMappingInAllIndex3Test()
{
//do indices.put_mapping
_body = new {
test_type= new {
properties= new {
text= new {
type= "string",
analyzer= "whitespace"
}
}
}
};
this.Do(()=> _client.IndicesPutMapping("_all", "test_type", _body));
//do indices.get_mapping
this.Do(()=> _client.IndicesGetMappingForAll());
//match _response.test_index1.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.type, @"string");
//match _response.test_index1.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.test_index2.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.type, @"string");
//match _response.test_index2.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.foo.mappings.test_type.properties.text.type:
this.IsMatch(_response.foo.mappings.test_type.properties.text.type, @"string");
//match _response.foo.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.foo.mappings.test_type.properties.text.analyzer, @"whitespace");
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutMappingInIndex4Tests : IndicesPutMapping2AllPathOptionsYamlBase
{
[Test]
public void PutMappingInIndex4Test()
{
//do indices.put_mapping
_body = new {
test_type= new {
properties= new {
text= new {
type= "string",
analyzer= "whitespace"
}
}
}
};
this.Do(()=> _client.IndicesPutMapping("*", "test_type", _body));
//do indices.get_mapping
this.Do(()=> _client.IndicesGetMappingForAll());
//match _response.test_index1.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.type, @"string");
//match _response.test_index1.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.test_index2.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.type, @"string");
//match _response.test_index2.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.foo.mappings.test_type.properties.text.type:
this.IsMatch(_response.foo.mappings.test_type.properties.text.type, @"string");
//match _response.foo.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.foo.mappings.test_type.properties.text.analyzer, @"whitespace");
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutMappingInPrefixIndex5Tests : IndicesPutMapping2AllPathOptionsYamlBase
{
[Test]
public void PutMappingInPrefixIndex5Test()
{
//do indices.put_mapping
_body = new {
test_type= new {
properties= new {
text= new {
type= "string",
analyzer= "whitespace"
}
}
}
};
this.Do(()=> _client.IndicesPutMapping("test_index*", "test_type", _body));
//do indices.get_mapping
this.Do(()=> _client.IndicesGetMappingForAll());
//match _response.test_index1.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.type, @"string");
//match _response.test_index1.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.test_index2.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.type, @"string");
//match _response.test_index2.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.analyzer, @"whitespace");
//is_false _response.foo;
this.IsFalse(_response.foo);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutMappingInListOfIndices6Tests : IndicesPutMapping2AllPathOptionsYamlBase
{
[Test]
public void PutMappingInListOfIndices6Test()
{
//do indices.put_mapping
_body = new {
test_type= new {
properties= new {
text= new {
type= "string",
analyzer= "whitespace"
}
}
}
};
this.Do(()=> _client.IndicesPutMapping("test_index1,test_index2", "test_type", _body));
//do indices.get_mapping
this.Do(()=> _client.IndicesGetMappingForAll());
//match _response.test_index1.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.type, @"string");
//match _response.test_index1.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.test_index2.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.type, @"string");
//match _response.test_index2.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.analyzer, @"whitespace");
//is_false _response.foo;
this.IsFalse(_response.foo);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutMappingWithBlankIndex7Tests : IndicesPutMapping2AllPathOptionsYamlBase
{
[Test]
public void PutMappingWithBlankIndex7Test()
{
//do indices.put_mapping
_body = new {
test_type= new {
properties= new {
text= new {
type= "string",
analyzer= "whitespace"
}
}
}
};
this.Do(()=> _client.IndicesPutMappingForAll("test_type", _body));
//do indices.get_mapping
this.Do(()=> _client.IndicesGetMappingForAll());
//match _response.test_index1.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.type, @"string");
//match _response.test_index1.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index1.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.test_index2.mappings.test_type.properties.text.type:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.type, @"string");
//match _response.test_index2.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.test_index2.mappings.test_type.properties.text.analyzer, @"whitespace");
//match _response.foo.mappings.test_type.properties.text.type:
this.IsMatch(_response.foo.mappings.test_type.properties.text.type, @"string");
//match _response.foo.mappings.test_type.properties.text.analyzer:
this.IsMatch(_response.foo.mappings.test_type.properties.text.analyzer, @"whitespace");
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutMappingWithMissingType8Tests : IndicesPutMapping2AllPathOptionsYamlBase
{
[Test]
public void PutMappingWithMissingType8Test()
{
//do indices.put_mapping
this.Do(()=> _client.IndicesPutMappingForAll("", null), shouldCatch: @"param");
}
}
}
}
| |
using System;
using System.Xml.Serialization;
namespace Data
{
/// <summary>
/// A TOF is the result of a single detector looking at a single pulse from the source.
/// </summary>
[Serializable]
public class TOF : MarshalByRefObject
{
private double[] tofData;
//private int length;
private int gateStartTime;
private int clockPeriod;
public double calibration;
public TOF() { }
public double Integrate()
{
double sum = 0;
foreach (double sample in tofData) sum += sample;
return (sum * clockPeriod);
}
// This helper function takes a pair of gates and trims them to the width of the
// captured data. It returns null if the gates don't make sense.
private double[] TrimGates(double startTime, double endTime)
{
// check for swapped gates
if (startTime > endTime) return null;
// is the gate region null, or entirely outside the TOF?
int gateEndTime = gateStartTime + (Length - 1) * clockPeriod;
if (startTime == endTime) return null;
if (startTime > gateEndTime) return null;
if (endTime < gateStartTime) return null;
// trim the gates
if (endTime > gateEndTime) endTime = gateEndTime;
if (startTime < gateStartTime) startTime = gateStartTime;
// it's now possible for the trimmed gate region to be null (!) so check again
if (startTime == endTime) return null;
return new double[] { startTime, endTime };
}
// Integrate returns the area under a part of the TOF curve. It interpolates linearly
// between sample points i.e. between each pair of sample times is a trapezium: this
// function returns the area of these trapeziums that are between the gates. A picture
// would really be better here!
public double Integrate(double startTime, double endTime)
{
double[] trimmedGates = TrimGates(startTime, endTime);
if (trimmedGates == null) return 0;
startTime = trimmedGates[0];
endTime = trimmedGates[1];
return IntegrateInternal(startTime, endTime);
}
// This function actually does the integration. Broken out so that GatedMean can use it also.
private double IntegrateInternal(double startTime, double endTime)
{
// calculate the the points that are included in the range, plus the point above and below
double p = (startTime - (double)gateStartTime) / (double)clockPeriod;
double q = (endTime - (double)gateStartTime) / (double)clockPeriod;
int lowest = (int)Math.Floor(p);
int highest = (int)Math.Ceiling(q);
// sum over all trapeziums included in the gate range, even those partially included
double sum = 0.0;
for (int i = lowest; i < highest; i++) sum += ((double)clockPeriod * 0.5) * (tofData[i] + tofData[i + 1]);
// correct the first and last trapeziums which may not be fully included
sum -= ((2 * tofData[lowest]) + (tofData[lowest + 1] - tofData[lowest])
* (p - Math.Floor(p))) * ((double)clockPeriod * 0.5 * (p - Math.Floor(p)));
sum -= ((2 * tofData[highest]) - (tofData[highest] - tofData[highest - 1])
* (Math.Ceiling(q) - q)) * ((double)clockPeriod * 0.5 * (Math.Ceiling(q) - q));
return sum;
}
//Copy pasted what's above, and added Math.Abs everywhere.
public double AbsValIntegrate(double startTime, double endTime)
{
double[] trimmedGates = TrimGates(startTime, endTime);
if (trimmedGates == null) return 0;
startTime = trimmedGates[0];
endTime = trimmedGates[1];
return IntegrateAbsValInternal(startTime, endTime);
}
private double IntegrateAbsValInternal(double startTime, double endTime)
{
// calculate the the points that are included in the range, plus the point above and below
double p = (startTime - (double)gateStartTime) / (double)clockPeriod;
double q = (endTime - (double)gateStartTime) / (double)clockPeriod;
int lowest = (int)Math.Floor(p);
int highest = (int)Math.Ceiling(q);
// sum over all trapeziums included in the gate range, even those partially included
double sum = 0.0;
for (int i = lowest; i < highest; i++) sum += ((double)clockPeriod * 0.5) * (Math.Abs(tofData[i]) + Math.Abs(tofData[i + 1]));
// correct the first and last trapeziums which may not be fully included
sum -= ((2 * Math.Abs(tofData[lowest])) + (Math.Abs(tofData[lowest + 1]) - Math.Abs(tofData[lowest]))
* (p - Math.Floor(p))) * ((double)clockPeriod * 0.5 * (p - Math.Floor(p)));
sum -= ((2 * Math.Abs(tofData[highest])) - (Math.Abs(tofData[highest]) - Math.Abs(tofData[highest - 1]))
* (Math.Ceiling(q) - q)) * ((double)clockPeriod * 0.5 * (Math.Ceiling(q) - q));
return sum;
}
// this is the old integrate method that did no interpolation.
//public double IntegrateOld(double startTime, double endTime)
//{
// int low = (int)Math.Ceiling((startTime - gateStartTime) / clockPeriod);
// int high = (int)Math.Floor((endTime - gateStartTime) / clockPeriod);
// // check the range is sensible
// if (low < 0) low = 0;
// if (high > length - 1) high = length - 1;
// if (low > high) return 0;
// double sum = 0;
// for (int i = low; i <= high; i++) sum += tofData[i];
// return (sum * clockPeriod);
//}
public double Mean
{
get
{
double tmp = 0;
for (int i = 0; i < Data.Length; i++) tmp += Data[i];
return tmp / Data.Length;
}
}
public double GatedMean(double startTime, double endTime)
{
double[] trimmedGates = TrimGates(startTime, endTime);
if (trimmedGates == null) return 0;
startTime = trimmedGates[0];
endTime = trimmedGates[1];
return IntegrateInternal(startTime, endTime) / (endTime - startTime);
}
public static TOF operator +(TOF p1, TOF p2)
{
if (p1.ClockPeriod == p2.ClockPeriod && p1.GateStartTime == p2.GateStartTime
&& p1.Length == p2.Length)
{
double[] tempData = new double[p1.Length];
for (int i = 0; i < p1.Length; i++)
{
tempData[i] = p1.Data[i] + p2.Data[i];
}
TOF temp = new TOF();
temp.Data = tempData;
temp.GateStartTime = p1.GateStartTime;
temp.ClockPeriod = p1.ClockPeriod;
temp.Calibration = p1.Calibration;
return temp;
}
else
{
if (p1.Length == 0) return p2;
if (p2.Length == 0) return p1;
return null;
}
}
public static TOF operator -(TOF p1, TOF p2)
{
TOF temp = new TOF();
temp.Data = new double[p2.Data.Length];
temp.GateStartTime = p1.GateStartTime;
temp.ClockPeriod = p1.ClockPeriod;
temp.Calibration = p1.Calibration;
for (int i = 0; i < p2.Data.Length; i++)
{
temp.Data[i] = -p2.Data[i];
}
return p1 + temp;
}
static public TOF operator *(TOF t, double d)
{
TOF temp = new TOF();
temp.Data = new double[t.Data.Length];
temp.GateStartTime = t.GateStartTime;
temp.ClockPeriod = t.ClockPeriod;
temp.Calibration = t.Calibration;
for (int i = 0; i < t.Data.Length; i++)
{
temp.Data[i] = d * t.Data[i];
}
return temp;
}
public static TOF operator /(TOF p, double d)
{
double[] tempData = new double[p.Length];
for (int i = 0; i < p.Length; i++)
{
tempData[i] = p.Data[i] / d;
}
TOF temp = new TOF();
temp.Data = tempData;
temp.GateStartTime = p.GateStartTime;
temp.ClockPeriod = p.ClockPeriod;
temp.Calibration = p.Calibration;
return temp;
}
static public TOF operator /(TOF t1, TOF t2)
{
TOF temp = new TOF();
temp.Data = new double[t1.Data.Length];
temp.GateStartTime = t1.GateStartTime;
temp.ClockPeriod = t1.ClockPeriod;
temp.Calibration = t1.Calibration;
for (int i = 0; i < t1.Data.Length; i++)
{
temp.Data[i] = t1.Data[i] / t2.Data[i];
}
return temp;
}
static public TOF operator *(TOF t1, TOF t2)
{
TOF temp = new TOF();
temp.Data = new double[t1.Data.Length];
temp.GateStartTime = t1.GateStartTime;
temp.ClockPeriod = t1.ClockPeriod;
for (int i = 0; i < t1.Data.Length; i++)
{
temp.Data[i] = t1.Data[i] * t2.Data[i];
}
return temp;
}
[XmlArrayItem("s")]
public double[] Data
{
get { return tofData; }
set
{
tofData = value;
// length = value.Length;
}
}
public int Length
{
get
{
if (tofData != null) return tofData.Length;
else return 0;
}
}
public int GateStartTime
{
get { return gateStartTime; }
set { gateStartTime = value; }
}
public int GateLength
{
get { return Length * clockPeriod; }
}
public int ClockPeriod
{
get { return clockPeriod; }
set { clockPeriod = value; }
}
public double Calibration
{
get { return calibration; }
set { calibration = value; }
}
public int[] Times
{
get
{
int[] times = new int[Length];
for (int i = 0; i < Length; i++) times[i] = gateStartTime + (i * clockPeriod);
return times;
}
}
// returns a typically sized TOF with random data
private const int RANDOM_TOF_SIZE = 80;
private static Random r = new Random();
public static TOF Random()
{
TOF t = new TOF();
t.Data = new double[RANDOM_TOF_SIZE];
for (int i = 0; i < RANDOM_TOF_SIZE; i++) t.Data[i] = r.NextDouble();
t.Calibration = 1.0;
t.ClockPeriod = 10;
t.GateStartTime = 1800;
return t;
}
// helper to make a TOF from a single data point
public TOF(double d)
{
this.Data = new double[1];
this.Data[0] = d;
this.ClockPeriod = 1;
this.gateStartTime = 0;
this.Calibration = 1.0;
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define USE_TRACING
#define DEBUG
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Configuration;
using System.Net;
using NUnit.Framework;
using Google.GData.Client;
using Google.GData.Client.UnitTests;
using Google.GData.Extensions;
using Google.GData.Calendar;
using Google.GData.AccessControl;
namespace Google.GData.Client.LiveTests
{
[TestFixture]
[Category("LiveTest")]
public class CalendarTestSuite : BaseLiveTestClass
{
/// <summary>
/// test Uri for google calendarURI
/// </summary>
protected string defaultCalendarUri;
/// <summary>
/// test URI for Google Calendar owncalendars feed
/// </summary>
protected string defaultOwnCalendarsUri;
/// <summary>
/// test Uri for google acl feed
/// </summary>
protected string aclFeedUri;
/// <summary>
/// test Uri for google composite calendarURI
/// </summary>
protected string defaultCompositeUri;
//////////////////////////////////////////////////////////////////////
/// <summary>default empty constructor</summary>
//////////////////////////////////////////////////////////////////////
public CalendarTestSuite()
{
}
//////////////////////////////////////////////////////////////////////
/// <summary>the setup method</summary>
//////////////////////////////////////////////////////////////////////
[SetUp] public override void InitTest()
{
Tracing.TraceCall();
base.InitTest();
GDataGAuthRequestFactory authFactory = this.factory as GDataGAuthRequestFactory;
if (authFactory != null)
{
authFactory.Handler = this.strAuthHandler;
}
FeedCleanup(this.defaultCalendarUri, this.userName, this.passWord, VersionDefaults.Major);
}
/////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
/// <summary>the end it all method</summary>
//////////////////////////////////////////////////////////////////////
[TearDown] public override void EndTest()
{
Tracing.TraceCall();
FeedCleanup(this.defaultCalendarUri, this.userName, this.passWord, VersionDefaults.Major);
Tracing.ExitTracing();
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>private void ReadConfigFile()</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
protected override void ReadConfigFile()
{
base.ReadConfigFile();
if (unitTestConfiguration.Contains("calendarURI") == true)
{
this.defaultCalendarUri = (string) unitTestConfiguration["calendarURI"];
Tracing.TraceInfo("Read calendarURI value: " + this.defaultCalendarUri);
}
if (unitTestConfiguration.Contains("aclFeedURI") == true)
{
this.aclFeedUri = (string) unitTestConfiguration["aclFeedURI"];
Tracing.TraceInfo("Read aclFeed value: " + this.aclFeedUri);
}
if (unitTestConfiguration.Contains("compositeURI") == true)
{
this.defaultCompositeUri = (string) unitTestConfiguration["compositeURI"];
Tracing.TraceInfo("Read compositeURI value: " + this.defaultCompositeUri);
}
if (unitTestConfiguration.Contains("ownCalendarsURI") == true)
{
this.defaultOwnCalendarsUri = (string) unitTestConfiguration["ownCalendarsURI"];
Tracing.TraceInfo("Read ownCalendarsURI value: " + this.defaultOwnCalendarsUri);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void GoogleAuthenticationTest()
{
Tracing.TraceMsg("Entering GoogleAuthenticationTest");
FeedQuery query = new FeedQuery();
Service service = new Service();
int iCount;
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
AtomFeed calFeed = service.Query(query);
ObjectModelHelper.DumpAtomObject(calFeed,CreateDumpFileName("AuthenticationTest"));
iCount = calFeed.Entries.Count;
String strTitle = "Dinner time" + Guid.NewGuid().ToString();
if (calFeed != null && calFeed.Entries.Count > 0)
{
// get the first entry
AtomEntry entry = calFeed.Entries[0];
entry = ObjectModelHelper.CreateAtomEntry(1);
entry.Title.Text = strTitle;
AtomEntry newEntry = calFeed.Insert(entry);
iCount++;
Tracing.TraceMsg("Created calendar entry");
// try to get just that guy.....
FeedQuery singleQuery = new FeedQuery();
singleQuery.Uri = new Uri(newEntry.SelfUri.ToString());
AtomFeed newFeed = service.Query(singleQuery);
AtomEntry sameGuy = newFeed.Entries[0];
Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical");
}
calFeed = service.Query(query);
Assert.AreEqual(iCount, calFeed.Entries.Count, "Feed should have one more entry, it has: " + calFeed.Entries.Count);
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (AtomEntry entry in calFeed.Entries)
{
Tracing.TraceMsg("Entrie title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
entry.Content.Content = "Maybe stay until breakfast";
entry.Update();
Tracing.TraceMsg("Updated entry");
}
}
}
calFeed = service.Query(query);
Assert.AreEqual(iCount, calFeed.Entries.Count, "Feed should have one more entry, it has: " + calFeed.Entries.Count);
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (AtomEntry entry in calFeed.Entries)
{
Tracing.TraceMsg("Entrie title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
entry.Delete();
iCount--;
Tracing.TraceMsg("deleted entry");
}
}
}
calFeed = service.Query(query);
Assert.AreEqual(iCount, calFeed.Entries.Count, "Feed should have the same count again, it has: " + calFeed.Entries.Count);
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test</summary>
//////////////////////////////////////////////////////////////////////
[Ignore ("Currently broken on the server")]
[Test] public void CalendarXHTMLTest()
{
Tracing.TraceMsg("Entering CalendarXHTMLTest");
FeedQuery query = new FeedQuery();
Service service = new Service();
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
AtomFeed calFeed = service.Query(query);
String strTitle = "Dinner time" + Guid.NewGuid().ToString();
if (calFeed != null)
{
// get the first entry
Tracing.TraceMsg("Created calendar entry");
String xhtmlContent = "<div><b>this is an xhtml test text</b></div>";
AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1);
Tracing.TraceMsg("Created calendar entry");
entry.Title.Text = strTitle;
entry.Content.Type = "xhtml";
Tracing.TraceMsg("Created calendar entry");
entry.Content.Content = xhtmlContent;
AtomEntry newEntry = calFeed.Insert(entry);
Tracing.TraceMsg("Created calendar entry");
// try to get just that guy.....
FeedQuery singleQuery = new FeedQuery();
singleQuery.Uri = new Uri(newEntry.SelfUri.ToString());
AtomFeed newFeed = service.Query(singleQuery);
AtomEntry sameGuy = newFeed.Entries[0];
Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical");
Assert.IsTrue(sameGuy.Content.Type.Equals("xhtml"));
Assert.IsTrue(sameGuy.Content.Content.Equals(xhtmlContent));
}
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarExtensionTest()
{
Tracing.TraceMsg("Entering CalendarExtensionTest");
EventQuery query = new EventQuery();
CalendarService service = new CalendarService(this.ApplicationName);
int iCount;
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
if (calFeed.TimeZone != null)
{
Tracing.TraceMsg(calFeed.TimeZone.Value);
}
iCount = calFeed.Entries.Count;
String strTitle = "Dinner & time" + Guid.NewGuid().ToString();
if (calFeed != null)
{
// get the first entry
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = strTitle;
EventEntry newEntry = (EventEntry) calFeed.Insert(entry);
iCount++;
Tracing.TraceMsg("Created calendar entry");
Reminder rNew = null;
Reminder rOld = null;
if (newEntry.Reminders.Count > 0)
{
rNew = newEntry.Reminders[0] as Reminder;
}
if (entry.Reminders.Count > 0)
{
rOld = entry.Reminders[0] as Reminder;
}
Assert.IsTrue(rNew != null, "Reminder should not be NULL);");
Assert.IsTrue(rOld != null, "Original Reminder should not be NULL);");
Assert.AreEqual(rNew.Minutes, rOld.Minutes, "Reminder time should be identical");
Where wOldOne, wOldTwo;
Where wNewOne;
Assert.IsTrue(entry.Locations.Count == 2, "entry should have 2 locations");
// calendar ignores sending more than one location
Assert.IsTrue(newEntry.Locations.Count == 1, "new entry should have 1 location");
if (entry.Locations.Count > 1)
{
wOldOne = entry.Locations[0];
wOldTwo = entry.Locations[1];
if (newEntry.Locations.Count == 1)
{
wNewOne = newEntry.Locations[0];
Assert.IsTrue(wOldOne != null, "Where oldOne should not be NULL);");
Assert.IsTrue(wOldTwo != null, "Where oldTwo should not be NULL);");
Assert.IsTrue(wNewOne != null, "Where newOne should not be NULL);");
Assert.IsTrue(wOldOne.ValueString == wNewOne.ValueString, "location one should be identical");
}
}
newEntry.Content.Content = "Updated..";
newEntry.Update();
// try to get just that guy.....
FeedQuery singleQuery = new FeedQuery();
singleQuery.Uri = new Uri(newEntry.SelfUri.ToString());
EventFeed newFeed = service.Query(query) as EventFeed;
EventEntry sameGuy = newFeed.Entries[0] as EventEntry;
sameGuy.Content.Content = "Updated again...";
When x = sameGuy.Times[0];
sameGuy.Times.Clear();
x.StartTime = DateTime.Now;
sameGuy.Times.Add(x);
sameGuy.Update();
Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical");
}
calFeed = service.Query(query) as EventFeed;
Assert.AreEqual(iCount, calFeed.Entries.Count, "Feed should have one more entry, it has: " + calFeed.Entries.Count);
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (EventEntry entry in calFeed.Entries)
{
Tracing.TraceMsg("Entrie title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
Assert.AreEqual(ObjectModelHelper.DEFAULT_REMINDER_TIME, entry.Reminder.Minutes, "Reminder time should be identical");
entry.Content.Content = "Maybe stay until breakfast";
entry.Update();
Tracing.TraceMsg("Updated entry");
}
}
}
calFeed = service.Query(query) as EventFeed;
Assert.AreEqual(iCount, calFeed.Entries.Count, "Feed should have one more entry, it has: " + calFeed.Entries.Count);
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (AtomEntry entry in calFeed.Entries)
{
Tracing.TraceMsg("Entrie title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
entry.Delete();
iCount--;
Tracing.TraceMsg("deleted entry");
}
}
}
calFeed = service.Query(query) as EventFeed;
Assert.AreEqual(iCount, calFeed.Entries.Count, "Feed should have the same count again, it has: " + calFeed.Entries.Count);
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarQuickAddTest()
{
Tracing.TraceMsg("Entering CalendarQuickAddTest");
EventQuery query = new EventQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
if (calFeed != null)
{
// get the first entry
EventEntry entry = new EventEntry();
entry.Content.Content = "Dinner with Sabine, Oct 1st, 10pm";
entry.Content.Type = "html";
entry.QuickAdd = true;
EventEntry newEntry = (EventEntry) calFeed.Insert(entry);
Assert.IsTrue(newEntry.Title.Text.StartsWith("Dinner with Sabine"), "both titles should be identical" + newEntry.Title.Text);
}
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs a test of batch support on the events feed</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarBatchTest()
{
Tracing.TraceMsg("Entering CalendarBatchTest");
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
EventQuery query = new EventQuery(this.defaultCalendarUri);
EventFeed feed = service.Query(query);
AtomFeed batchFeed = new AtomFeed(feed);
string newEntry1Title = "new event" + Guid.NewGuid().ToString();
EventEntry newEntry1 = new EventEntry(newEntry1Title);
newEntry1.BatchData = new GDataBatchEntryData("1", GDataBatchOperationType.insert);
batchFeed.Entries.Add(newEntry1);
string newEntry2Title = "new event" + Guid.NewGuid().ToString();
EventEntry newEntry2 = new EventEntry(newEntry2Title);
newEntry2.BatchData = new GDataBatchEntryData("2", GDataBatchOperationType.insert);
batchFeed.Entries.Add(newEntry2);
string newEntry3Title = "new event" + Guid.NewGuid().ToString();
EventEntry newEntry3 = new EventEntry(newEntry3Title);
newEntry3.BatchData = new GDataBatchEntryData("3", GDataBatchOperationType.insert);
batchFeed.Entries.Add(newEntry3);
Tracing.TraceMsg("Creating batch items");
EventFeed batchResultFeed = (EventFeed)service.Batch(batchFeed, new Uri(feed.Batch));
foreach (EventEntry evt in batchResultFeed.Entries)
{
Assert.IsNotNull(evt.BatchData, "Result should contain batch information.");
Assert.IsNotNull(evt.BatchData.Id, "Result should have a Batch ID.");
Assert.AreEqual(201, evt.BatchData.Status.Code, "Created entries should return 201");
switch (evt.BatchData.Id)
{
case "1":
Assert.AreEqual(newEntry1Title, evt.Title.Text, "titles should be equal.");
break;
case "2":
Assert.AreEqual(newEntry2Title, evt.Title.Text, "titles should be equal.");
break;
case "3":
Assert.AreEqual(newEntry3Title, evt.Title.Text, "titles should be equal.");
break;
default:
Assert.Fail("Unrecognized entry in result of batch insert feed");
break;
}
}
Tracing.TraceMsg("Updating created entries.");
batchFeed = new AtomFeed(feed);
foreach (EventEntry evt in batchResultFeed.Entries)
{
evt.BatchData = new GDataBatchEntryData(evt.BatchData.Id, GDataBatchOperationType.update);
evt.Title.Text = evt.Title.Text + "update";
batchFeed.Entries.Add(evt);
}
batchResultFeed = (EventFeed) service.Batch(batchFeed, new Uri(feed.Batch));
foreach (EventEntry evt in batchResultFeed.Entries)
{
Assert.IsNotNull(evt.BatchData, "Result should contain batch information.");
Assert.IsNotNull(evt.BatchData.Id, "Result should have a Batch ID.");
Assert.AreEqual(200, evt.BatchData.Status.Code, "Updated entries should return 200");
switch (evt.BatchData.Id)
{
case "1":
Assert.AreEqual(newEntry1Title + "update", evt.Title.Text, "titles should be equal.");
break;
case "2":
Assert.AreEqual(newEntry2Title + "update", evt.Title.Text, "titles should be equal.");
break;
case "3":
Assert.AreEqual(newEntry3Title + "update", evt.Title.Text, "titles should be equal.");
break;
default:
Assert.Fail("Unrecognized entry in result of batch update feed");
break;
}
}
Tracing.TraceMsg("Deleting created entries.");
batchFeed = new AtomFeed(feed);
foreach (EventEntry evt in batchResultFeed.Entries)
{
evt.BatchData = new GDataBatchEntryData(GDataBatchOperationType.delete);
evt.Id = new AtomId(evt.EditUri.ToString());
batchFeed.Entries.Add(evt);
}
batchResultFeed = (EventFeed)service.Batch(batchFeed, new Uri(feed.Batch));
foreach (EventEntry evt in batchResultFeed.Entries)
{
Assert.AreEqual(200, evt.BatchData.Status.Code, "Deleted entries should return 200");
}
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Tests the reminder method property</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarReminderMethodTest()
{
Tracing.TraceMsg("Entering CalendarReminderMethodTest");
EventQuery query = new EventQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
String strTitle = "Dinner & time" + Guid.NewGuid().ToString();
if (calFeed != null)
{
// get the first entry
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = strTitle;
entry.Reminders.Clear();
Reminder r1 = new Reminder();
r1.Method = Reminder.ReminderMethod.email;
r1.Minutes = 30;
Reminder r2 = new Reminder();
r2.Method = Reminder.ReminderMethod.alert;
r2.Minutes = 60;
entry.Reminders.Add(r1);
entry.Reminders.Add(r2);
EventEntry newEntry = (EventEntry) calFeed.Insert(entry);
Assert.AreEqual(2, newEntry.Reminders.Count, "There should be two reminders");
Reminder r3 = newEntry.Reminders[0] as Reminder;
Reminder r4 = newEntry.Reminders[1] as Reminder;
Reminder r1a;
Reminder r2a;
if (r3.Method == Reminder.ReminderMethod.email)
{
r1a = r3;
r2a = r4;
}
else
{
r1a = r4;
r2a = r3;
}
Assert.AreEqual(r1.Minutes, r1a.Minutes, "Reminder time should be identical");
Assert.AreEqual(r1.Method, r1a.Method, "Reminder method should be identical");
Assert.AreEqual(r2.Minutes, r2a.Minutes, "Reminder time should be identical");
Assert.AreEqual(r2.Method, r2a.Method, "Reminder method should be identical");
Tracing.TraceMsg("Created calendar entry");
}
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Tests the ACL extensions</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarACLTest()
{
Tracing.TraceMsg("Entering CalendarACLTest");
AclQuery query = new AclQuery();
CalendarService service = new CalendarService(this.ApplicationName);
int iCount;
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.aclFeedUri);
AclFeed aclFeed = service.Query(query);
AclEntry newEntry = null;
foreach (AclEntry e in aclFeed.Entries )
{
if (e.Scope.Value.StartsWith(this.userName) == false)
{
e.Delete();
}
}
aclFeed = service.Query(query);
iCount = aclFeed.Entries.Count;
if (aclFeed != null)
{
// create an entry
AclEntry entry = new AclEntry();
entry.Role = AclRole.ACL_CALENDAR_FREEBUSY;
AclScope scope = new AclScope();
scope.Type = AclScope.SCOPE_USER;
scope.Value = "meoh2my@test.com";
entry.Scope = scope;
newEntry = (AclEntry) aclFeed.Insert(entry);
Assert.AreEqual(newEntry.Role.Value, entry.Role.Value);
Assert.AreEqual(newEntry.Scope.Type, entry.Scope.Type);
Assert.AreEqual(newEntry.Scope.Value, entry.Scope.Value);
}
Tracing.TraceMsg("CalendarACLTest: done insering Acl:entry");
iCount++;
aclFeed = (AclFeed) service.Query(query);
Tracing.TraceMsg("CalendarACLTest: done query after: Acl:entry");
// update that entry
if (newEntry != null)
{
newEntry.Role = AclRole.ACL_CALENDAR_READ;
newEntry = (AclEntry) newEntry.Update();
Assert.AreEqual(AclRole.ACL_CALENDAR_READ.Value, newEntry.Role.Value);
}
Tracing.TraceMsg("CalendarACLTest: done updating Acl:entry");
newEntry.Delete();
iCount--;
Tracing.TraceMsg("CalendarACLTest: done deleting Acl:entry");
aclFeed = (AclFeed) service.Query(query);
Assert.AreEqual(iCount, aclFeed.Entries.Count, "Feed should have one more entry, it has: " + aclFeed.Entries.Count);
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Tests the ACL extensions, this time getting the feed from the entry</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarACL2Test()
{
Tracing.TraceMsg("Entering CalendarACL2Test");
CalendarQuery query = new CalendarQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultOwnCalendarsUri);
CalendarFeed calFeed = service.Query(query);
if (calFeed != null && calFeed.Entries != null && calFeed.Entries[0] != null)
{
AtomLink link = calFeed.Entries[0].Links.FindService(AclNameTable.LINK_REL_ACCESS_CONTROL_LIST, null);
AclEntry aclEntry = new AclEntry();
aclEntry.Scope = new AclScope();
aclEntry.Scope.Type = AclScope.SCOPE_USER;
aclEntry.Scope.Value = "meoh2my@test.com";
aclEntry.Role = AclRole.ACL_CALENDAR_READ;
Uri aclUri = null;
if (link != null)
{
aclUri = new Uri(link.HRef.ToString());
}
else
{
throw new Exception("ACL link was null.");
}
AclEntry insertedEntry = service.Insert(aclUri, aclEntry);
insertedEntry.Delete();
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an CalendarWebContentTest test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarWebContentTest()
{
Tracing.TraceMsg("Entering CalendarWebContentTest");
EventQuery query = new EventQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
if (calFeed.TimeZone != null)
{
Tracing.TraceMsg(calFeed.TimeZone.Value);
}
String strTitle = "Dinner & time" + Guid.NewGuid().ToString();
if (calFeed != null)
{
// get the first entry
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = strTitle;
WebContentLink wc = new WebContentLink();
wc.Type = "image/gif";
wc.Url = "http://www.google.com/logos/july4th06.gif";
wc.Icon = "http://www.google.com/calendar/images/google-holiday.gif";
wc.Title = "Test content";
wc.Width = 270;
wc.Height = 130;
wc.GadgetPreferences.Add("color", "blue");
wc.GadgetPreferences.Add("taste", "sweet");
wc.GadgetPreferences.Add("smell", "fresh");
entry.WebContentLink = wc;
EventEntry newEntry = (EventEntry) calFeed.Insert(entry);
// check if the web content link came back
Assert.IsTrue(newEntry.WebContentLink != null, "the WebContentLink did not come back for the webContent");
Tracing.TraceMsg("Created calendar entry");
Assert.IsTrue(newEntry.WebContentLink.WebContent != null, "The returned WebContent element was not found");
Assert.AreEqual(3, newEntry.WebContentLink.GadgetPreferences.Count, "The gadget preferences should be there");
Assert.AreEqual("blue", newEntry.WebContentLink.GadgetPreferences["color"], "Color should be blue");
Assert.AreEqual("sweet", newEntry.WebContentLink.GadgetPreferences["taste"], "Taste should be sweet");
Assert.AreEqual("fresh", newEntry.WebContentLink.GadgetPreferences["smell"], "smell should be fresh");
newEntry.Content.Content = "Updated..";
newEntry.Update();
// try to get just that guy.....
FeedQuery singleQuery = new FeedQuery();
singleQuery.Uri = new Uri(newEntry.SelfUri.ToString());
EventFeed newFeed = service.Query(query) as EventFeed;
EventEntry sameGuy = newFeed.Entries[0] as EventEntry;
sameGuy.Content.Content = "Updated again...";
When x = sameGuy.Times[0];
sameGuy.Times.Clear();
x.StartTime = DateTime.Now;
sameGuy.Times.Add(x);
sameGuy.Update();
Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical");
}
calFeed = service.Query(query) as EventFeed;
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (EventEntry entry in calFeed.Entries)
{
Tracing.TraceMsg("Entry title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
Assert.AreEqual(ObjectModelHelper.DEFAULT_REMINDER_TIME, entry.Reminder.Minutes, "Reminder time should be identical");
// check if the link came back
// check if the web content link came back
Assert.IsTrue(entry.WebContentLink != null, "the WebContentLink did not come back for the webContent");
}
}
}
calFeed = service.Query(query) as EventFeed;
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (EventEntry entry in calFeed.Entries)
{
Tracing.TraceMsg("Entry title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
entry.Delete();
Tracing.TraceMsg("deleted entry");
}
}
}
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarRecurranceTest()
{
Tracing.TraceMsg("Entering CalendarRecurranceTest");
EventQuery query = new EventQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
string recur =
"DTSTART;TZID=America/Los_Angeles:20060314T060000\n" +
"DURATION:PT3600S\n" +
"RRULE:FREQ=DAILY;UNTIL=20060321T220000Z\n" +
"BEGIN:VTIMEZONE\n" +
"TZID:America/Los_Angeles\n" +
"X-LIC-LOCATION:America/Los_Angeles\n" +
"BEGIN:STANDARD\n" +
"TZOFFSETFROM:-0700\n" +
"TZOFFSETTO:-0800\n" +
"TZNAME:PST\n" +
"DTSTART:19671029T020000\n" +
"RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\n" +
"END:STANDARD\n" +
"BEGIN:DAYLIGHT\n" +
"TZOFFSETFROM:-0800\n" +
"TZOFFSETTO:-0700\n" +
"TZNAME:PDT\n" +
"DTSTART:19870405T020000\n" +
"RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU\n" +
"END:DAYLIGHT\n" +
"END:VTIMEZONE\n";
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = "New recurring event" + Guid.NewGuid().ToString();
// get rid of the when entry
entry.Times.Clear();
entry.Recurrence = new Recurrence();
entry.Recurrence.Value = recur;
calFeed.Insert(entry);
if (calFeed.TimeZone != null)
{
Tracing.TraceMsg(calFeed.TimeZone.Value);
}
// requery
calFeed = service.Query(query) as EventFeed;
ObjectModelHelper.DumpAtomObject(calFeed,CreateDumpFileName("CalendarRecurrance"));
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for all events that have an original Event pointer, and if so, try to find that one
foreach (EventEntry e in calFeed.Entries)
{
Tracing.TraceMsg("Looping Feed entries, title: " + e.Title.Text);
if (e.OriginalEvent != null)
{
Tracing.TraceMsg("Searching for original Event");
EventEntry original = calFeed.FindEvent(e.OriginalEvent);
Tracing.TraceMsg("Found original Event: " + original.Title.Text);
Assert.IsTrue(original != null, "can not find original event");
}
}
}
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an enter all day event test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarAllDayEvent()
{
Tracing.TraceMsg("Entering CalendarAllDayEvent");
EventQuery query = new EventQuery();
CalendarService service = new CalendarService(this.ApplicationName);
int iCount;
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
iCount = calFeed.Entries.Count;
String strTitle = "Dinner time" + Guid.NewGuid().ToString();
if (calFeed != null)
{
// get the first entry
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = strTitle;
entry.Times[0].AllDay = true;
EventEntry newEntry = (EventEntry) calFeed.Insert(entry);
iCount++;
Tracing.TraceMsg("Created calendar entry");
// try to get just that guy.....
FeedQuery singleQuery = new FeedQuery();
singleQuery.Uri = new Uri(newEntry.SelfUri.ToString());
EventFeed newFeed = service.Query(singleQuery) as EventFeed;
EventEntry sameGuy = newFeed.Entries[0] as EventEntry;
sameGuy.Content.Content = "Updated again...";
sameGuy.Times[0].StartTime = DateTime.Now;
sameGuy.Update();
Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical");
}
calFeed = service.Query(query) as EventFeed;
Assert.AreEqual(iCount, calFeed.Entries.Count, "Feed should have one more entry, it has: " + calFeed.Entries.Count);
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (EventEntry entry in calFeed.Entries)
{
Tracing.TraceMsg("Entrie title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
Assert.IsTrue(entry.Times[0].AllDay, "Entry should be an all day event");
}
}
}
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>test for composite mode</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarCompositeTest()
{
Tracing.TraceMsg("Entering CalendarCompositeTest");
// first run the RecurranceTest to create a recurring event
this.CalendarRecurranceTest();
// now get the feedService
EventQuery query = new EventQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCompositeUri);
EventFeed calFeed = service.Query(query) as EventFeed;
Assert.IsTrue(calFeed!=null, "that's wrong, there should be a feed object" + calFeed);
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Test to check creating/updating/deleting a secondary calendar.
/// </summary>
[Test] public void CalendarOwnCalendarsTest()
{
Tracing.TraceMsg("Enterting CalendarOwnCalendarsTest");
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultOwnCalendarsUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
CalendarEntry newCalendar = new CalendarEntry();
newCalendar.Title.Text = "new calendar" + Guid.NewGuid().ToString();
newCalendar.Summary.Text = "some unique summary" + Guid.NewGuid().ToString();
newCalendar.TimeZone = "America/Los_Angeles";
newCalendar.Hidden = false;
newCalendar.Selected = true;
newCalendar.Color = "#2952A3";
newCalendar.Location = new Where("", "", "Test City");
Uri postUri = new Uri(this.defaultOwnCalendarsUri);
CalendarEntry createdCalendar = (CalendarEntry) service.Insert(postUri, newCalendar);
Assert.IsNotNull(createdCalendar, "created calendar should be returned.");
Assert.AreEqual(newCalendar.Title.Text, createdCalendar.Title.Text, "Titles should be equal");
Assert.AreEqual(newCalendar.Summary.Text, createdCalendar.Summary.Text, "Summaries should be equal");
Assert.AreEqual(newCalendar.TimeZone, createdCalendar.TimeZone, "Timezone should be equal");
Assert.AreEqual(newCalendar.Hidden, createdCalendar.Hidden, "Hidden property should be equal");
Assert.AreEqual(newCalendar.Color, createdCalendar.Color, "Color property should be equal");
Assert.AreEqual(newCalendar.Location.ValueString, createdCalendar.Location.ValueString, "Where should be equal");
createdCalendar.Title.Text = "renamed calendar" + Guid.NewGuid().ToString();
createdCalendar.Hidden = true;
CalendarEntry updatedCalendar = (CalendarEntry) createdCalendar.Update();
Assert.AreEqual(createdCalendar.Title.Text, updatedCalendar.Title.Text, "entry should have been updated");
updatedCalendar.Delete();
CalendarQuery query = new CalendarQuery();
query.Uri = postUri;
CalendarFeed calendarList = service.Query(query);
foreach (CalendarEntry entry in calendarList.Entries)
{
Assert.IsTrue(entry.Title.Text != updatedCalendar.Title.Text, "Calendar should have been removed");
}
service.Credentials = null;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>runs an enter all day event test</summary>
//////////////////////////////////////////////////////////////////////
[Ignore ("Currently broken on the server")]
[Test] public void CalendarCommentTest()
{
Tracing.TraceMsg("Entering CalendarCommentTest");
EventQuery query = new EventQuery();
CalendarService service = new CalendarService(this.ApplicationName);
int iCount;
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
iCount = calFeed.Entries.Count;
String strTitle = "Comment Test" + Guid.NewGuid().ToString();
if (calFeed != null)
{
// insert a new entry
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = strTitle;
entry.Times[0].AllDay = true;
calFeed.Insert(entry);
iCount++;
Tracing.TraceMsg("Created calendar entry");
}
calFeed = service.Query(query) as EventFeed;
Assert.AreEqual(iCount, calFeed.Entries.Count, "Feed should have one more entry, it has: " + calFeed.Entries.Count);
if (calFeed != null && calFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (EventEntry entry in calFeed.Entries)
{
Tracing.TraceMsg("Entrie title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
// get the comment feed
Uri commentFeedUri = new Uri(entry.Comments.FeedLink.Href);
// now we use an AtomFeed to post there
Service feedService = new Service("cl", "UnitTests");
feedService.Credentials = new GDataCredentials(this.userName, this.passWord);
query.Uri = commentFeedUri;
AtomFeed commentFeed = feedService.Query(query);
AtomEntry newEntry = ObjectModelHelper.CreateAtomEntry(1);
Tracing.TraceMsg("trying to insert a comment");
try
{
commentFeed.Insert(newEntry);
} catch (GDataRequestException e )
{
Console.WriteLine(e.ResponseString);
Tracing.TraceMsg(e.ResponseString);
}
}
}
}
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs a stress test against the calendar</summary>
//////////////////////////////////////////////////////////////////////
[Ignore ("Normally not required to run, and takes pretty long")]
[Test] public void CalendarStressTest()
{
Tracing.TraceMsg("Entering CalendarStressTest");
FeedQuery query = new FeedQuery();
Service service = new Service();
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
AtomFeed calFeed = service.Query(query);
if (calFeed != null)
{
for (int i = 0; i<127; i++)
{
AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1);
entry.Title.Text = "Entry number: " + i;
calFeed.Insert(entry);
}
}
calFeed = service.Query(query);
int iCount = 0;
while (calFeed != null && calFeed.Entries.Count > 0)
{
iCount += calFeed.Entries.Count;
// just query the same query again.
if (calFeed.NextChunk != null)
{
query.Uri = new Uri(calFeed.NextChunk);
calFeed = service.Query(query);
}
else
{
calFeed = null;
}
}
Assert.AreEqual(127, iCount, "Feed should have 127 entries, it has: " + iCount);
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>tests the sendNotification property against the calendar</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarNotificationTest()
{
Tracing.TraceMsg("Entering CalendarNotificationTest");
FeedQuery query = new FeedQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
GDataLoggingRequestFactory factory = (GDataLoggingRequestFactory) this.factory;
factory.MethodOverride = true;
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
string guid = Guid.NewGuid().ToString();
if (calFeed != null)
{
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = guid;
entry.Notifications = true;
calFeed.Insert(entry);
}
calFeed = service.Query(query) as EventFeed;
if (calFeed != null && calFeed.Entries.Count > 0)
{
EventEntry entry = calFeed.Entries[0] as EventEntry;
Assert.AreEqual(entry.Title.Text, guid, "Expected the same entry");
// Assert.IsTrue(entry.Notifications, "Expected the sendNotify to be true" + entry.Notifications.ToString());
}
service.Credentials = null;
factory.MethodOverride = false;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>tests the extended property against the calendar</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarExtendedPropertyTest()
{
Tracing.TraceMsg("Entering CalendarExtendedPropertyTest");
FeedQuery query = new FeedQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
string guid = Guid.NewGuid().ToString();
ExtendedProperty prop;
EventEntry entry;
if (calFeed != null)
{
entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = guid;
prop = new ExtendedProperty();
prop.Name = "http://frank.schemas/2005#prop";
prop.Value = "Mantek";
entry.ExtensionElements.Add(prop);
calFeed.Insert(entry);
}
calFeed = service.Query(query) as EventFeed;
prop = null;
entry = null;
if (calFeed != null && calFeed.Entries.Count > 0)
{
entry = calFeed.Entries[0] as EventEntry;
Assert.AreEqual(entry.Title.Text, guid, "Expected the same entry");
foreach (Object o in entry.ExtensionElements )
{
ExtendedProperty p = o as ExtendedProperty;
if (p != null)
{
Tracing.TraceMsg("Found one extended property");
Assert.AreEqual(p.Name, "http://frank.schemas/2005#prop", "Expected the same entry");
Assert.AreEqual(p.Value, "Mantek", "Expected the same entry");
prop = p;
}
}
}
Assert.IsTrue(prop != null, "prop should not be null");
// now delete the prop again
// BUGBUG: currently you can not delete extended properties in the calendar
/*
if (entry != null)
{
entry.ExtensionElements.Remove(prop);
prop = null;
EventEntry newEntry = entry.Update() as EventEntry;
foreach (Object o in newEntry.ExtensionElements )
{
ExtendedProperty p = o as ExtendedProperty;
if (p != null)
{
Tracing.TraceMsg("Found one extended property");
prop = p;
break;
}
}
Assert.IsTrue(prop == null, "prop should be gone now");
}
*/
// get rid of the entry
if (entry != null)
entry.Delete();
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>tests that a default reminder get's created if none is set</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarDefaultReminderTest()
{
Tracing.TraceMsg("Entering CalendarDefaultReminderTest");
FeedQuery query = new FeedQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
GDataLoggingRequestFactory factory = (GDataLoggingRequestFactory) this.factory;
factory.MethodOverride = true;
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = "New event with default reminder" + Guid.NewGuid().ToString();
entry.Reminder = new Reminder();
entry.Reminder.Method = Reminder.ReminderMethod.unspecified;
EventEntry newEntry = calFeed.Insert(entry) as EventEntry;
Reminder reminder = newEntry.Reminder;
Assert.IsTrue(reminder != null, "reminder should not be null - this only works if the calendar HAS default remidners set");
Assert.IsTrue(reminder.Method != Reminder.ReminderMethod.unspecified, "reminder should not be unspecified - this only works if the calendar HAS default remidners set");
service.Credentials = null;
factory.MethodOverride = false;
}
}
/////////////////////////////////////////////////////////////////////////////
///
/// tests the reminder object
///
[Test] public void ReminderTest()
{
String xml = "<reminder xmlns=\"http://schemas.google.com/g/2005\" minutes=\"0\" method=\"email\"/>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode reminderNode = doc.FirstChild;
Reminder f = new Reminder();
Reminder r;
r = f.CreateInstance(reminderNode, new AtomFeedParser()) as Reminder;
Assert.IsTrue(r.Method == Reminder.ReminderMethod.email);
Assert.IsTrue(r.Minutes == 0);
xml = "<reminder xmlns=\"http://schemas.google.com/g/2005\" minutes=\"5\" method=\"sms\"/>";
doc = new XmlDocument();
doc.LoadXml(xml);
reminderNode = doc.FirstChild;
r = new Reminder();
r = f.CreateInstance(reminderNode, new AtomFeedParser()) as Reminder;
Assert.IsTrue(r.Method == Reminder.ReminderMethod.sms);
Assert.IsTrue(r.Minutes == 5);
}
//////////////////////////////////////////////////////////////////////
/// <summary>tests the original event </summary>
//////////////////////////////////////////////////////////////////////
[Test] public void CalendarOriginalEventTest()
{
Tracing.TraceMsg("Entering CalendarOriginalEventTest");
FeedQuery query = new FeedQuery();
CalendarService service = new CalendarService(this.ApplicationName);
if (this.defaultCalendarUri != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
GDataLoggingRequestFactory factory = (GDataLoggingRequestFactory) this.factory;
factory.MethodOverride = true;
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultCalendarUri);
EventFeed calFeed = service.Query(query) as EventFeed;
string recur =
"DTSTART;TZID=America/Los_Angeles:20060314T060000\n" +
"DURATION:PT3600S\n" +
"RRULE:FREQ=DAILY;UNTIL=20060321T220000Z\n" +
"BEGIN:VTIMEZONE\n" +
"TZID:America/Los_Angeles\n" +
"X-LIC-LOCATION:America/Los_Angeles\n" +
"BEGIN:STANDARD\n" +
"TZOFFSETFROM:-0700\n" +
"TZOFFSETTO:-0800\n" +
"TZNAME:PST\n" +
"DTSTART:19671029T020000\n" +
"RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\n" +
"END:STANDARD\n" +
"BEGIN:DAYLIGHT\n" +
"TZOFFSETFROM:-0800\n" +
"TZOFFSETTO:-0700\n" +
"TZNAME:PDT\n" +
"DTSTART:19870405T020000\n" +
"RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU\n" +
"END:DAYLIGHT\n" +
"END:VTIMEZONE\n";
EventEntry entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = "New recurring event" + Guid.NewGuid().ToString();
// get rid of the when entry
entry.Times.Clear();
entry.Recurrence = new Recurrence();
entry.Recurrence.Value = recur;
EventEntry recEntry = calFeed.Insert(entry) as EventEntry;
entry = ObjectModelHelper.CreateEventEntry(1);
entry.Title.Text = "whateverfancy";
OriginalEvent originalEvent = new OriginalEvent();
When start = new When();
start.StartTime = new DateTime(2006, 03, 14, 15, 0,0);
originalEvent.OriginalStartTime = start;
originalEvent.Href = recEntry.SelfUri.ToString();
originalEvent.IdOriginal = recEntry.EventId;
entry.OriginalEvent = originalEvent;
entry.Times.Add(new When(new DateTime(2006, 03, 14, 9,0,0),
new DateTime(2006, 03, 14, 10,0,0)));
calFeed.Insert(entry);
service.Credentials = null;
factory.MethodOverride = false;
}
}
/////////////////////////////////////////////////////////////////////////////
} /////////////////////////////////////////////////////////////////////////////
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MongoDB.Configuration;
using MongoDB.Connections;
using MongoDB.Protocol;
using MongoDB.Results;
using MongoDB.Util;
namespace MongoDB
{
/// <summary>
///
/// </summary>
public class MongoCollection<T> : IMongoCollection<T> where T : class
{
private readonly MongoConfiguration _configuration;
private readonly Connection _connection;
private MongoDatabase _database;
private CollectionMetadata _metadata;
/// <summary>
/// Initializes a new instance of the <see cref="MongoCollection<T>"/> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <param name="connection">The connection.</param>
/// <param name="databaseName">Name of the database.</param>
/// <param name="collectionName">The name.</param>
internal MongoCollection(MongoConfiguration configuration, Connection connection, string databaseName, string collectionName)
{
//Todo: add public constructors for users to call
Name = collectionName;
DatabaseName = databaseName;
_configuration = configuration;
_connection = connection;
}
/// <summary>
/// Gets the database.
/// </summary>
/// <value>The database.</value>
public IMongoDatabase Database {
get { return _database ?? (_database = new MongoDatabase(_configuration, _connection, DatabaseName)); }
}
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; private set; }
/// <summary>
/// Gets or sets the name of the database.
/// </summary>
/// <value>The name of the database.</value>
public string DatabaseName { get; private set; }
/// <summary>
/// Gets the full name including database name.
/// </summary>
/// <value>The full name.</value>
public string FullName {
get { return DatabaseName + "." + Name; }
}
/// <summary>
/// Gets the meta data.
/// </summary>
/// <value>The meta data.</value>
public CollectionMetadata Metadata {
get { return _metadata ?? (_metadata = new CollectionMetadata(_configuration, DatabaseName, Name, _connection)); }
}
/// <summary>
/// Finds and returns the first document in a selector query.
/// </summary>
/// <param name="javascriptWhere">The where.</param>
/// <returns>
/// A <see cref="Document"/> from the collection.
/// </returns>
public T FindOne(string javascriptWhere)
{
var spec = new Document { { "$where", new Code(javascriptWhere) } };
using(var cursor = Find(spec, -1, 0, null))
return cursor.Documents.FirstOrDefault();
}
/// <summary>
/// Finds and returns the first document in a query.
/// </summary>
/// <param name="spec">A <see cref="Document"/> representing the query.</param>
/// <returns>
/// A <see cref="Document"/> from the collection.
/// </returns>
public T FindOne(object spec){
using(var cursor = Find(spec, -1, 0, null))
return cursor.Documents.FirstOrDefault();
}
/// <summary>
/// Finds all.
/// </summary>
/// <returns></returns>
public ICursor<T> FindAll(){
var spec = new Document();
return Find(spec, 0, 0, null);
}
/// <summary>
/// Finds the specified where.
/// </summary>
/// <param name="javascriptWhere">The where.</param>
/// <returns></returns>
public ICursor<T> Find(string javascriptWhere){
var spec = new Document { { "$where", new Code(javascriptWhere) } };
return Find(spec, 0, 0, null);
}
/// <summary>
/// Finds the specified spec.
/// </summary>
/// <param name="spec">The spec.</param>
/// <returns></returns>
public ICursor<T> Find(object spec){
return Find(spec, 0, 0, null);
}
/// <summary>
/// Finds the specified spec.
/// </summary>
/// <param name="spec">The spec.</param>
/// <param name="fields"></param>
/// <returns>A <see cref="ICursor"/></returns>
public ICursor<T> Find(object spec, object fields){
return Find(spec, 0, 0, fields);
}
/// <summary>
/// Finds the specified spec.
/// </summary>
/// <param name="spec">The spec.</param>
/// <param name="limit">The limit.</param>
/// <param name="skip">The skip.</param>
/// <returns></returns>
public ICursor<T> Find(object spec, int limit, int skip){
return Find(spec, limit, skip, null);
}
/// <summary>
/// Finds the specified spec.
/// </summary>
/// <param name="spec">The spec.</param>
/// <param name="limit">The limit.</param>
/// <param name="skip">The skip.</param>
/// <param name="fields">The fields.</param>
/// <returns></returns>
public ICursor<T> Find(object spec, int limit, int skip, object fields){
if (spec == null)
spec = new Document();
return new Cursor<T>(_configuration.SerializationFactory, _configuration.MappingStore, _connection, DatabaseName, Name, spec, limit, skip, fields);
}
/// <summary>
/// Executes a query and atomically applies a modifier operation to the first document returning the original document
/// by default.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="spec"><see cref="Document"/> to find the document.</param>
/// <returns>A <see cref="Document"/></returns>
public T FindAndModify(object document, object spec){
return FindAndModify(document, spec, false);
}
/// <summary>
/// Executes a query and atomically applies a modifier operation to the first document returning the original document
/// by default.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="spec"><see cref="Document"/> to find the document.</param>
/// <param name="sort"><see cref="Document"/> containing the names of columns to sort on with the values being the</param>
/// <returns>A <see cref="Document"/></returns>
/// <see cref="IndexOrder"/>
public T FindAndModify(object document, object spec, object sort)
{
return FindAndModify(document, spec, sort, null, false, false, false);
}
/// <summary>
/// Executes a query and atomically applies a modifier operation to the first document returning the original document
/// by default.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="spec"><see cref="Document"/> to find the document.</param>
/// <param name="returnNew">if set to <c>true</c> [return new].</param>
/// <returns>A <see cref="Document"/></returns>
public T FindAndModify(object document, object spec, bool returnNew)
{
return FindAndModify(document, spec, null, null, false, returnNew, false);
}
/// <summary>
/// Executes a query and atomically applies a modifier operation to the first document returning the original document
/// by default.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="spec"><see cref="Document"/> to find the document.</param>
/// <param name="sort"><see cref="Document"/> containing the names of columns to sort on with the values being the
/// <see cref="IndexOrder"/></param>
/// <param name="returnNew">if set to <c>true</c> [return new].</param>
/// <returns>A <see cref="Document"/></returns>
public T FindAndModify(object document, object spec, object sort, bool returnNew)
{
return FindAndModify(document, spec, sort, null, false, returnNew, false);
}
/// <summary>
/// Executes a query and atomically applies a modifier operation to the first document returning the original document
/// by default.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="spec"><see cref="Document"/> to find the document.</param>
/// <param name="sort"><see cref="Document"/> containing the names of columns to sort on with the values being the
/// <see cref="IndexOrder"/></param>
/// <param name="fields">The fields.</param>
/// <param name="remove">if set to <c>true</c> [remove].</param>
/// <param name="returnNew">if set to <c>true</c> [return new].</param>
/// <param name="upsert">if set to <c>true</c> [upsert].</param>
/// <returns>A <see cref="Document"/></returns>
public T FindAndModify(object document, object spec, object sort, object fields, bool remove, bool returnNew, bool upsert)
{
var command = new Document
{
{"findandmodify", Name},
{"query", spec},
{"update", EnsureUpdateDocument(document)},
{"new", returnNew},
{"remove", remove},
{"upsert", upsert}
};
if(sort != null)
command.Add("sort", sort);
if(fields != null)
command.Add("fields", fields);
var response = _connection.SendCommand<FindAndModifyResult<T>>(_configuration.SerializationFactory,
DatabaseName,
typeof(T),
command,
false);
return response.Value;
}
/// <summary>
/// Entrypoint into executing a map/reduce query against the collection.
/// </summary>
/// <returns>A <see cref="MapReduce"/></returns>
public MapReduce MapReduce(){
return new MapReduce(Database, Name, typeof(T));
}
///<summary>
/// Count all items in the collection.
///</summary>
public long Count(){
return Count(new Document());
}
/// <summary>
/// Count all items in a collection that match the query spec.
/// </summary>
/// <param name="spec">The spec.</param>
/// <returns></returns>
/// <remarks>
/// It will return 0 if the collection doesn't exist yet.
/// </remarks>
public long Count(object spec){
try {
var response = Database.SendCommand(typeof(T),new Document().Add("count", Name).Add("query", spec));
return Convert.ToInt64((double)response["n"]);
} catch (MongoCommandException) {
//FIXME This is an exception condition when the namespace is missing.
//-1 might be better here but the console returns 0.
return 0;
}
}
/// <summary>
/// Inserts the Document into the collection.
/// </summary>
public void Insert(object document, bool safemode){
Insert(document);
CheckError(safemode);
}
/// <summary>
/// Inserts the specified doc.
/// </summary>
/// <param name="document">The doc.</param>
public void Insert(object document){
Insert(new[] { document });
}
/// <summary>
/// Inserts all.
/// </summary>
/// <typeparam name="TElement">The type of the element.</typeparam>
/// <param name="documents">The documents.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
public void Insert<TElement>(IEnumerable<TElement> documents, bool safemode){
if (safemode)
Database.ResetError();
Insert(documents);
CheckPreviousError(safemode);
}
/// <summary>
/// Inserts the specified documents.
/// </summary>
/// <param name="documents">The documents.</param>
public void Insert<TElement>(IEnumerable<TElement> documents){
if(documents is Document)
{
Insert(new[]{(Document)documents});
return;
}
var rootType = typeof(T);
var writerSettings = _configuration.SerializationFactory.GetBsonWriterSettings(rootType);
var insertMessage = new InsertMessage(writerSettings)
{
FullCollectionName = FullName
};
var descriptor = _configuration.SerializationFactory.GetObjectDescriptor(rootType);
var insertDocument = new List<object>();
foreach (var document in documents) {
var id = descriptor.GetPropertyValue(document, "_id");
if (id == null)
descriptor.SetPropertyValue(document, "_id", descriptor.GenerateId(document));
insertDocument.Add(document);
}
insertMessage.Documents = insertDocument.ToArray();
try {
_connection.SendMessage(insertMessage,DatabaseName);
} catch (IOException exception) {
throw new MongoConnectionException("Could not insert document, communication failure", _connection, exception);
}
}
/// <summary>
/// Deletes documents from the collection according to the spec.
/// </summary>
/// <param name="selector">The selector.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
/// <remarks>
/// An empty document will match all documents in the collection and effectively truncate it.
/// </remarks>
[Obsolete("Use Remove instead")]
public void Delete(object selector, bool safemode)
{
Delete(selector);
CheckError(safemode);
}
/// <summary>
/// Remove documents from the collection according to the selector.
/// </summary>
/// <param name="selector">The selector.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
/// <remarks>
/// An empty document will match all documents in the collection and effectively truncate it.
/// See the safemode description in the class description
/// </remarks>
public void Remove(object selector, bool safemode){
Remove(selector);
CheckError(safemode);
}
/// <summary>
/// Deletes documents from the collection according to the spec.
/// </summary>
/// <param name="selector">The selector.</param>
/// <remarks>
/// An empty document will match all documents in the collection and effectively truncate it.
/// </remarks>
[Obsolete("Use Remove instead")]
public void Delete(object selector){
var writerSettings = _configuration.SerializationFactory.GetBsonWriterSettings(typeof(T));
try {
_connection.SendMessage(new DeleteMessage(writerSettings)
{
FullCollectionName = FullName,
Selector = selector
},DatabaseName);
} catch (IOException exception) {
throw new MongoConnectionException("Could not delete document, communication failure", _connection, exception);
}
}
/// <summary>
/// Remove documents from the collection according to the selector.
/// </summary>
/// <param name="selector">The selector.</param>
/// <remarks>
/// An empty document will match all documents in the collection and effectively truncate it.
/// </remarks>
public void Remove(object selector){
var writerSettings = _configuration.SerializationFactory.GetBsonWriterSettings(typeof(T));
try
{
_connection.SendMessage(new DeleteMessage(writerSettings)
{
FullCollectionName = FullName,
Selector = selector
}, DatabaseName);
}
catch(IOException exception)
{
throw new MongoConnectionException("Could not delete document, communication failure", _connection, exception);
}
}
/// <summary>
/// Updates the specified document.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
[Obsolete("Use Save instead")]
public void Update(object document, bool safemode)
{
Save(document, safemode);
}
/// <summary>
/// Updates a document with the data in doc as found by the selector.
/// </summary>
/// <param name="document">The document.</param>
/// <remarks>
/// _id will be used in the document to create a selector. If it isn't in
/// the document then it is assumed that the document is new and an upsert is sent to the database
/// instead.
/// </remarks>
[Obsolete("Use Save(Document)")]
public void Update(object document){
Save(document);
}
/// <summary>
/// Updates the specified document.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
public void Update(object document, object selector, bool safemode){
Update(document, selector, 0, safemode);
}
/// <summary>
/// Updates a document with the data in doc as found by the selector.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
public void Update(object document, object selector){
Update(document, selector, 0);
}
/// <summary>
/// Updates the specified document.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
/// <param name="flags">The flags.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
public void Update(object document, object selector, UpdateFlags flags, bool safemode){
Update(document, selector, flags);
CheckError(safemode);
}
/// <summary>
/// Updates a document with the data in doc as found by the selector.
/// </summary>
/// <param name="document">The <see cref="Document"/> to update with</param>
/// <param name="selector">The query spec to find the document to update.</param>
/// <param name="flags"><see cref="UpdateFlags"/></param>
public void Update(object document, object selector, UpdateFlags flags){
var writerSettings = _configuration.SerializationFactory.GetBsonWriterSettings(typeof(T));
try {
_connection.SendMessage(new UpdateMessage(writerSettings)
{
FullCollectionName = FullName,
Selector = selector,
Document = document,
Flags = (int)flags
}, DatabaseName);
} catch (IOException exception) {
throw new MongoConnectionException("Could not update document, communication failure", _connection, exception);
}
}
/// <summary>
/// Runs a multiple update query against the database. It will wrap any
/// doc with $set if the passed in doc doesn't contain any '$' ops.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
public void UpdateAll(object document, object selector){
Update(EnsureUpdateDocument(document), selector, UpdateFlags.MultiUpdate);
}
/// <summary>
/// Updates all.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
public void UpdateAll(object document, object selector, bool safemode){
if (safemode)
Database.ResetError();
UpdateAll(document, selector);
CheckPreviousError(safemode);
}
/// <summary>
/// Saves a document to the database using an upsert.
/// </summary>
/// <param name="document">The document.</param>
/// <remarks>
/// The document will contain the _id that is saved to the database. This is really just an alias
/// to Update(Document) to maintain consistency between drivers.
/// </remarks>
public void Save(object document){
//Try to generate a selector using _id for an existing document.
//otherwise just set the upsert flag to 1 to insert and send onward.
var descriptor = _configuration.SerializationFactory.GetObjectDescriptor(typeof(T));
var value = descriptor.GetPropertyValue(document, "_id");
if(value == null)
{
//Likely a new document
descriptor.SetPropertyValue(document, "_id", descriptor.GenerateId(value));
Insert(document);
}
else
Update(document, new Document("_id", value), UpdateFlags.Upsert);
}
/// <summary>
/// Saves a document to the database using an upsert.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
/// <remarks>
/// The document will contain the _id that is saved to the database. This is really just an alias
/// to Update(Document) to maintain consistency between drivers.
/// </remarks>
public void Save(object document, bool safemode)
{
Save(document);
CheckError(safemode);
}
/// <summary>
/// Checks the error.
/// </summary>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
private void CheckError(bool safemode){
if (!safemode)
return;
var lastError = Database.GetLastError();
if (ErrorTranslator.IsError(lastError))
throw ErrorTranslator.Translate(lastError);
}
/// <summary>
/// Checks the previous error.
/// </summary>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
private void CheckPreviousError(bool safemode){
if (!safemode)
return;
var previousError = Database.GetPreviousError();
if (ErrorTranslator.IsError(previousError))
throw ErrorTranslator.Translate(previousError);
}
/// <summary>
/// Ensures the update document.
/// </summary>
/// <param name="document">The document.</param>
/// <returns></returns>
private object EnsureUpdateDocument(object document)
{
var descriptor = _configuration.SerializationFactory.GetObjectDescriptor(typeof(T));
var foundOp = document is Document && ( (Document)document ).Keys.Any(k => k.Contains("$"));
if(foundOp == false)
foundOp = descriptor.GetMongoPropertyNames(document)
.Any(name => name.Contains('$'));
return foundOp == false ? new Document().Add("$set", document) : document;
}
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using ResolutionBuddy;
using System;
//using BloomBuddy;
namespace SpriteEffects
{
/// <summary>
/// Sample demonstrating how pixel shaders can be used to apply special effects to sprite rendering.
/// </summary>
public class Game1 : Game
{
#region Fields
GraphicsDeviceManager graphics;
/// <summary>
/// Shader to draw the texture with the supplied color.
/// </summary>
private Effect passThrough;
/// <summary>
/// Shader to draw the texture with inverted color.
/// </summary>
private Effect inverseColor;
/// <summary>
/// Shader to draw the light map, using the supplied normal map and light direction.
/// </summary>
private Effect lightmap;
/// <summary>
/// Shader to draw the texture, light correctly using the supplied normal map
/// </summary>
private Effect normalmapEffect;
/// <summary>
/// Shader to draw the texture, light correctly using the supplied normal map
/// </summary>
//private Effect rotatedNormalEffect;
private Effect maskNormalEffect;
// Textures used by this sample.
Texture2D cubeTexture;
Texture2D cubeNormalmapTexture;
private Texture2D cubeMask;
Texture2D catTexture;
Texture2D catNormalmapTexture;
Texture2D blank;
// SpriteBatch instance used to render all the effects.
SpriteBatch spriteBatch;
//BloomComponent bloom;
#endregion
#region Initialization
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
#if __IOS__
var resolution = new ResolutionComponent(this, graphics, new Point(1280, 720), new Point(1280, 720), true, true);
#else
var resolution = new ResolutionComponent(this, graphics, new Point(1280, 720), new Point(1280, 720), false, false);
#endif
//bloom = new BloomComponent(this);
//bloom.Settings = BloomSettings.PresetSettings[0];
//Components.Add(bloom);
}
/// <summary>
/// Loads graphics content.
/// </summary>
protected override void LoadContent()
{
passThrough = Content.Load<Effect>("PassThrough");
inverseColor = Content.Load<Effect>("InverseColor");
lightmap = Content.Load<Effect>("LightMap");
normalmapEffect = Content.Load<Effect>("normalmap");
maskNormalEffect = Content.Load<Effect>("AnimationBuddyShader");
catTexture = Content.Load<Texture2D>("cat");
catNormalmapTexture = Content.Load<Texture2D>("CatNormalMap");
cubeTexture = Content.Load<Texture2D>("cube");
cubeNormalmapTexture = Content.Load<Texture2D>("CubeNormalMap");
cubeMask = Content.Load<Texture2D>("cube_mask");
blank = Content.Load<Texture2D>("blank");
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the game to run logic.
/// </summary>
protected override void Update(GameTime gameTime)
{
if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) ||
Keyboard.GetState().IsKeyDown(Keys.Escape))
{
#if !__IOS__
Exit();
#endif
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
protected override void Draw(GameTime gameTime)
{
//bloom.BeginDraw();
//This is the light direction to use to light any norma. maps.
Vector2 dir = MoveInCircle(gameTime, 1.0f);
Vector3 lightDirection = new Vector3(1f, 0f, .2f);
lightDirection.Normalize();
var rotation = (float)gameTime.TotalGameTime.TotalSeconds * .25f;
//Clear the device to XNA blue.
GraphicsDevice.Clear(Color.CornflowerBlue);
//Set the light directions.
normalmapEffect.Parameters["LightDirection"].SetValue(lightDirection);
normalmapEffect.Parameters["NormalTexture"].SetValue(catNormalmapTexture);
normalmapEffect.Parameters["AmbientColor"].SetValue(new Vector3(.45f, .45f, .45f));
normalmapEffect.Parameters["LightColor"].SetValue(new Vector3(1f, 1f, 1f));
maskNormalEffect.Parameters["LightDirection"].SetValue(lightDirection);
maskNormalEffect.Parameters["NormalTexture"].SetValue(catNormalmapTexture);
maskNormalEffect.Parameters["HasNormal"].SetValue(true);
maskNormalEffect.Parameters["AmbientColor"].SetValue(new Vector3(.45f, .45f, .45f));
maskNormalEffect.Parameters["LightColor"].SetValue(new Vector3(1f, 1f, 1f));
maskNormalEffect.Parameters["Rotation"].SetValue(rotation);
maskNormalEffect.Parameters["ColorMaskTexture"].SetValue(cubeMask);
maskNormalEffect.Parameters["HasColorMask"].SetValue(false);
maskNormalEffect.Parameters["ColorMask"].SetValue(new Vector4(1f, 1f, 1f, 1f));
maskNormalEffect.Parameters["FlipHorizontal"].SetValue(false);
lightmap.Parameters["LightDirection"].SetValue(lightDirection);
lightmap.Parameters["NormalTexture"].SetValue(catNormalmapTexture);
// Set the normalmap texture.
Vector2 pos = Vector2.Zero;
//Draw the plain texture, first in white and then with red tint.
pos = Vector2.Zero;
DrawPassthrough(pos);
//Draw the light map, first in white and then with red tint.
pos = Vector2.Zero;
DrawLightmap(pos);
var catMid = new Vector2(catTexture.Width * 0.5f, catTexture.Height * 0.5f);
//Draw the lit texture.
maskNormalEffect.Parameters["FlipHorizontal"].SetValue(true);
pos = Vector2.Zero;
pos.X += catTexture.Width * 2f;
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, maskNormalEffect, Resolution.TransformationMatrix());
spriteBatch.Draw(catTexture,
pos + catMid,
null,
Color.White,
rotation,
catMid,
Vector2.One,
Microsoft.Xna.Framework.Graphics.SpriteEffects.FlipHorizontally,
1f);
pos.Y += catTexture.Height;
rotation = -rotation;
maskNormalEffect.Parameters["Rotation"].SetValue(rotation);
maskNormalEffect.Parameters["NormalTexture"].SetValue(cubeNormalmapTexture);
maskNormalEffect.Parameters["HasColorMask"].SetValue(true);
maskNormalEffect.Parameters["FlipHorizontal"].SetValue(false);
spriteBatch.Draw(cubeTexture,
pos + catMid,
null,
Color.Green,
rotation,
catMid,
Vector2.One,
Microsoft.Xna.Framework.Graphics.SpriteEffects.None,
1f);
spriteBatch.End();
base.Draw(gameTime);
}
private void DrawLightmap(Vector2 pos)
{
pos.X += cubeTexture.Width;
spriteBatch.Begin(0, null, null, null, null, lightmap, Resolution.TransformationMatrix());
spriteBatch.Draw(blank, pos, Color.White);
pos.Y += cubeTexture.Height;
spriteBatch.Draw(blank, pos, Color.Red);
spriteBatch.End();
}
private void DrawPassthrough(Vector2 pos)
{
spriteBatch.Begin(0, null, null, null, null, passThrough, Resolution.TransformationMatrix());
spriteBatch.Draw(catTexture, pos, Color.White);
pos.Y += catTexture.Height;
spriteBatch.Draw(catTexture, pos, Color.Red);
spriteBatch.End();
}
/// <summary>
/// Helper for moving a value around in a circle.
/// </summary>
static Vector2 MoveInCircle(GameTime gameTime, float speed)
{
double time = gameTime.TotalGameTime.TotalSeconds * speed;
float x = (float)Math.Cos(time);
float y = (float)Math.Sin(time);
return new Vector2(x, y);
}
#endregion
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using CoreAnimation;
using CoreGraphics;
using Foundation;
using UIKit;
// Do not remove this notice
// Copyright (c)2016-2018 Vapolia. All rights reserved.
namespace Vapolia.Ios.Lib
{
/// <summary>
/// An UIButton which can have an alternate background color when pressed, or when disabled.
/// When autolayout is used, this button correctly computes the intrisic dimensions by adding titleinsets.
/// </summary>
[Register("UIButtonEx")]
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class UIButtonEx : UIButton
{
public UIColor BackgroundColorHighlighted { get; set; }
public UIColor BackgroundColorDisabled { get; set; }
public UIColor BackgroundColorSelected { get; set; }
private UIColor originalBackgroundColor = UIColor.Clear;
/// <summary>
/// If set, this is the value returned by IntrinsicContentSize
/// </summary>
[Export(nameof(ForcedHeight))]
public nfloat ForcedHeight { get; set; }
public nfloat? ForcedWidth { get; set; }
/// <summary>
/// If true, when hidden/shown the space used by the label is freed so the constraints can be recomputed.
/// </summary>
public bool ZeroSizeWhenHidden { get => zeroSizeWhenHidden; set { zeroSizeWhenHidden = value; InvalidateIntrinsicContentSize(); } }
private bool zeroSizeWhenHidden;
public override UIColor BackgroundColor
{
get => originalBackgroundColor;
set
{
originalBackgroundColor = value;
SetBackgroundColor();
}
}
public UIButtonEx()
{
}
public UIButtonEx(IntPtr handle) : base(handle)
{
}
private void SetBackgroundColor([CallerMemberName]string caller = null)
{
var color =
(Highlighted && BackgroundColorHighlighted != null ? BackgroundColorHighlighted :
(!Enabled && BackgroundColorDisabled!=null) ? BackgroundColorDisabled :
(Selected && BackgroundColorSelected!=null ? BackgroundColorSelected :
originalBackgroundColor));
//Vap.Trace($"SetBackgroundColor {color} Highlighted:{Highlighted} Enabled:{Enabled} caller:{caller}");
base.BackgroundColor = color;
base.Layer.BackgroundColor = color?.CGColor; //For alpha without ButtonType.Custom
}
public override bool Selected
{
get => base.Selected;
set
{
base.Selected = value;
SetBackgroundColor();
}
}
public override bool Highlighted
{
get => base.Highlighted;
set
{
base.Highlighted = value;
SetBackgroundColor();
}
}
public override bool Enabled
{
get => base.Enabled;
set
{
base.Enabled = value;
SetBackgroundColor();
}
}
public override bool Hidden
{
get => base.Hidden;
set
{
base.Hidden = value;
if (zeroSizeWhenHidden)
{
if (Superview != null)
{
Animate(.3, () =>
{
InvalidateIntrinsicContentSize();
Superview.LayoutIfNeeded();
});
}
else
InvalidateIntrinsicContentSize();
}
}
}
private CALayer topBorder, bottomBorder, rightImage;
public void AddTopBottomBorders(UIColor color)
{
if (topBorder != null)
{
topBorder.RemoveFromSuperLayer();
topBorder = null;
}
if (bottomBorder != null)
{
bottomBorder.RemoveFromSuperLayer();
bottomBorder = null;
}
topBorder = new CALayer
{
BackgroundColor = color.CGColor,
Frame = new CGRect(0, 0, Bounds.Width, lineWidth)
};
Layer.AddSublayer(topBorder);
bottomBorder = new CALayer
{
BackgroundColor = color.CGColor,
Frame = new CGRect(0, Bounds.Height-1f, Bounds.Width, lineWidth)
};
Layer.AddSublayer(bottomBorder);
}
private static readonly nfloat rightImageMargin = 12;
private static readonly nfloat lineWidth = 1/UIScreen.MainScreen.Scale;
public void AddRightImage(UIImage image)
{
//TODO: modify the title rect
if (rightImage != null)
{
rightImage.RemoveFromSuperLayer();
rightImage = null;
}
rightImage = new CALayer
{
Frame = Bounds.Inset(lineWidth+rightImageMargin,lineWidth),
ContentsGravity = CALayer.GravityRight,
Contents = image.CGImage,
ContentsScale = UIScreen.MainScreen.Scale,
RasterizationScale = UIScreen.MainScreen.Scale,
AllowsEdgeAntialiasing = true,
ShouldRasterize = true
};
Layer.AddSublayer(rightImage);
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (topBorder != null)
topBorder.Frame = new CGRect(0, 0, Bounds.Width, lineWidth);
if (bottomBorder != null)
bottomBorder.Frame = new CGRect(0, Bounds.Height - lineWidth, Bounds.Width, lineWidth);
if (rightImage != null)
rightImage.Frame = new CGRect(0,topBorder != null ? lineWidth : 0, Bounds.Width - rightImageMargin, Bounds.Height-((topBorder!=null ? lineWidth : 0)+(bottomBorder!=null ? lineWidth : 0)));
}
/// <summary>
/// Add TitleEdgeInsets to intrisic content for autolayout
/// </summary>
public override CGSize IntrinsicContentSize
{
get
{
if (zeroSizeWhenHidden && base.Hidden)
return CGSize.Empty;
var s = base.IntrinsicContentSize;
var size = new CGSize(
ForcedWidth ?? s.Width+TitleEdgeInsets.Left+TitleEdgeInsets.Right+ContentEdgeInsets.Left+ContentEdgeInsets.Right,
ForcedHeight != 0 ? ForcedHeight : s.Height+TitleEdgeInsets.Top+TitleEdgeInsets.Bottom+ContentEdgeInsets.Top+ContentEdgeInsets.Bottom);
return size;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading;
using Xunit;
namespace System.Diagnostics.ProcessTests
{
public class ProcessTests : ProcessTestBase
{
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
switch (global::Interop.PlatformDetection.OperatingSystem)
{
case global::Interop.OperatingSystem.Windows:
Assert.NotEqual(0, value);
break;
default:
Assert.Equal(0, value);
break;
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestBasePriorityOnWindows()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestBasePriorityOnUnix()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Fact]
public void TestEnableRaiseEvents()
{
{
bool isExitedInvoked = false;
// Test behavior when EnableRaisingEvent = true;
// Ensure event is called.
Process p = CreateProcessInfinite();
p.EnableRaisingEvents = true;
p.Exited += delegate { isExitedInvoked = true; };
StartAndKillProcessWithDelay(p);
Assert.True(isExitedInvoked, String.Format("TestCanRaiseEvents0001: {0}", "isExited Event not called when EnableRaisingEvent is set to true."));
}
{
bool isExitedInvoked = false;
// Check with the default settings (false, events will not be raised)
Process p = CreateProcessInfinite();
p.Exited += delegate { isExitedInvoked = true; };
StartAndKillProcessWithDelay(p);
Assert.False(isExitedInvoked, String.Format("TestCanRaiseEvents0002: {0}", "isExited Event called with the default settings for EnableRaiseEvents"));
}
{
bool isExitedInvoked = false;
// Same test, this time explicitly set the property to false
Process p = CreateProcessInfinite();
p.EnableRaisingEvents = false;
p.Exited += delegate { isExitedInvoked = true; }; ;
StartAndKillProcessWithDelay(p);
Assert.False(isExitedInvoked, String.Format("TestCanRaiseEvents0003: {0}", "isExited Event called with the EnableRaiseEvents = false"));
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessInfinite();
StartAndKillProcessWithDelay(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
DateTime timeBeforeProcessStart = DateTime.UtcNow;
Process p = CreateProcessInfinite();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.ExitTime.ToUniversalTime() > timeBeforeProcessStart, "TestExitTime is incorrect.");
}
[Fact]
public void TestId()
{
if (global::Interop.IsWindows)
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(CoreRunName).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessInfinite();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void TestMachineName()
{
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact, PlatformSpecific(~PlatformID.OSX)]
public void TestMainModuleOnNonOSX()
{
string fileName = "corerun";
if (global::Interop.IsWindows)
fileName = "CoreRun.exe";
Process p = Process.GetCurrentProcess();
Assert.True(p.Modules.Count > 0);
Assert.Equal(fileName, p.MainModule.ModuleName);
Assert.EndsWith(fileName, p.MainModule.FileName);
Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString());
}
[Fact]
public void TestMaxWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (global::Interop.IsOSX)
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (global::Interop.IsWindows)
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestMinWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (global::Interop.IsOSX)
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (global::Interop.IsWindows)
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestModules()
{
foreach (ProcessModule pModule in _process.Modules)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotEqual(IntPtr.Zero, pModule.BaseAddress);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr addr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
public void TestNonpagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void TestPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void TestPagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void TestPeakPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void TestPeakVirtualMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void TestPeakWorkingSet64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void TestPrivateMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void TestVirtualMemorySize64()
{
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void TestWorkingSet64()
{
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void TestProcessorTime()
{
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact]
public void TestProcessStartTime()
{
DateTime timeBeforeCreatingProcess = DateTime.UtcNow;
Process p = CreateProcessInfinite();
Assert.Throws<InvalidOperationException>(() => p.StartTime);
try
{
p.Start();
// Time in unix, is measured in jiffies, which is incremented by one for every timer interrupt since the boot time.
// Thus, because there are HZ timer interrupts in a second, there are HZ jiffies in a second. Hence 1\HZ, will
// be the resolution of system timer. The lowest value of HZ on unix is 100, hence the timer resolution is 10 ms.
// Allowing for error in 10 ms.
long tenMSTicks = new TimeSpan(0, 0, 0, 0, 10).Ticks;
long beforeTicks = timeBeforeCreatingProcess.Ticks - tenMSTicks;
try
{
// Ensure the process has started, p.id throws InvalidOperationException, if the process has not yet started.
Assert.Equal(p.Id, Process.GetProcessById(p.Id).Id);
long afterTicks = DateTime.UtcNow.Ticks + tenMSTicks;
Assert.InRange(p.StartTime.ToUniversalTime().Ticks, beforeTicks, afterTicks);
}
catch (InvalidOperationException)
{
Assert.True(p.StartTime.ToUniversalTime().Ticks > beforeTicks);
}
}
finally
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
[Fact]
[PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestPriorityClassUnix()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestPriorityClassWindows()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact]
public void TestInvalidPriorityClass()
{
Process p = new Process();
Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; });
}
[Fact]
public void TestProcessName()
{
Assert.Equal(_process.ProcessName, CoreRunName, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void TestSafeHandle()
{
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void TestSessionId()
{
uint sessionId;
if (global::Interop.IsWindows)
{
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
}
else
{
sessionId = (uint)Interop.getsid(_process.Id);
}
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId = global::Interop.IsWindows ?
Interop.GetCurrentProcessId() :
Interop.getpid();
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
public void TestGetProcessById()
{
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void TestGetProcessesByName()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "TestGetProcessesByName001 failed");
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "TestGetProcessesByName001 failed");
}
public static IEnumerable<object[]> GetTestProcess()
{
Process currentProcess = Process.GetCurrentProcess();
yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") };
yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() };
}
[Theory, PlatformSpecific(PlatformID.Windows)]
[MemberData("GetTestProcess")]
public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess)
{
Assert.Equal(currentProcess.Id, remoteProcess.Id);
Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
[Fact, PlatformSpecific(PlatformID.AnyUnix)]
public void TestProcessOnRemoteMachineUnix()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1"));
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1"));
}
[Fact]
public void TestStartInfo()
{
{
Process process = CreateProcessInfinite();
process.Start();
Assert.Equal(CoreRunName, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = CreateProcessInfinite();
process.Start();
Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo()));
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = new Process();
process.StartInfo = new ProcessStartInfo(TestExeName);
Assert.Equal(TestExeName, process.StartInfo.FileName);
}
{
Process process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
{
Process process = Process.GetCurrentProcess();
Assert.Throws<System.InvalidOperationException>(() => process.StartInfo);
}
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests.Cache.Query.Continuous
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cache.Event;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for continuous query.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
public abstract class ContinuousQueryAbstractTest
{
/** Cache name: ATOMIC, backup. */
protected const string CACHE_ATOMIC_BACKUP = "atomic_backup";
/** Cache name: ATOMIC, no backup. */
protected const string CACHE_ATOMIC_NO_BACKUP = "atomic_no_backup";
/** Cache name: TRANSACTIONAL, backup. */
protected const string CACHE_TX_BACKUP = "transactional_backup";
/** Cache name: TRANSACTIONAL, no backup. */
protected const string CACHE_TX_NO_BACKUP = "transactional_no_backup";
/** Listener events. */
public static BlockingCollection<CallbackEvent> CB_EVTS = new BlockingCollection<CallbackEvent>();
/** Listener events. */
public static BlockingCollection<FilterEvent> FILTER_EVTS = new BlockingCollection<FilterEvent>();
/** First node. */
private IIgnite grid1;
/** Second node. */
private IIgnite grid2;
/** Cache on the first node. */
private ICache<int, BinarizableEntry> cache1;
/** Cache on the second node. */
private ICache<int, BinarizableEntry> cache2;
/** Cache name. */
private readonly string cacheName;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cacheName">Cache name.</param>
protected ContinuousQueryAbstractTest(string cacheName)
{
this.cacheName = cacheName;
}
/// <summary>
/// Set-up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(BinarizableEntry)),
new BinaryTypeConfiguration(typeof(BinarizableFilter)),
new BinaryTypeConfiguration(typeof(KeepBinaryFilter))
}
},
SpringConfigUrl = "config\\cache-query-continuous.xml",
IgniteInstanceName = "grid-1"
};
grid1 = Ignition.Start(cfg);
cache1 = grid1.GetCache<int, BinarizableEntry>(cacheName);
cfg.IgniteInstanceName = "grid-2";
grid2 = Ignition.Start(cfg);
cache2 = grid2.GetCache<int, BinarizableEntry>(cacheName);
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Before-test routine.
/// </summary>
[SetUp]
public void BeforeTest()
{
CB_EVTS = new BlockingCollection<CallbackEvent>();
FILTER_EVTS = new BlockingCollection<FilterEvent>();
AbstractFilter<BinarizableEntry>.res = true;
AbstractFilter<BinarizableEntry>.err = false;
AbstractFilter<BinarizableEntry>.marshErr = false;
AbstractFilter<BinarizableEntry>.unmarshErr = false;
cache1.Remove(PrimaryKey(cache1));
cache1.Remove(PrimaryKey(cache2));
Assert.AreEqual(0, cache1.GetSize());
Assert.AreEqual(0, cache2.GetSize());
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
/// Test arguments validation.
/// </summary>
[Test]
public void TestValidation()
{
Assert.Throws<ArgumentException>(() => { cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(null)); });
}
/// <summary>
/// Test multiple closes.
/// </summary>
[Test]
public void TestMultipleClose()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
Assert.AreNotEqual(key1, key2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
IDisposable qryHnd;
using (qryHnd = cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
qryHnd.Dispose();
}
/// <summary>
/// Test regular callback operations.
/// </summary>
[Test]
public void TestCallback()
{
CheckCallback(false);
}
/// <summary>
/// Check regular callback execution.
/// </summary>
/// <param name="loc"></param>
protected void CheckCallback(bool loc)
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>(), true) :
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckCallbackSingle(key1, Entry(key1), Entry(key1 + 1), CacheEntryEventType.Updated);
cache1.Remove(key1);
CheckCallbackSingle(key1, Entry(key1 + 1), null, CacheEntryEventType.Removed);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2), Entry(key2 + 1), CacheEntryEventType.Updated);
cache1.Remove(key2);
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2 + 1), null, CacheEntryEventType.Removed);
}
cache1.Put(key1, Entry(key1));
CheckNoCallback(100);
cache1.Put(key2, Entry(key2));
CheckNoCallback(100);
}
/// <summary>
/// Test Ignite injection into callback.
/// </summary>
[Test]
public void TestCallbackInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
Assert.IsNull(cb.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb)))
{
Assert.IsNotNull(cb.ignite);
}
}
/// <summary>
/// Test binarizable filter logic.
/// </summary>
[Test]
public void TestFilterBinarizable()
{
CheckFilter(true, false);
}
/// <summary>
/// Test serializable filter logic.
/// </summary>
[Test]
public void TestFilterSerializable()
{
CheckFilter(false, false);
}
/// <summary>
/// Tests the defaults.
/// </summary>
[Test]
public void TestDefaults()
{
var qry = new ContinuousQuery<int, int>(null);
Assert.AreEqual(ContinuousQuery.DefaultAutoUnsubscribe, qry.AutoUnsubscribe);
Assert.AreEqual(ContinuousQuery.DefaultBufferSize, qry.BufferSize);
Assert.AreEqual(ContinuousQuery.DefaultTimeInterval, qry.TimeInterval);
Assert.IsFalse(qry.Local);
}
/// <summary>
/// Check filter.
/// </summary>
/// <param name="binarizable">Binarizable.</param>
/// <param name="loc">Local cache flag.</param>
protected void CheckFilter(bool binarizable, bool loc)
{
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) :
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
int key2 = PrimaryKey(cache2);
cache1.GetAndPut(key2, Entry(key2));
if (loc)
{
CheckNoFilter(key2);
CheckNoCallback(key2);
}
else
{
CheckFilterSingle(key2, null, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
AbstractFilter<BinarizableEntry>.res = false;
// Ignored put from local node.
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckFilterSingle(key1, Entry(key1), Entry(key1 + 1));
CheckNoCallback(100);
// Ignored put from remote node.
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoFilter(100);
else
CheckFilterSingle(key2, Entry(key2), Entry(key2 + 1));
CheckNoCallback(100);
}
}
/// <summary>
/// Test binarizable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorBinarizable()
{
CheckFilterInvokeError(true);
}
/// <summary>
/// Test serializable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorSerializable()
{
CheckFilterInvokeError(false);
}
/// <summary>
/// Check filter error handling logic during invoke.
/// </summary>
private void CheckFilterInvokeError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.err = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache1), Entry(1)));
// Put from remote node.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache2), Entry(1)));
}
}
/// <summary>
/// Test binarizable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorBinarizable()
{
CheckFilterMarshalError(true);
}
/// <summary>
/// Test serializable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorSerializable()
{
CheckFilterMarshalError(false);
}
/// <summary>
/// Check filter marshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterMarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.marshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>)new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
Assert.Throws<Exception>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
/// <summary>
/// Test non-serializable filter error.
/// </summary>
[Test]
public void TestFilterNonSerializable()
{
CheckFilterNonSerializable(false);
}
/// <summary>
/// Test non-serializable filter behavior.
/// </summary>
/// <param name="loc"></param>
protected void CheckFilterNonSerializable(bool loc)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter = new LocalFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc
? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true)
: new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
if (loc)
{
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
}
}
else
{
Assert.Throws<BinaryObjectException>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
}
/// <summary>
/// Test binarizable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorBinarizable()
{
CheckFilterUnmarshalError(true);
}
/// <summary>
/// Test serializable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorSerializable()
{
CheckFilterUnmarshalError(false);
}
/// <summary>
/// Check filter unmarshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterUnmarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
// Remote put must fail.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache2), Entry(1)));
}
}
/// <summary>
/// Test Ignite injection into filters.
/// </summary>
[Test]
public void TestFilterInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
BinarizableFilter filter = new BinarizableFilter();
Assert.IsNull(filter.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb, filter)))
{
// Local injection.
Assert.IsNotNull(filter.ignite);
// Remote injection.
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, 500));
Assert.IsNotNull(evt.ignite);
}
}
/// <summary>
/// Test "keep-binary" scenario.
/// </summary>
[Test]
public void TestKeepBinary()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
ContinuousQuery<int, IBinaryObject> qry = new ContinuousQuery<int, IBinaryObject>(
new Listener<IBinaryObject>(), new KeepBinaryFilter());
using (cache.QueryContinuous(qry))
{
// 1. Local put.
cache1.GetAndPut(PrimaryKey(cache1), Entry(1));
CallbackEvent cbEvt;
FilterEvent filterEvt;
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache1), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(1), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache1), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(1), (cbEvt.entries.First().Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
// 2. Remote put.
ClearEvents();
cache1.GetAndPut(PrimaryKey(cache2), Entry(2));
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache2), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(2), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache2), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(2),
(cbEvt.entries.First().Value as IBinaryObject).Deserialize<BinarizableEntry>());
}
}
/// <summary>
/// Test value types (special handling is required for nulls).
/// </summary>
[Test]
public void TestValueTypes()
{
var cache = grid1.GetCache<int, int>(cacheName);
var qry = new ContinuousQuery<int, int>(new Listener<int>());
var key = PrimaryKey(cache);
using (cache.QueryContinuous(qry))
{
// First update
cache.Put(key, 1);
CallbackEvent cbEvt;
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
var cbEntry = cbEvt.entries.Single();
Assert.IsFalse(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(null, cbEntry.OldValue);
Assert.AreEqual(1, cbEntry.Value);
// Second update
cache.Put(key, 2);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(1, cbEntry.OldValue);
Assert.AreEqual(2, cbEntry.Value);
// Remove
cache.Remove(key);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsFalse(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(2, cbEntry.OldValue);
Assert.AreEqual(null, cbEntry.Value);
}
}
/// <summary>
/// Test whether buffer size works fine.
/// </summary>
[Test]
public void TestBufferSize()
{
// Put two remote keys in advance.
var rmtKeys = TestUtils.GetPrimaryKeys(cache2.Ignite, cache2.Name).Take(2).ToList();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(1000000);
using (cache1.QueryContinuous(qry))
{
qry.BufferSize = 2;
cache1.GetAndPut(rmtKeys[0], Entry(rmtKeys[0]));
CheckNoCallback(100);
cache1.GetAndPut(rmtKeys[1], Entry(rmtKeys[1]));
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, 1000));
Assert.AreEqual(2, evt.entries.Count);
var entryRmt0 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[0]); });
var entryRmt1 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[1]); });
Assert.AreEqual(rmtKeys[0], entryRmt0.Key);
Assert.IsNull(entryRmt0.OldValue);
Assert.AreEqual(Entry(rmtKeys[0]), entryRmt0.Value);
Assert.AreEqual(rmtKeys[1], entryRmt1.Key);
Assert.IsNull(entryRmt1.OldValue);
Assert.AreEqual(Entry(rmtKeys[1]), entryRmt1.Value);
}
cache1.Remove(rmtKeys[0]);
cache1.Remove(rmtKeys[1]);
}
/// <summary>
/// Test whether timeout works fine.
/// </summary>
[Test]
public void TestTimeout()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(500);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
cache1.GetAndPut(key2, Entry(key2));
CheckNoCallback(100);
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
}
/// <summary>
/// Test whether nested Ignite API call from callback works fine.
/// </summary>
[Test]
public void TestNestedCallFromCallback()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
int key = PrimaryKey(cache1);
NestedCallListener cb = new NestedCallListener();
using (cache.QueryContinuous(new ContinuousQuery<int, IBinaryObject>(cb)))
{
cache1.GetAndPut(key, Entry(key));
cb.countDown.Wait();
}
cache.Remove(key);
}
/// <summary>
/// Tests the initial query.
/// </summary>
[Test]
public void TestInitialQuery()
{
// Scan query, GetAll
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.GetAll());
// Scan query, iterator
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.ToList());
// Sql query, GetAll
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.GetAll());
// Sql query, iterator
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.ToList());
// Text query, GetAll
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.GetAll());
// Text query, iterator
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.ToList());
// Test exception: invalid initial query
var ex = Assert.Throws<IgniteException>(
() => TestInitialQuery(new TextQuery(typeof (BinarizableEntry), "*"), cur => cur.GetAll()));
Assert.AreEqual("Cannot parse '*': '*' or '?' not allowed as first character in WildcardQuery", ex.Message);
}
/// <summary>
/// Tests the initial query.
/// </summary>
private void TestInitialQuery(QueryBase initialQry, Func<IQueryCursor<ICacheEntry<int, BinarizableEntry>>,
IEnumerable<ICacheEntry<int, BinarizableEntry>>> getAllFunc)
{
var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
cache1.Put(11, Entry(11));
cache1.Put(12, Entry(12));
cache1.Put(33, Entry(33));
try
{
IContinuousQueryHandle<ICacheEntry<int, BinarizableEntry>> contQry;
using (contQry = cache1.QueryContinuous(qry, initialQry))
{
// Check initial query
var initialEntries =
getAllFunc(contQry.GetInitialQueryCursor()).Distinct().OrderBy(x => x.Key).ToList();
Assert.Throws<InvalidOperationException>(() => contQry.GetInitialQueryCursor());
Assert.AreEqual(2, initialEntries.Count);
for (int i = 0; i < initialEntries.Count; i++)
{
Assert.AreEqual(i + 11, initialEntries[i].Key);
Assert.AreEqual(i + 11, initialEntries[i].Value.val);
}
// Check continuous query
cache1.Put(44, Entry(44));
CheckCallbackSingle(44, null, Entry(44), CacheEntryEventType.Created);
}
Assert.Throws<ObjectDisposedException>(() => contQry.GetInitialQueryCursor());
contQry.Dispose(); // multiple dispose calls are ok
}
finally
{
cache1.Clear();
}
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
private void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal)
{
CheckFilterSingle(expKey, expOldVal, expVal, 1000);
ClearEvents();
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout)
{
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(expKey, evt.entry.Key);
Assert.AreEqual(expOldVal, evt.entry.OldValue);
Assert.AreEqual(expVal, evt.entry.Value);
ClearEvents();
}
/// <summary>
/// Clears the events collection.
/// </summary>
private static void ClearEvents()
{
while (FILTER_EVTS.Count > 0)
FILTER_EVTS.Take();
}
/// <summary>
/// Ensure that no filter events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private static void CheckNoFilter(int timeout)
{
FilterEvent evt;
Assert.IsFalse(FILTER_EVTS.TryTake(out evt, timeout));
}
/// <summary>
/// Check single callback event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected new value.</param>
/// <param name="expType">Expected type.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal,
CacheEntryEventType expType, int timeout = 1000)
{
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(0, CB_EVTS.Count);
var e = evt.entries.Single();
Assert.AreEqual(expKey, e.Key);
Assert.AreEqual(expOldVal, e.OldValue);
Assert.AreEqual(expVal, e.Value);
Assert.AreEqual(expType, e.EventType);
}
/// <summary>
/// Ensure that no callback events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private void CheckNoCallback(int timeout)
{
CallbackEvent evt;
Assert.IsFalse(CB_EVTS.TryTake(out evt, timeout));
}
/// <summary>
/// Craate entry.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Entry.</returns>
private static BinarizableEntry Entry(int val)
{
return new BinarizableEntry(val);
}
/// <summary>
/// Get primary key for cache.
/// </summary>
/// <param name="cache">Cache.</param>
/// <returns>Primary key.</returns>
private static int PrimaryKey<T>(ICache<int, T> cache)
{
return TestUtils.GetPrimaryKey(cache.Ignite, cache.Name);
}
/// <summary>
/// Creates object-typed event.
/// </summary>
private static ICacheEntryEvent<object, object> CreateEvent<T, V>(ICacheEntryEvent<T,V> e)
{
if (!e.HasOldValue)
return new CacheEntryCreateEvent<object, object>(e.Key, e.Value);
if (!e.HasValue)
return new CacheEntryRemoveEvent<object, object>(e.Key, e.OldValue);
return new CacheEntryUpdateEvent<object, object>(e.Key, e.OldValue, e.Value);
}
/// <summary>
/// Binarizable entry.
/// </summary>
public class BinarizableEntry
{
/** Value. */
public readonly int val;
/** <inheritDot /> */
public override int GetHashCode()
{
return val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public BinarizableEntry(int val)
{
this.val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
return obj != null && obj is BinarizableEntry && ((BinarizableEntry)obj).val == val;
}
/** <inheritDoc /> */
public override string ToString()
{
return string.Format("BinarizableEntry [Val: {0}]", val);
}
}
/// <summary>
/// Abstract filter.
/// </summary>
[Serializable]
public abstract class AbstractFilter<V> : ICacheEntryEventFilter<int, V>
{
/** Result. */
public static volatile bool res = true;
/** Throw error on invocation. */
public static volatile bool err;
/** Throw error during marshalling. */
public static volatile bool marshErr;
/** Throw error during unmarshalling. */
public static volatile bool unmarshErr;
/** Grid. */
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public bool Evaluate(ICacheEntryEvent<int, V> evt)
{
if (err)
throw new Exception("Filter error.");
FILTER_EVTS.Add(new FilterEvent(ignite, CreateEvent(evt)));
return res;
}
}
/// <summary>
/// Filter which cannot be serialized.
/// </summary>
public class LocalFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
/// Binarizable filter.
/// </summary>
public class BinarizableFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
}
/// <summary>
/// Serializable filter.
/// </summary>
[Serializable]
public class SerializableFilter : AbstractFilter<BinarizableEntry>, ISerializable
{
/// <summary>
/// Constructor.
/// </summary>
public SerializableFilter()
{
// No-op.
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info">Info.</param>
/// <param name="context">Context.</param>
protected SerializableFilter(SerializationInfo info, StreamingContext context)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
}
/// <summary>
/// Filter for "keep-binary" scenario.
/// </summary>
public class KeepBinaryFilter : AbstractFilter<IBinaryObject>
{
// No-op.
}
/// <summary>
/// Listener.
/// </summary>
public class Listener<V> : ICacheEntryEventListener<int, V>
{
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public void OnEvent(IEnumerable<ICacheEntryEvent<int, V>> evts)
{
CB_EVTS.Add(new CallbackEvent(evts.Select(CreateEvent).ToList()));
}
}
/// <summary>
/// Listener with nested Ignite API call.
/// </summary>
public class NestedCallListener : ICacheEntryEventListener<int, IBinaryObject>
{
/** Event. */
public readonly CountdownEvent countDown = new CountdownEvent(1);
public void OnEvent(IEnumerable<ICacheEntryEvent<int, IBinaryObject>> evts)
{
foreach (ICacheEntryEvent<int, IBinaryObject> evt in evts)
{
IBinaryObject val = evt.Value;
IBinaryType meta = val.GetBinaryType();
Assert.AreEqual(typeof(BinarizableEntry).FullName, meta.TypeName);
}
countDown.Signal();
}
}
/// <summary>
/// Filter event.
/// </summary>
public class FilterEvent
{
/** Grid. */
public IIgnite ignite;
/** Entry. */
public ICacheEntryEvent<object, object> entry;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ignite">Grid.</param>
/// <param name="entry">Entry.</param>
public FilterEvent(IIgnite ignite, ICacheEntryEvent<object, object> entry)
{
this.ignite = ignite;
this.entry = entry;
}
}
/// <summary>
/// Callbakc event.
/// </summary>
public class CallbackEvent
{
/** Entries. */
public ICollection<ICacheEntryEvent<object, object>> entries;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="entries">Entries.</param>
public CallbackEvent(ICollection<ICacheEntryEvent<object, object>> entries)
{
this.entries = entries;
}
}
/// <summary>
/// ScanQuery filter for InitialQuery test.
/// </summary>
[Serializable]
private class InitialQueryScanFilter : ICacheEntryFilter<int, BinarizableEntry>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, BinarizableEntry> entry)
{
return entry.Key < 33;
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class BaseProviderAsyncTest
{
[Fact]
public void TestDbConnection()
{
MockConnection connection = new MockConnection();
CancellationTokenSource source = new CancellationTokenSource();
// ensure OpenAsync() calls OpenAsync(CancellationToken.None)
DataTestClass.AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
connection.OpenAsync().Wait();
Assert.False(connection.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestClass.AssertEqualsWithDescription(ConnectionState.Open, connection.State, "Connection state should have been marked as Open");
connection.Close();
// Verify cancellationToken over-ride
DataTestClass.AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
connection.OpenAsync(source.Token).Wait();
DataTestClass.AssertEqualsWithDescription(ConnectionState.Open, connection.State, "Connection state should have been marked as Open");
connection.Close();
// Verify exceptions are routed through task
MockConnection connectionFail = new MockConnection()
{
Fail = true
};
connectionFail.OpenAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
connectionFail.OpenAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
// Verify base implementation does not call Open when passed an already cancelled cancellation token
source.Cancel();
DataTestClass.AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
connection.OpenAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestClass.AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
}
[Fact]
public void TestDbCommand()
{
MockCommand command = new MockCommand()
{
ScalarResult = 1,
Results = Enumerable.Range(1, 5).Select((x) => new object[] { x, x.ToString() })
};
CancellationTokenSource source = new CancellationTokenSource();
// Verify parameter routing and correct synchronous implementation is called
command.ExecuteNonQueryAsync().Wait();
Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestClass.AssertEqualsWithDescription("ExecuteNonQuery", command.LastCommand, "Last command was not as expected");
command.ExecuteReaderAsync().Wait();
DataTestClass.AssertEqualsWithDescription(CommandBehavior.Default, command.CommandBehavior, "Command behavior should have been marked as Default");
Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestClass.AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
command.ExecuteScalarAsync().Wait();
Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestClass.AssertEqualsWithDescription("ExecuteScalar", command.LastCommand, "Last command was not as expected");
command.ExecuteNonQueryAsync(source.Token).Wait();
DataTestClass.AssertEqualsWithDescription("ExecuteNonQuery", command.LastCommand, "Last command was not as expected");
command.ExecuteReaderAsync(source.Token).Wait();
DataTestClass.AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
command.ExecuteScalarAsync(source.Token).Wait();
DataTestClass.AssertEqualsWithDescription("ExecuteScalar", command.LastCommand, "Last command was not as expected");
command.ExecuteReaderAsync(CommandBehavior.SequentialAccess).Wait();
DataTestClass.AssertEqualsWithDescription(CommandBehavior.SequentialAccess, command.CommandBehavior, "Command behavior should have been marked as SequentialAccess");
Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
DataTestClass.AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
command.ExecuteReaderAsync(CommandBehavior.SingleRow, source.Token).Wait();
DataTestClass.AssertEqualsWithDescription(CommandBehavior.SingleRow, command.CommandBehavior, "Command behavior should have been marked as SingleRow");
DataTestClass.AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
// Verify exceptions are routed through task
MockCommand commandFail = new MockCommand
{
Fail = true
};
commandFail.ExecuteNonQueryAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteNonQueryAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteReaderAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteReaderAsync(CommandBehavior.SequentialAccess).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteReaderAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteReaderAsync(CommandBehavior.SequentialAccess, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteScalarAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
commandFail.ExecuteScalarAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
// Verify base implementation does not call Open when passed an already cancelled cancellation token
source.Cancel();
command.LastCommand = "Nothing";
command.ExecuteNonQueryAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestClass.AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
command.ExecuteReaderAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestClass.AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestClass.AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
command.ExecuteScalarAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestClass.AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
// Verify cancellation
command.WaitForCancel = true;
source = new CancellationTokenSource();
Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
Task result = command.ExecuteNonQueryAsync(source.Token);
Assert.True(result.IsFaulted, "Task result should be faulted");
source = new CancellationTokenSource();
Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
result = command.ExecuteReaderAsync(source.Token);
Assert.True(result.IsFaulted, "Task result should be faulted");
source = new CancellationTokenSource();
Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
result = command.ExecuteScalarAsync(source.Token);
Assert.True(result.IsFaulted, "Task result should be faulted");
}
[Fact]
public void TestDbDataReader()
{
var query = Enumerable.Range(1, 2).Select((x) => new object[] { x, x.ToString(), DBNull.Value });
MockDataReader reader = new MockDataReader { Results = query.GetEnumerator() };
CancellationTokenSource source = new CancellationTokenSource();
Task<bool> result;
result = reader.ReadAsync(); result.Wait();
DataTestClass.AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
Assert.True(result.Result, "Should have received a Result from the ReadAsync");
Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
GetFieldValueAsync(reader, 0, 1);
Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
GetFieldValueAsync(reader, source.Token, 1, "1");
result = reader.ReadAsync(source.Token); result.Wait();
DataTestClass.AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
Assert.True(result.Result, "Should have received a Result from the ReadAsync");
GetFieldValueAsync<object>(reader, 2, DBNull.Value);
GetFieldValueAsync<DBNull>(reader, 2, DBNull.Value);
reader.GetFieldValueAsync<int?>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
reader.GetFieldValueAsync<string>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
reader.GetFieldValueAsync<bool>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
DataTestClass.AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
result = reader.ReadAsync(); result.Wait();
DataTestClass.AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
Assert.False(result.Result, "Should NOT have received a Result from the ReadAsync");
result = reader.NextResultAsync();
DataTestClass.AssertEqualsWithDescription("NextResult", reader.LastCommand, "Last command was not as expected");
Assert.False(result.Result, "Should NOT have received a Result from NextResultAsync");
Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
result = reader.NextResultAsync(source.Token);
DataTestClass.AssertEqualsWithDescription("NextResult", reader.LastCommand, "Last command was not as expected");
Assert.False(result.Result, "Should NOT have received a Result from NextResultAsync");
MockDataReader readerFail = new MockDataReader { Results = query.GetEnumerator(), Fail = true };
readerFail.ReadAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.ReadAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.NextResultAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.NextResultAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.GetFieldValueAsync<object>(0).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
readerFail.GetFieldValueAsync<object>(0, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
source.Cancel();
reader.LastCommand = "Nothing";
reader.ReadAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestClass.AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
reader.NextResultAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestClass.AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
reader.GetFieldValueAsync<object>(0, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
DataTestClass.AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
}
private void GetFieldValueAsync<T>(MockDataReader reader, int ordinal, T expected)
{
Task<T> result = reader.GetFieldValueAsync<T>(ordinal);
result.Wait();
DataTestClass.AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
DataTestClass.AssertEqualsWithDescription(expected, result.Result, "GetFieldValueAsync did not return expected value");
}
private void GetFieldValueAsync<T>(MockDataReader reader, CancellationToken cancellationToken, int ordinal, T expected)
{
Task<T> result = reader.GetFieldValueAsync<T>(ordinal, cancellationToken);
result.Wait();
DataTestClass.AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
DataTestClass.AssertEqualsWithDescription(expected, result.Result, "GetFieldValueAsync did not return expected value");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using IxMilia.Dxf.Collections;
using IxMilia.Dxf.Sections;
namespace IxMilia.Dxf.Tables
{
public enum DxfViewRenderMode
{
Classic2D = 0,
Wireframe = 1,
HiddenLine = 2,
FlatShaded = 3,
GouraudShaded = 4,
FlatShadedWithWireframe = 5,
GouraudShadedWithWireframe = 6
}
public enum DxfDefaultLightingType
{
OneDistantLight = 0,
TwoDistantLights = 1
}
public abstract partial class DxfTable : IDxfItemInternal
{
public const string AppIdText = "APPID";
public const string BlockRecordText = "BLOCK_RECORD";
public const string DimStyleText = "DIMSTYLE";
public const string LayerText = "LAYER";
public const string LTypeText = "LTYPE";
public const string StyleText = "STYLE";
public const string UcsText = "UCS";
public const string ViewText = "VIEW";
public const string ViewPortText = "VPORT";
public IDxfItem Owner { get; private set; }
void IDxfItemInternal.SetOwner(IDxfItem owner)
{
Owner = owner;
}
IEnumerable<DxfPointer> IDxfItemInternal.GetPointers()
{
return GetSymbolItems().SelectMany(i => ((IDxfItemInternal)i).GetPointers());
}
IEnumerable<IDxfItemInternal> IDxfItemInternal.GetChildItems()
{
return GetSymbolItems().Cast<IDxfItemInternal>();
}
internal abstract DxfTableType TableType { get; }
internal virtual string TableClassName { get { return null; } }
public DxfHandle Handle { get; set; }
public DxfHandle OwnerHandle { get; set; }
public IList<DxfCodePairGroup> ExtensionDataGroups { get; }
public DxfTable()
{
ExtensionDataGroups = new ListNonNull<DxfCodePairGroup>();
}
internal virtual void Normalize() { }
protected abstract IEnumerable<DxfSymbolTableFlags> GetSymbolItems();
internal IEnumerable<DxfCodePair> GetValuePairs(DxfAcadVersion version, bool outputHandles, HashSet<IDxfItem> writtenItems)
{
BeforeWrite();
var pairs = new List<DxfCodePair>();
// common pairs
pairs.Add(new DxfCodePair(0, DxfSection.TableText));
pairs.Add(new DxfCodePair(2, TableTypeToName(TableType)));
if (outputHandles && Handle.Value != 0)
{
pairs.Add(new DxfCodePair(5, DxfCommonConverters.HandleString(Handle)));
}
if (version >= DxfAcadVersion.R13)
{
foreach (var group in ExtensionDataGroups)
{
group.AddValuePairs(pairs, version, outputHandles);
}
if (version >= DxfAcadVersion.R2000 && OwnerHandle.Value != 0)
{
pairs.Add(new DxfCodePair(330, DxfCommonConverters.HandleString(OwnerHandle)));
}
pairs.Add(new DxfCodePair(100, "AcDbSymbolTable"));
}
var symbolItems = GetSymbolItems().Where(item => item != null).OrderBy(i => i.Name).ToList();
pairs.Add(new DxfCodePair(70, (short)symbolItems.Count));
if (version >= DxfAcadVersion.R2000 && TableClassName != null)
{
pairs.Add(new DxfCodePair(100, TableClassName));
}
foreach (var item in symbolItems)
{
if (writtenItems.Add(item))
{
item.AddCommonValuePairs(pairs, version, outputHandles);
item.AddValuePairs(pairs, version, outputHandles);
}
}
pairs.Add(new DxfCodePair(0, DxfSection.EndTableText));
return pairs;
}
public string TableTypeName
{
get { return TableTypeToName(TableType); }
}
public static DxfTableType TableNameToType(string name)
{
var type = DxfTableType.AppId;
switch (name)
{
case AppIdText:
type = DxfTableType.AppId;
break;
case BlockRecordText:
type = DxfTableType.BlockRecord;
break;
case DimStyleText:
type = DxfTableType.DimStyle;
break;
case LayerText:
type = DxfTableType.Layer;
break;
case LTypeText:
type = DxfTableType.LType;
break;
case StyleText:
type = DxfTableType.Style;
break;
case UcsText:
type = DxfTableType.Ucs;
break;
case ViewText:
type = DxfTableType.View;
break;
case ViewPortText:
type = DxfTableType.ViewPort;
break;
}
return type;
}
public static string TableTypeToName(DxfTableType type)
{
string name = "NONE";
switch (type)
{
case DxfTableType.AppId:
name = AppIdText;
break;
case DxfTableType.BlockRecord:
name = BlockRecordText;
break;
case DxfTableType.DimStyle:
name = DimStyleText;
break;
case DxfTableType.Layer:
name = LayerText;
break;
case DxfTableType.LType:
name = LTypeText;
break;
case DxfTableType.Style:
name = StyleText;
break;
case DxfTableType.Ucs:
name = UcsText;
break;
case DxfTableType.View:
name = ViewText;
break;
case DxfTableType.ViewPort:
name = ViewPortText;
break;
}
return name;
}
internal static DxfTable FromBuffer(DxfCodePairBufferReader buffer)
{
var pair = buffer.Peek();
buffer.Advance();
if (pair.Code != 2)
{
throw new DxfReadException("Expected table type.", pair);
}
var tableType = pair.StringValue;
// read common table values
var commonValues = new List<DxfCodePair>();
var groups = new List<DxfCodePairGroup>();
pair = buffer.Peek();
while (pair != null && pair.Code != 0)
{
buffer.Advance();
if (pair.Code == DxfCodePairGroup.GroupCodeNumber)
{
var groupName = DxfCodePairGroup.GetGroupName(pair.StringValue);
groups.Add(DxfCodePairGroup.FromBuffer(buffer, groupName));
}
else
{
commonValues.Add(pair);
}
pair = buffer.Peek();
}
DxfTable result;
switch (tableType)
{
case DxfTable.AppIdText:
result = DxfAppIdTable.ReadFromBuffer(buffer);
break;
case DxfTable.BlockRecordText:
result = DxfBlockRecordTable.ReadFromBuffer(buffer);
break;
case DxfTable.DimStyleText:
result = DxfDimStyleTable.ReadFromBuffer(buffer);
break;
case DxfTable.LayerText:
result = DxfLayerTable.ReadFromBuffer(buffer);
break;
case DxfTable.LTypeText:
result = DxfLTypeTable.ReadFromBuffer(buffer);
break;
case DxfTable.StyleText:
result = DxfStyleTable.ReadFromBuffer(buffer);
break;
case DxfTable.UcsText:
result = DxfUcsTable.ReadFromBuffer(buffer);
break;
case DxfTable.ViewText:
result = DxfViewTable.ReadFromBuffer(buffer);
break;
case DxfTable.ViewPortText:
result = DxfViewPortTable.ReadFromBuffer(buffer);
break;
default:
SwallowTable(buffer);
result = null;
break;
}
if (result != null)
{
// set common values
foreach (var common in commonValues)
{
switch (common.Code)
{
case 5:
result.Handle = DxfCommonConverters.HandleString(common.StringValue);
break;
case 70:
// entry count, read dynamically
break;
case 330:
result.OwnerHandle = DxfCommonConverters.HandleString(common.StringValue);
break;
}
}
foreach (var group in groups)
{
result.ExtensionDataGroups.Add(group);
}
result.AfterRead();
}
return result;
}
protected virtual void BeforeWrite()
{
}
protected virtual void AfterRead()
{
}
internal static void SwallowTable(DxfCodePairBufferReader buffer)
{
while (buffer.ItemsRemain)
{
var pair = buffer.Peek();
buffer.Advance();
if (DxfTablesSection.IsTableEnd(pair))
break;
}
}
}
public partial class DxfAppIdTable
{
internal override void Normalize()
{
foreach (var name in new[] { "ACAD", "ACADANNOTATIVE", "ACAD_NAV_VCDISPLAY", "ACAD_MLEADERVER" })
{
if (!Items.Any(a => string.Compare(a.Name, name, StringComparison.OrdinalIgnoreCase) == 0))
{
Items.Add(new DxfAppId() { Name = name });
}
}
}
}
public partial class DxfBlockRecordTable
{
protected override void BeforeWrite()
{
foreach (var blockRecord in Items.Where(item => item != null))
{
blockRecord.BeforeWrite();
}
}
protected override void AfterRead()
{
foreach (var blockRecord in Items.Where(item => item != null))
{
blockRecord.AfterRead();
}
}
internal override void Normalize()
{
foreach (var name in new[] { "*MODEL_SPACE", "*PAPER_SPACE" })
{
if (!Items.Any(a => string.Compare(a.Name, name, StringComparison.OrdinalIgnoreCase) == 0))
{
Items.Add(new DxfBlockRecord() { Name = name });
}
}
}
}
public partial class DxfDimStyleTable
{
internal override void Normalize()
{
foreach (var name in new[] { "STANDARD", "ANNOTATIVE" })
{
if (!Items.Any(a => string.Compare(a.Name, name, StringComparison.OrdinalIgnoreCase) == 0))
{
Items.Add(new DxfDimStyle() { Name = name });
}
}
}
}
public partial class DxfLayerTable
{
internal override void Normalize()
{
if (!Items.Any(a => a.Name == "0"))
{
Items.Add(new DxfLayer("0"));
}
}
}
public partial class DxfLTypeTable
{
internal override void Normalize()
{
foreach (var name in new[] { "BYLAYER", "BYBLOCK", "CONTINUOUS" })
{
if (!Items.Any(a => string.Compare(a.Name, name, StringComparison.OrdinalIgnoreCase) == 0))
{
Items.Add(new DxfLineType() { Name = name });
}
}
}
}
public partial class DxfStyleTable
{
internal override void Normalize()
{
foreach (var name in new[] { "STANDARD", "ANNOTATIVE" })
{
if (!Items.Any(a => string.Compare(a.Name, name, StringComparison.OrdinalIgnoreCase) == 0))
{
Items.Add(new DxfStyle() { Name = name });
}
}
}
}
public partial class DxfViewPortTable
{
internal override void Normalize()
{
if (!Items.Any(a => string.Compare(a.Name, DxfViewPort.ActiveViewPortName, StringComparison.OrdinalIgnoreCase) == 0))
{
Items.Add(new DxfViewPort() { Name = DxfViewPort.ActiveViewPortName });
}
}
}
}
| |
// 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.Globalization;
public class DateTimeParse1
{
private CultureInfo CurrentCulture = TestLibrary.Utilities.CurrentCulture;
private const int c_MIN_STRING_LEN = 1;
private const int c_MAX_STRING_LEN = 2048;
private const int c_NUM_LOOPS = 100;
//new string[12] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
private static string[] c_MONTHS = CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthNames;
//new string[12] {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
private static string[] c_MONTHS_SH = CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthGenitiveNames;
//new string[7] {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
private static string[] c_DAYS_SH = CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedDayNames;
public static int Main()
{
DateTimeParse1 test = new DateTimeParse1();
TestLibrary.TestFramework.BeginTestCase("DateTimeParse1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
TestLibrary.Utilities.CurrentCulture = CultureInfo.InvariantCulture;
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
TestLibrary.Utilities.CurrentCulture = CurrentCulture;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
string dateBefore = "";
DateTime dateAfter;
TestLibrary.TestFramework.BeginScenario("PosTest1: DateTime.Parse(DateTime.Now)");
try
{
dateBefore = DateTime.Now.ToString();
dateAfter = DateTime.Parse( dateBefore );
if (!dateBefore.Equals(dateAfter.ToString()))
{
TestLibrary.TestFramework.LogError("001", "DateTime.Parse(" + dateBefore + ") did not equal " + dateAfter.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 29
int year; // 1900 - 2000
int month; // 1 - 12
TestLibrary.TestFramework.BeginScenario("PosTest2: DateTime.Parse(M/d/yyyy (ShortDatePattern ex: 1/3/2002))");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 28) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
dateBefore = month + "/" + day + "/" + year;
dateAfter = DateTime.Parse( dateBefore );
if (month != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year)
{
TestLibrary.TestFramework.LogError("003", "DateTime.Parse(" + dateBefore + ") did not equal " + dateAfter.ToString());
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int dayOfWeek; // 0 - 6
int day; // 1 - 28
int year; // 1900 - 2000
int month; // 0 - 11
TestLibrary.TestFramework.BeginScenario("PosTest3: DateTime.Parse(dddd, MMMM dd, yyyy (LongDatePattern ex: Thursday, January 03, 2002))");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
// cheat and get day of the week
dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year);
dayOfWeek = (int)dateAfter.DayOfWeek;
// parse the date
dateBefore = (DayOfWeek)dayOfWeek + ", " + c_MONTHS[month] + " " + day + ", " + year;
dateAfter = DateTime.Parse( dateBefore );
if ((month+1) != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek)
{
TestLibrary.TestFramework.LogError("005", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.DayOfWeek + ", " + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ", " + dateAfter.Year + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int dayOfWeek; // 0 - 6
int day; // 1 - 28
int year; // 1900 - 2000
int month; // 0 - 11
int hour; // 0 - 11
int minute; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
TestLibrary.TestFramework.BeginScenario("PosTest4: DateTime.Parse(ex: Thursday, January 03, 2002 12:00 AM)");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
// cheat and get day of the week
dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year);
dayOfWeek = (int)dateAfter.DayOfWeek;
// parse the date
dateBefore = (DayOfWeek)dayOfWeek + ", " + c_MONTHS[month] + " " + day + ", " + year + " " + hour + ":" + minute + " " + twelveHour[timeOfDay];
dateAfter = DateTime.Parse( dateBefore );
if ((month+1) != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek
|| (hour + timeOfDay*12) != dateAfter.Hour
|| minute != dateAfter.Minute)
{
TestLibrary.TestFramework.LogError("007", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.DayOfWeek + ", " + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ", " + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int dayOfWeek; // 0 - 6
int day; // 1 - 28
int year; // 1900 - 2000
int month; // 0 - 11
int hour; // 0 - 11
int minute; // 0 - 59
int second; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
TestLibrary.TestFramework.BeginScenario("PosTest5: DateTime.Parse(dddd, MMMM dd, yyyy h:mm:ss tt (FullDateTimePattern ex: Thursday, January 03, 2002 12:00:00 AM))");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
// cheat and get day of the week
dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year);
dayOfWeek = (int)dateAfter.DayOfWeek;
// parse the date
dateBefore = (DayOfWeek)dayOfWeek + ", " + c_MONTHS[month] + " " + day + ", " + year + " " + hour + ":" + minute + ":" + second + " " + twelveHour[timeOfDay];
dateAfter = DateTime.Parse( dateBefore );
if ((month+1) != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek
|| (hour + timeOfDay*12) != dateAfter.Hour
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("009", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.DayOfWeek + ", " + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ", " + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 1 - 12
int year; // 1900 - 2000
int hour; // 0 - 11
int minute; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
TestLibrary.TestFramework.BeginScenario("PosTest6: DateTime.Parse(ex: 1/3/2002 12:00 AM)");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
// parse the date
dateBefore = month + "/" + day + "/" + year + " " + hour + ":" + minute + " " + twelveHour[timeOfDay];
dateAfter = DateTime.Parse( dateBefore );
if (month != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| (hour + timeOfDay*12) != dateAfter.Hour
|| minute != dateAfter.Minute)
{
TestLibrary.TestFramework.LogError("011", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Month + "/" + dateAfter.Day + "/" + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 1 - 12
int year; // 1900 - 2000
int hour; // 0 - 11
int minute; // 0 - 59
int second; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
TestLibrary.TestFramework.BeginScenario("PosTest7: DateTime.Parse(ex: 1/3/2002 12:00:00 AM)");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
// parse the date
dateBefore = month + "/" + day + "/" + year + " " + hour + ":" + minute + ":" + second + " " + twelveHour[timeOfDay];
dateAfter = DateTime.Parse( dateBefore );
if (month != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| (hour + timeOfDay*12) != dateAfter.Hour
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("013", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Month + "/" + dateAfter.Day + "/" + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 0 - 11
TestLibrary.TestFramework.BeginScenario("PosTest8: DateTime.Parse(MMMM dd (MonthDayPattern ex: January 03))");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
// parse the date
dateBefore = c_MONTHS[month] + " " + day;
dateAfter = DateTime.Parse( dateBefore );
if ((month+1) != dateAfter.Month
|| day != dateAfter.Day)
{
TestLibrary.TestFramework.LogError("015", "DateTime.Parse(" + dateBefore + ") did not equal (" + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int dayOfWeek; // 0 - 6
int day; // 1 - 28
int year; // 1900 - 2000
int month; // 0 - 11
int hour; // 12 - 23
int minute; // 0 - 59
int second; // 0 - 59
TestLibrary.TestFramework.BeginScenario("PosTest9: DateTime.Parse(ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (RFC1123Pattern ex: Thu, 03 Jan 2002 00:00:00 GMT))");
DateTime now = DateTime.Now;
int hourshift;
if (now - now.ToUniversalTime() < TimeSpan.Zero) // western hemisphere
hourshift = +12;
else
hourshift = 0;
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
hour = (TestLibrary.Generator.GetInt32(-55) % 12) + hourshift; // Parse will convert perform GMT -> PST conversion
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
dayOfWeek = (TestLibrary.Generator.GetInt32(-55) % 7);
// cheat and get day of the week
dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year);
dayOfWeek = (int)dateAfter.DayOfWeek;
// parse the date
dateBefore = c_DAYS_SH[dayOfWeek] + ", " + day + " " + c_MONTHS_SH[month] + " " + year + " " + hour + ":" + minute + ":" + second + " GMT";
dateAfter = DateTime.Parse( dateBefore );
if ((month+1) != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("017", "DateTime.Parse(" + dateBefore + ") did not equal (" + c_DAYS_SH[(int)dateAfter.DayOfWeek] + ", " + dateAfter.Day + " " + c_MONTHS_SH[dateAfter.Month-1] + " " + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + " GMT)");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 1 - 12
int year; // 1900 - 2000
int hour; // 0 - 23
int minute; // 0 - 59
int second; // 0 - 59
TestLibrary.TestFramework.BeginScenario("PosTest10: DateTime.Parse(yyyy'-'MM'-'dd'T'HH':'mm':'ss (SortableDateTimePattern ex: 2002-01-03T00:00:00))");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
hour = (TestLibrary.Generator.GetInt32(-55) % 24);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
// parse the date
dateBefore = year + "-" + month + "-" + day + "T" + ((10 > hour) ? "0" : "") + hour + ":" + ((10 > minute) ? "0" : "") + minute + ":" + ((10 > second) ? "0" : "") + second;
dateAfter = DateTime.Parse( dateBefore );
if (month != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| hour != dateAfter.Hour
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("019", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Year + "-" + dateAfter.Month + "-" + dateAfter.Day + "T" + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("020", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int hour; // 0 - 11
int minute; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
TestLibrary.TestFramework.BeginScenario("PosTest11: DateTime.Parse(h:mm tt (ShortTimePattern ex: 12:00 AM))");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
// parse the date
dateBefore = hour + ":" + minute + " " + twelveHour[timeOfDay];
dateAfter = DateTime.Parse( dateBefore );
if ((hour + timeOfDay*12) != dateAfter.Hour
|| minute != dateAfter.Minute)
{
TestLibrary.TestFramework.LogError("021", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Hour + ":" + dateAfter.Minute + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("022", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int hour; // 0 - 11
int minute; // 0 - 59
int second; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
TestLibrary.TestFramework.BeginScenario("PosTest12: DateTime.Parse(h:mm:ss tt (LongTimePattern ex: 12:00:00 AM))");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
// parse the date
dateBefore = hour + ":" + minute + ":" + second + " " + twelveHour[timeOfDay];
dateAfter = DateTime.Parse( dateBefore );
if ((hour + timeOfDay*12) != dateAfter.Hour
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("023", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("024", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest13()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 1 - 12
int year; // 1900 - 2000
int hour; // 12 - 23
int minute; // 0 - 59
int second; // 0 - 59
TestLibrary.TestFramework.BeginScenario("PosTest13: DateTime.Parse(yyyy'-'MM'-'dd HH':'mm':'ss'Z' (UniversalSortableDateTimePattern ex: 2002-01-03 00:00:00Z))");
DateTime now = DateTime.Now;
int hourshift;
if (now - now.ToUniversalTime() < TimeSpan.Zero) // western hemisphere
hourshift = +12;
else
hourshift = 0;
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
hour = (TestLibrary.Generator.GetInt32(-55) % 12) + hourshift; // conversion
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
// parse the date
dateBefore = year + "-" + month + "-" + day + " " + ((10 > hour) ? "0" : "") + hour + ":" + ((10 > minute) ? "0" : "") + minute + ":" + ((10 > second) ? "0" : "") + second +"Z";
dateAfter = DateTime.Parse( dateBefore );
if (month != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("025", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Year + "-" + dateAfter.Month + "-" + dateAfter.Day + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + "Z)");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("026", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("026", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest14()
{
bool retVal = true;
DateTime dateAfter;
string dateBefore = "";
int year; // 1900 - 2000
int month; // 0 - 11
TestLibrary.TestFramework.BeginScenario("PosTest14: DateTime.Parse(MMMM, yyyy (YearMonthPattern ex: January, 2002))");
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
// parse the date
dateBefore = c_MONTHS[month] + ", " + year;
dateAfter = DateTime.Parse( dateBefore );
if ((month+1) != dateAfter.Month
|| year != dateAfter.Year)
{
TestLibrary.TestFramework.LogError("027", "DateTime.Parse(" + dateBefore + ") did not equal (" + c_MONTHS[dateAfter.Month-1] + ", " + dateAfter.Year + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("028", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("028", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: DateTime.Parse(null)");
try
{
DateTime.Parse(null);
TestLibrary.TestFramework.LogError("029", "DateTime.Parse(null) should have thrown");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("030", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: DateTime.Parse(String.Empty)");
try
{
DateTime.Parse(String.Empty);
TestLibrary.TestFramework.LogError("031", "DateTime.Parse(String.Empty) should have thrown");
retVal = false;
}
catch (FormatException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("032", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
string strDateTime = "";
DateTime dateAfter;
TestLibrary.TestFramework.BeginScenario("NegTest3: DateTime.Parse(<garbage>)");
try
{
for (int i=0; i<c_NUM_LOOPS; i++)
{
try
{
strDateTime = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
dateAfter = DateTime.Parse(strDateTime);
TestLibrary.TestFramework.LogError("033", "DateTime.Parse(" + strDateTime + ") should have thrown (" + dateAfter + ")");
retVal = false;
}
catch (FormatException)
{
// expected
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("034", "Failing date: " + strDateTime);
TestLibrary.TestFramework.LogError("034", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| |
//Copyright 2019 Esri
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using LivingAtlasOfTheWorld.Common;
using LivingAtlasOfTheWorld.Models;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Core.Portal;
namespace LivingAtlasOfTheWorld.UI {
/// <summary>
/// Represents the settings for the Browse Dialog
/// </summary>
class BrowseLayersViewModel : INotifyPropertyChanged {
private static readonly string _title = "Browse Esri Map Layers and Web Maps";
private List<OnlineQuery> _browseQueries = new List<OnlineQuery>();
private OnlineQuery _selectedOnlineQuery = null;
private string _keywords = "";
private ObservableCollection<PortalItem> _results = new ObservableCollection<PortalItem>();
private ICommand _submitQueryCommand = null;
private DispatcherTimer _timer = null;
private double _progressValue = 1;
private double _maxProgressValue = 100;
private bool _executeQuery = false;
private bool _isInitialized = false;
private bool _addFailed = false;
private static List<PortalItemType> _resultOptions = new List<PortalItemType>() {PortalItemType.Layer, PortalItemType.WebMap};
private PortalItemType _selResultOption;
public BrowseLayersViewModel() {
BindingOperations.CollectionRegistering += BindingOperations_CollectionRegistering;
Initialize();
}
void BindingOperations_CollectionRegistering(object sender, CollectionRegisteringEventArgs e) {
if (e.Collection == Results)
BindingOperations.EnableCollectionSynchronization(_results, new object());
}
private void Initialize()
{
if (_isInitialized)
return;
_isInitialized = true;
_selResultOption = _resultOptions[0];
OnlineUriFactory.CreateOnlineUris();
foreach (var uri in OnlineUriFactory.OnlineUris)
{
//create a query
OnlineQuery query = new OnlineQuery()
{
OnlineUri = uri
};
_browseQueries.Add(query);
}
//init timer
_timer = new DispatcherTimer()
{
Interval = TimeSpan.FromMilliseconds(25d),
IsEnabled = false
};
_timer.Tick += (o, e) =>
{
//update the progress bar
_progressValue += 1.0;
if (_progressValue > _maxProgressValue)
_progressValue = 1.0;
FrameworkApplication.Current.Dispatcher.Invoke(() => OnPropertyChanged("ProgressValue"));
};
}
/// <summary>
/// Gets the title
/// </summary>
public string Title {
get {
return _title;
}
}
/// <summary>
/// Gets and sets the keywords for the current query
/// </summary>
public string Keywords {
get {
return _keywords;
}
set {
_keywords = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets the list of supported named queries
/// </summary>
public IReadOnlyList<OnlineQuery> BrowseQueryList {
get {
if (_browseQueries.Count == 0)
Initialize();
return _browseQueries;
}
}
/// <summary>
/// Gets and sets the selected Uri to be submitted
/// </summary>
public OnlineQuery SelectedOnlineQuery {
get {
return _selectedOnlineQuery;
}
set {
_selectedOnlineQuery = value;
OnPropertyChanged();
SubmitQuery();
}
}
/// <summary>
/// Gets the value to set on the progress
/// </summary>
public double ProgressValue {
get {
return _progressValue;
}
}
/// <summary>
/// Gets the max value to set on the progress
/// </summary>
public double MaxProgressValue {
get {
return _maxProgressValue;
}
}
/// <summary>
/// Gets whether a query is executing or not
/// </summary>
public bool IsExecutingQuery {
get {
return _executeQuery;
}
}
/// <summary>
/// Gets the list of results from the query
/// </summary>
public ObservableCollection<PortalItem> Results {
get {
return _results;
}
}
/// <summary>
/// Gets the list of supported result options
/// </summary>
public static IReadOnlyList<PortalItemType> ResultOptions {
get {
return _resultOptions;
}
}
public PortalItemType SelectedResultOption
{
get
{
return _selResultOption;
}
set
{
_selResultOption = value;
OnPropertyChanged();
SubmitQuery();
}
}
/// <summary>
/// Gets the relevant link text to display on the thumbnails
/// </summary>
public string LinkText {
get {
string linkText = (SelectedResultOption == PortalItemType.Layer ? "Add layer to map" : "Add web map");
return linkText;
}
}
/// <summary>
/// Gets the add status
/// </summary>
public string AddStatus {
get {
return _addFailed ? "Sorry, item cannot be added" : "";
}
}
#region Commands
/// <summary>
/// Gets a command to "manually" submit the query (assumes keywords have been added)
/// </summary>
public ICommand SubmitQueryCommand {
get {
if (_submitQueryCommand == null)
_submitQueryCommand = new RelayCommand((Action)SubmitQuery);
return _submitQueryCommand;
}
}
#endregion Commands
internal void AddLayerToMap(string url) {
//clear previous flag, if any
_addFailed = false;
OnPropertyChanged("AddStatus");
string id = url;
//get the query result
var result = _results.FirstOrDefault(ri => ri.ID == id);
if (result == null)
throw new ApplicationException(string.Format("Debug: bad id {0}",id));
QueuedTask.Run(action: async () => {
if (LayerFactory.Instance.CanCreateLayerFrom(result) && MapView.Active?.Map != null)
LayerFactory.Instance.CreateLayer(result, MapView.Active.Map);
else if (MapFactory.Instance.CanCreateMapFrom(result)) {
Map newMap = MapFactory.Instance.CreateMapFromItem(result);
IMapPane newMapPane = await ProApp.Panes.CreateMapPaneAsync(newMap);
}
else {
_addFailed = true;//cannot be added
FrameworkApplication.Current.Dispatcher.Invoke(() => OnPropertyChanged("AddStatus"));
}
});
}
private async void SubmitQuery() {
if (this.SelectedOnlineQuery == null)
return;
if (_executeQuery)
return;
_executeQuery = true;
_addFailed = false;
_results.Clear();
_timer.Start();
OnPropertyChanged("IsExecutingQuery");
OnPropertyChanged("AddStatus");
int maxResults = 0;
if (maxResults == 0)
maxResults = OnlineQuery.DefaultMaxResults;
try
{
this.SelectedOnlineQuery.Keywords = this.Keywords;
this.SelectedOnlineQuery.Content = SelectedResultOption;
int startIndex = 0;
ArcGISPortal portal = ArcGISPortalManager.Current.GetPortal(new Uri(@"http://www.arcgis.com:80/"));
do //Query ArcGIS Online for 25 items at a time for a max limit of 100 items.
{
this.SelectedOnlineQuery.Start = startIndex;
PortalQueryResultSet<PortalItem> portalResults = await ArcGISPortalExtensions.SearchForContentAsync(portal, this.SelectedOnlineQuery.PortalQuery);
if (portalResults.Results.OfType<PortalItem>().Count() == 0)
return;
foreach (var item in portalResults.Results.OfType<PortalItem>())
{
_results.Add(item);
}
startIndex = portalResults.Results.Count + startIndex;
} while (startIndex < maxResults);
}
finally {
_timer.Stop();
_executeQuery = false;
OnPropertyChanged("IsExecutingQuery");
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate {};
protected void OnPropertyChanged([CallerMemberName] string name = "") {
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Conversations.V1
{
/// <summary>
/// Create a new conversation in your account's default service
/// </summary>
public class CreateConversationOptions : IOptions<ConversationResource>
{
/// <summary>
/// The human-readable name of this conversation.
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// An application-defined string that uniquely identifies the resource
/// </summary>
public string UniqueName { get; set; }
/// <summary>
/// The date that this resource was created.
/// </summary>
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated.
/// </summary>
public DateTime? DateUpdated { get; set; }
/// <summary>
/// The unique ID of the Messaging Service this conversation belongs to.
/// </summary>
public string MessagingServiceSid { get; set; }
/// <summary>
/// An optional string metadata field you can use to store any data you wish.
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// Current state of this conversation.
/// </summary>
public ConversationResource.StateEnum State { get; set; }
/// <summary>
/// ISO8601 duration when conversation will be switched to `inactive` state.
/// </summary>
public string TimersInactive { get; set; }
/// <summary>
/// ISO8601 duration when conversation will be switched to `closed` state.
/// </summary>
public string TimersClosed { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public ConversationResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (UniqueName != null)
{
p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName));
}
if (DateCreated != null)
{
p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated)));
}
if (DateUpdated != null)
{
p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated)));
}
if (MessagingServiceSid != null)
{
p.Add(new KeyValuePair<string, string>("MessagingServiceSid", MessagingServiceSid.ToString()));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
if (State != null)
{
p.Add(new KeyValuePair<string, string>("State", State.ToString()));
}
if (TimersInactive != null)
{
p.Add(new KeyValuePair<string, string>("Timers.Inactive", TimersInactive));
}
if (TimersClosed != null)
{
p.Add(new KeyValuePair<string, string>("Timers.Closed", TimersClosed));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Update an existing conversation in your account's default service
/// </summary>
public class UpdateConversationOptions : IOptions<ConversationResource>
{
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The human-readable name of this conversation.
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The date that this resource was created.
/// </summary>
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated.
/// </summary>
public DateTime? DateUpdated { get; set; }
/// <summary>
/// An optional string metadata field you can use to store any data you wish.
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The unique ID of the Messaging Service this conversation belongs to.
/// </summary>
public string MessagingServiceSid { get; set; }
/// <summary>
/// Current state of this conversation.
/// </summary>
public ConversationResource.StateEnum State { get; set; }
/// <summary>
/// ISO8601 duration when conversation will be switched to `inactive` state.
/// </summary>
public string TimersInactive { get; set; }
/// <summary>
/// ISO8601 duration when conversation will be switched to `closed` state.
/// </summary>
public string TimersClosed { get; set; }
/// <summary>
/// An application-defined string that uniquely identifies the resource
/// </summary>
public string UniqueName { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public ConversationResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new UpdateConversationOptions
/// </summary>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public UpdateConversationOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (DateCreated != null)
{
p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated)));
}
if (DateUpdated != null)
{
p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated)));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
if (MessagingServiceSid != null)
{
p.Add(new KeyValuePair<string, string>("MessagingServiceSid", MessagingServiceSid.ToString()));
}
if (State != null)
{
p.Add(new KeyValuePair<string, string>("State", State.ToString()));
}
if (TimersInactive != null)
{
p.Add(new KeyValuePair<string, string>("Timers.Inactive", TimersInactive));
}
if (TimersClosed != null)
{
p.Add(new KeyValuePair<string, string>("Timers.Closed", TimersClosed));
}
if (UniqueName != null)
{
p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Remove a conversation from your account's default service
/// </summary>
public class DeleteConversationOptions : IOptions<ConversationResource>
{
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public ConversationResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new DeleteConversationOptions
/// </summary>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public DeleteConversationOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Fetch a conversation from your account's default service
/// </summary>
public class FetchConversationOptions : IOptions<ConversationResource>
{
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchConversationOptions
/// </summary>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public FetchConversationOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Retrieve a list of conversations in your account's default service
/// </summary>
public class ReadConversationOptions : ReadOptions<ConversationResource>
{
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("TDTK/Optional/AudioManager")]
public class AudioManager : MonoBehaviour {
static private AudioObject[] audioObject;
static public AudioManager instance;
static private Transform camT;
public float minFallOffRange=10;
public AudioClip[] musicList;
public bool playMusic=true;
public bool shuffle=false;
public float initialMusicVolume=0.5f;
private int currentTrackID=0;
private AudioSource musicSource;
private Transform listenerT;
public float initialSFXVolume=0.75f;
public AudioClip gameWonSound;
public AudioClip gameLostSound;
public AudioClip newRoundSound;
public AudioClip actionFailedSound;
private GameObject thisObj;
private Transform thisT;
static public void PlayGameWonSound(){
if(instance==null) return;
if(instance.gameWonSound!=null) PlaySound(instance.gameWonSound);
}
static public void PlayGameLostSound(){
if(instance==null) return;
if(instance.gameLostSound!=null) PlaySound(instance.gameLostSound);
}
public static void PlayNewRoundSound(int round){
if(instance==null) return;
if(instance.newRoundSound!=null) PlaySound(instance.newRoundSound);
}
static public void PlayActionFailedSound(){
if(instance==null) return;
if(instance.actionFailedSound!=null) PlaySound(instance.actionFailedSound);
}
void Awake(){
thisObj=gameObject;
thisT=transform;
camT=Camera.main.transform;
if(playMusic && musicList!=null && musicList.Length>0){
GameObject musicObj=new GameObject();
musicObj.name="MusicSource";
musicObj.transform.position=camT.position;
musicObj.transform.parent=camT;
musicSource=musicObj.AddComponent<AudioSource>();
musicSource.loop=false;
musicSource.playOnAwake=false;
musicSource.volume=initialMusicVolume;
musicSource.ignoreListenerVolume=true;
if(listenerT!=null){
musicObj.transform.parent=listenerT;
musicObj.transform.localPosition=Vector3.zero;
}
StartCoroutine(MusicRoutine());
}
audioObject=new AudioObject[20];
for(int i=0; i<audioObject.Length; i++){
GameObject obj=new GameObject();
obj.name="AudioSource"+i;
AudioSource src=obj.AddComponent<AudioSource>();
src.playOnAwake=false;
src.loop=false;
src.minDistance=minFallOffRange;
Transform t=obj.transform;
t.parent=thisObj.transform;
audioObject[i]=new AudioObject(src, t);
}
AudioListener.volume=initialSFXVolume;
if(instance==null) instance=this;
}
static public void Init(){
if(instance==null){
GameObject objParent=new GameObject();
objParent.name="AudioManager";
instance=objParent.AddComponent<AudioManager>();
}
}
public IEnumerator MusicRoutine(){
while(true){
if(shuffle) musicSource.clip=musicList[Random.Range(0, musicList.Length)];
else{
musicSource.clip=musicList[currentTrackID];
currentTrackID+=1;
if(currentTrackID==musicList.Length) currentTrackID=0;
}
musicSource.Play();
yield return new WaitForSeconds(musicSource.clip.length);
}
}
// Use this for initialization
void Start () {
}
void OnEnable(){
GameControlTB.onBattleEndE += OnGameOver;
GameControlTB.onNewRoundE += PlayNewRoundSound;
}
void OnDisable(){
GameControlTB.onBattleEndE -= OnGameOver;
GameControlTB.onNewRoundE -= PlayNewRoundSound;
}
void OnGameOver(int vicFactionID){
//if(victory) PlayGameWonSound();
//else PlayGameLostSound();
if(GameControlTB.playerFactionExisted){
if(GameControlTB.IsPlayerFaction(vicFactionID)){
PlayGameWonSound();
}
else{
PlayGameLostSound();
}
}
else{
PlayGameWonSound();
}
}
// Update is called once per frame
void Update () {
}
//check for the next free, unused audioObject
static private int GetUnusedAudioObject(){
for(int i=0; i<audioObject.Length; i++){
if(!audioObject[i].inUse){
return i;
}
}
//if everything is used up, use item number zero
return 0;
}
//this is a 3D sound that has to be played at a particular position following a particular event
static public int PlaySound(AudioClip clip, Vector3 pos){
if(instance==null) Init();
int ID=GetUnusedAudioObject();
audioObject[ID].inUse=true;
audioObject[ID].thisT.position=pos;
audioObject[ID].source.clip=clip;
audioObject[ID].source.loop=false;
audioObject[ID].source.Play();
float duration=audioObject[ID].source.clip.length;
instance.StartCoroutine(instance.ClearAudioObject(ID, duration));
return ID;
}
//this is a 3D sound that has to be played at a particular position following a particular event
static public int PlaySound(AudioClip clip, Transform srcT){
if(instance==null) Init();
int ID=GetUnusedAudioObject();
audioObject[ID].inUse=true;
//audioObject[ID].thisT.position=pos;
audioObject[ID].thisT.parent=srcT;
audioObject[ID].thisT.localPosition=Vector3.zero;
audioObject[ID].source.clip=clip;
audioObject[ID].source.loop=false;
audioObject[ID].source.Play();
float duration=audioObject[ID].source.clip.length;
instance.StartCoroutine(instance.ClearAudioObject(ID, duration));
return ID;
}
static public int PlaySoundLoop(AudioClip clip, Transform srcT){
if(instance==null) Init();
int ID=GetUnusedAudioObject();
audioObject[ID].inUse=true;
audioObject[ID].thisT.parent=srcT;
audioObject[ID].thisT.localPosition=Vector3.zero;
audioObject[ID].source.clip=clip;
audioObject[ID].source.loop=true;
audioObject[ID].source.Play();
return ID;
}
//this no position has been given, assume this is a 2D sound
static public int PlaySound(AudioClip clip){
if(instance==null) Init();
int ID=GetUnusedAudioObject();
audioObject[ID].inUse=true;
audioObject[ID].source.clip=clip;
audioObject[ID].source.loop=false;
audioObject[ID].source.Play();
audioObject[ID].thisT.position=camT.position;
float duration=audioObject[ID].source.clip.length;
instance.StartCoroutine(instance.ClearAudioObject(ID, duration));
return ID;
}
static public int PlaySoundLoop(AudioClip clip){
if(instance==null) Init();
int ID=GetUnusedAudioObject();
audioObject[ID].inUse=true;
audioObject[ID].source.clip=clip;
audioObject[ID].source.loop=true;
audioObject[ID].source.Play();
return ID;
}
public static void StopSound(int ID){
audioObject[ID].inUse=false;
audioObject[ID].source.Stop();
audioObject[ID].source.clip=null;
audioObject[ID].thisT.parent=instance.thisT;
//~ Debug.Log(audioObject[ID].source.gameObject);
}
//a sound routine for 2D sound, make sure they follow the listener, which is assumed to be the main camera
static IEnumerator SoundRoutine2D(int ID, float duration){
while(duration>0){
audioObject[ID].thisT.position=camT.position;
yield return null;
}
//finish playing, clear the audioObject
instance.StartCoroutine(instance.ClearAudioObject(ID, 0));
}
//function call to clear flag of an audioObject, indicate it's is free to be used again
private IEnumerator ClearAudioObject(int ID, float duration){
yield return new WaitForSeconds(duration);
audioObject[ID].inUse=false;
audioObject[ID].thisT.parent=thisT;
}
public static void SetSFXVolume(float val){
AudioListener.volume=val;
}
public static void SetMusicVolume(float val){
if(instance && instance.musicSource){
instance.musicSource.volume=val;
}
}
public static float GetSFXVolume(){
return AudioListener.volume;
}
public static float GetMusicVolume(){
if(instance && instance.musicSource){
return instance.musicSource.volume;
}
return instance.initialMusicVolume;
}
public static void SetMusicSourceToListener(Transform lisT){
instance.listenerT=lisT;
if(instance.musicSource!=null){
instance.musicSource.transform.parent=instance.listenerT;
instance.musicSource.transform.localPosition=Vector3.zero;
}
}
}
[System.Serializable]
public class AudioObject{
public AudioSource source;
public bool inUse=false;
public Transform thisT;
public AudioObject(AudioSource src, Transform t){
source=src;
thisT=t;
}
}
| |
namespace Nancy.Tests.Unit.Sessions
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using Nancy.Cryptography;
using FakeItEasy;
using Nancy.Bootstrapper;
using Nancy.IO;
using Nancy.Session;
using Xunit;
using Helpers = Nancy.Helpers;
public class CookieBasedSessionsFixture
{
private const string ValidData = "VgPJvXYwcXkn0gxDvg84tsfV9F5he1ZxhjsTZK1UZHVqWk7izPd9XsWnuFMrtQNRJEfyiqU2J7tAZDQvdKjQij9wUO6mOTCyZ7HPHK/pEnkgDFMXbHDctGQZSbb2WZZxola+Q3nP2tlQ+Tx//N6YyK7BwpsNPrvyHAvU1z5YzHfPT6HEowIl8mz/uUL6o+FME/Goi7RN2getMeYaPCs0fJkiMCAomnnagAy4aXN0Ak/p7Y3K/kpNAS6PvNu4aok0zVpfo1utP84GyyLomfr4urmDNFIe8PBVoKhuomxjsUOddaarHqqmN3PXOp15SPXPDxEKfpuLzhmqXnStiB8nH9qMBYI/AuLHMckDzkeESH5rQ2q2+1RgCN82PujzGhhVnBMk95ZS9k9zKCvKQa2yzVkaHqwSESyOFboU89kLAEQ0h48dtoJ2FTBs9GjsL3Z4fGogeLwjIvP8I8JF39HI+9U3PC2KnicA/bgUL/Z1paDzZYTrqQS4QSyFgy4DOxYz";
private const string ValidHmac = "un/5uJOoOAyn4AX8VU0HsGYYtr79A40TFF1wVqd/jDQ=";
private readonly IEncryptionProvider fakeEncryptionProvider;
private readonly CookieBasedSessions cookieStore;
private readonly IHmacProvider fakeHmacProvider;
private readonly IObjectSerializer fakeObjectSerializer;
private RijndaelEncryptionProvider rijndaelEncryptionProvider;
private DefaultHmacProvider defaultHmacProvider;
private IObjectSerializer defaultObjectSerializer;
public CookieBasedSessionsFixture()
{
this.fakeEncryptionProvider = A.Fake<IEncryptionProvider>();
this.fakeHmacProvider = A.Fake<IHmacProvider>();
this.fakeObjectSerializer = new Fakes.FakeObjectSerializer();
this.cookieStore = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, this.fakeObjectSerializer);
this.rijndaelEncryptionProvider = new RijndaelEncryptionProvider(new PassphraseKeyGenerator("password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));
this.defaultHmacProvider = new DefaultHmacProvider(new PassphraseKeyGenerator("anotherpassword", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));
this.defaultObjectSerializer = new DefaultObjectSerializer();
}
[Fact]
public void Should_save_nothing_if_the_session_is_null()
{
var response = new Response();
cookieStore.Save(null, response);
response.Cookies.Count.ShouldEqual(0);
}
[Fact]
public void Should_save_nothing_if_the_session_has_not_changed()
{
var response = new Response();
cookieStore.Save(new Session(new Dictionary<string, object> { { "key", "value" } }), response);
response.Cookies.Count.ShouldEqual(0);
}
[Fact]
public void Should_save_the_session_cookie()
{
var response = new Response();
var session = new Session(new Dictionary<string, object>
{
{"key1", "val1"},
});
session["key2"] = "val2";
A.CallTo(() => this.fakeEncryptionProvider.Encrypt("key1=val1;key2=val2;")).Returns("encrypted=key1=val1;key2=val2;");
cookieStore.Save(session, response);
response.Cookies.Count.ShouldEqual(1);
var cookie = response.Cookies.First();
cookie.Name.ShouldEqual(this.cookieStore.CookieName);
cookie.Value.ShouldEqual("encrypted=key1=val1;key2=val2;");
cookie.Expires.ShouldBeNull();
cookie.Path.ShouldBeNull();
cookie.Domain.ShouldBeNull();
}
[Fact]
public void Should_save_cookie_as_http_only()
{
var response = new Response();
var session = new Session();
session["key 1"] = "val=1";
A.CallTo(() => this.fakeEncryptionProvider.Encrypt("key+1=val%3d1;")).Returns("encryptedkey+1=val%3d1;");
cookieStore.Save(session, response);
response.Cookies.First().HttpOnly.ShouldEqual(true);
}
[Fact]
public void Should_saves_url_safe_keys_and_values()
{
var response = new Response();
var session = new Session();
session["key 1"] = "val=1";
A.CallTo(() => this.fakeEncryptionProvider.Encrypt("key+1=val%3d1;")).Returns("encryptedkey+1=val%3d1;");
cookieStore.Save(session, response);
response.Cookies.First().Value.ShouldEqual("encryptedkey+1=val%3d1;");
}
[Fact]
public void Should_load_an_empty_session_if_no_session_cookie_exists()
{
var request = CreateRequest(null);
var result = cookieStore.Load(request);
result.Count.ShouldEqual(0);
}
[Fact]
public void Should_load_an_empty_session_if_session_cookie_is_invalid()
{
//given
var inputValue = ValidHmac.Substring(0, 5); //invalid Hmac
inputValue = HttpUtility.UrlEncode(inputValue);
var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);
var request = new Request("GET", "/", "http");
request.Cookies.Add(store.CookieName, inputValue);
//when
var result = store.Load(request);
//then
result.Count.ShouldEqual(0);
}
[Fact]
public void Should_load_a_single_valued_session()
{
var request = CreateRequest("encryptedkey1=value1");
A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
var session = cookieStore.Load(request);
session.Count.ShouldEqual(1);
session["key1"].ShouldEqual("value1");
}
[Fact]
public void Should_load_a_multi_valued_session()
{
var request = CreateRequest("encryptedkey1=value1;key2=value2");
A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1;key2=value2")).Returns("key1=value1;key2=value2");
var session = cookieStore.Load(request);
session.Count.ShouldEqual(2);
session["key1"].ShouldEqual("value1");
session["key2"].ShouldEqual("value2");
}
[Fact]
public void Should_load_properly_decode_the_url_safe_session()
{
var request = CreateRequest("encryptedkey+1=val%3d1;");
A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey+1=val%3d1;")).Returns("key+1=val%3d1;");
var session = cookieStore.Load(request);
session.Count.ShouldEqual(1);
session["key 1"].ShouldEqual("val=1");
}
[Fact]
public void Should_add_pre_and_post_hooks_when_enabled()
{
var beforePipeline = new BeforePipeline();
var afterPipeline = new AfterPipeline();
var hooks = A.Fake<IPipelines>();
A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider));
beforePipeline.PipelineDelegates.Count().ShouldEqual(1);
afterPipeline.PipelineItems.Count().ShouldEqual(1);
}
[Fact]
public void Should_only_not_add_response_cookie_if_it_has_not_changed()
{
var beforePipeline = new BeforePipeline();
var afterPipeline = new AfterPipeline();
var hooks = A.Fake<IPipelines>();
A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer);
var request = CreateRequest("encryptedkey1=value1");
A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
var response = A.Fake<Response>();
var nancyContext = new NancyContext() { Request = request, Response = response };
beforePipeline.Invoke(nancyContext, new CancellationToken());
afterPipeline.Invoke(nancyContext, new CancellationToken());
response.Cookies.Count.ShouldEqual(0);
}
[Fact]
public void Should_add_response_cookie_if_it_has_changed()
{
var beforePipeline = new BeforePipeline();
var afterPipeline = new AfterPipeline();
var hooks = A.Fake<IPipelines>();
A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer);
var request = CreateRequest("encryptedkey1=value1");
A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
var response = A.Fake<Response>();
var nancyContext = new NancyContext() { Request = request, Response = response };
beforePipeline.Invoke(nancyContext, new CancellationToken());
request.Session["Testing"] = "Test";
afterPipeline.Invoke(nancyContext, new CancellationToken());
response.Cookies.Count.ShouldEqual(1);
}
[Fact]
public void Should_call_formatter_on_load()
{
var fakeFormatter = A.Fake<IObjectSerializer>();
A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
var store = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, fakeFormatter);
var request = CreateRequest("encryptedkey1=value1", false);
store.Load(request);
A.CallTo(() => fakeFormatter.Deserialize("value1")).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_call_the_formatter_on_save()
{
var response = new Response();
var session = new Session(new Dictionary<string, object>());
session["key1"] = "value1";
var fakeFormatter = A.Fake<IObjectSerializer>();
var store = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, fakeFormatter);
store.Save(session, response);
A.CallTo(() => fakeFormatter.Serialize("value1")).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_set_formatter_when_using_formatter_selector()
{
var beforePipeline = new BeforePipeline();
var afterPipeline = new AfterPipeline();
var hooks = A.Fake<IPipelines>();
A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
var fakeFormatter = A.Fake<IObjectSerializer>();
A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(fakeFormatter);
var request = CreateRequest("encryptedkey1=value1");
var nancyContext = new NancyContext() { Request = request };
beforePipeline.Invoke(nancyContext, new CancellationToken());
A.CallTo(() => fakeFormatter.Deserialize(A<string>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_be_able_to_save_a_complex_object_to_session()
{
var response = new Response();
var session = new Session(new Dictionary<string, object>());
var payload = new DefaultSessionObjectFormatterFixture.Payload(27, true, "Test string");
var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);
session["testObject"] = payload;
store.Save(session, response);
response.Cookies.Count.ShouldEqual(1);
var cookie = response.Cookies.First();
cookie.Name.ShouldEqual(store.CookieName);
cookie.Value.ShouldNotBeNull();
cookie.Value.ShouldNotBeEmpty();
}
[Fact]
public void Should_be_able_to_load_an_object_previously_saved_to_session()
{
var response = new Response();
var session = new Session(new Dictionary<string, object>());
var payload = new DefaultSessionObjectFormatterFixture.Payload(27, true, "Test string");
var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);
session["testObject"] = payload;
store.Save(session, response);
var request = new Request("GET", "/", "http");
request.Cookies.Add(Helpers.HttpUtility.UrlEncode(response.Cookies.First().Name), Helpers.HttpUtility.UrlEncode(response.Cookies.First().Value));
var result = store.Load(request);
result["testObject"].ShouldEqual(payload);
}
[Fact]
public void Should_encrypt_data()
{
var response = new Response();
var session = new Session(new Dictionary<string, object>
{
{"key1", "val1"},
});
session["key2"] = "val2";
cookieStore.Save(session, response);
A.CallTo(() => this.fakeEncryptionProvider.Encrypt(A<string>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_generate_hmac()
{
var response = new Response();
var session = new Session(new Dictionary<string, object>
{
{"key1", "val1"},
});
session["key2"] = "val2";
cookieStore.Save(session, response);
A.CallTo(() => this.fakeHmacProvider.GenerateHmac(A<string>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_load_valid_test_data()
{
var inputValue = ValidHmac + ValidData;
inputValue = HttpUtility.UrlEncode(inputValue);
var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);
var request = new Request("GET", "/", "http");
request.Cookies.Add(store.CookieName, inputValue);
var result = store.Load(request);
result.Count.ShouldEqual(1);
result.First().Value.ShouldBeOfType(typeof(DefaultSessionObjectFormatterFixture.Payload));
}
[Fact]
public void Should_return_blank_session_if_hmac_changed()
{
var inputValue = "b" + ValidHmac.Substring(1) + ValidData;
inputValue = HttpUtility.UrlEncode(inputValue);
var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);
var request = new Request("GET", "/", "http");
request.Cookies.Add(store.CookieName, inputValue);
var result = store.Load(request);
result.Count.ShouldEqual(0);
}
[Fact]
public void Should_return_blank_session_if_hmac_missing()
{
var inputValue = ValidData;
inputValue = HttpUtility.UrlEncode(inputValue);
var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);
var request = new Request("GET", "/", "http");
request.Cookies.Add(store.CookieName, inputValue);
var result = store.Load(request);
result.Count.ShouldEqual(0);
}
[Fact]
public void Should_return_blank_session_if_encrypted_data_modified()
{
var inputValue = ValidHmac + ValidData.Substring(0, ValidData.Length - 1) + "Z";
inputValue = HttpUtility.UrlEncode(inputValue);
var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);
var request = new Request("GET", "/", "http");
request.Cookies.Add(store.CookieName, inputValue);
var result = store.Load(request);
result.Count.ShouldEqual(0);
}
[Fact]
public void Should_return_blank_session_if_encrypted_data_are_invalid_but_contain_semicolon_when_decrypted()
{
var bogusEncrypted = this.rijndaelEncryptionProvider.Encrypt("foo;bar");
var inputValue = ValidHmac + bogusEncrypted;
inputValue = HttpUtility.UrlEncode(inputValue);
var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);
var request = new Request("GET", "/", "http");
request.Cookies.Add(store.CookieName, inputValue);
var result = store.Load(request);
result.Count.ShouldEqual(0);
}
[Fact]
public void Should_use_CookieName_when_config_provides_cookiename_value()
{
//Given
var cryptoConfig = new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider);
var storeConfig = new CookieBasedSessionsConfiguration(cryptoConfig)
{
CookieName = "NamedCookie",
Serializer = this.fakeObjectSerializer
};
var store = new CookieBasedSessions(storeConfig);
//When
var response = new Response();
var session = new Session(new Dictionary<string, object>
{
{"key1", "val1"},
});
session["key2"] = "val2";
store.Save(session, response);
//Then
response.Cookies.ShouldHave(c => c.Name == storeConfig.CookieName);
}
[Fact]
public void Should_set_Domain_when_config_provides_domain_value()
{
//Given
var cryptoConfig = new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider);
var storeConfig = new CookieBasedSessionsConfiguration(cryptoConfig)
{
Domain = ".nancyfx.org",
Serializer = this.fakeObjectSerializer
};
var store = new CookieBasedSessions(storeConfig);
//When
var response = new Response();
var session = new Session(new Dictionary<string, object>
{
{"key1", "val1"},
});
session["key2"] = "val2";
store.Save(session, response);
//Then
var cookie = response.Cookies.First(c => c.Name == storeConfig.CookieName);
cookie.Domain.ShouldEqual(storeConfig.Domain);
}
[Fact]
public void Should_set_Path_when_config_provides_path_value()
{
//Given
var cryptoConfig = new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider);
var storeConfig = new CookieBasedSessionsConfiguration(cryptoConfig)
{
Path = "/",
Serializer = this.fakeObjectSerializer
};
var store = new CookieBasedSessions(storeConfig);
//When
var response = new Response();
var session = new Session(new Dictionary<string, object>
{
{"key1", "val1"},
});
session["key2"] = "val2";
store.Save(session, response);
//Then
var cookie = response.Cookies.First(c => c.Name == storeConfig.CookieName);
cookie.Path.ShouldEqual(storeConfig.Path);
}
private Request CreateRequest(string sessionValue, bool load = true)
{
var headers = new Dictionary<string, IEnumerable<string>>(1);
if (!string.IsNullOrEmpty(sessionValue))
{
headers.Add("cookie", new[] { this.cookieStore.CookieName+ "=" + HttpUtility.UrlEncode(sessionValue) });
}
var request = new Request("GET", new Url { Path = "/", Scheme = "http", Port = 9001, BasePath = "goku.power" }, CreateRequestStream(), headers);
if (load)
{
cookieStore.Load(request);
}
return request;
}
private static RequestStream CreateRequestStream()
{
return CreateRequestStream(new MemoryStream());
}
private static RequestStream CreateRequestStream(Stream stream)
{
return RequestStream.FromStream(stream, 0, 1, true);
}
}
}
| |
/*
* 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.Linq;
using NUnit.Framework;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Securities.Option;
namespace QuantConnect.Tests.Common
{
[TestFixture]
public class SymbolTests
{
[Theory]
[TestCaseSource(nameof(GetSymbolCreateTestCaseData))]
public void SymbolCreate(string ticker, SecurityType securityType, string market, Symbol expected)
{
Assert.AreEqual(Symbol.Create(ticker, securityType, market), expected);
}
private static TestCaseData[] GetSymbolCreateTestCaseData()
{
return new []
{
new TestCaseData("SPY", SecurityType.Equity, Market.USA, new Symbol(SecurityIdentifier.GenerateEquity("SPY", Market.USA), "SPY")),
new TestCaseData("EURUSD", SecurityType.Forex, Market.FXCM, new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD")),
new TestCaseData("SPY", SecurityType.Option, Market.USA, new Symbol(SecurityIdentifier.GenerateOption(SecurityIdentifier.DefaultDate, Symbols.SPY.ID, Market.USA, 0, default(OptionRight), default(OptionStyle)), "?SPY"))
};
}
[Test]
public void SymbolCreateBaseWithUnderlyingEquity()
{
var type = typeof(BaseData);
var equitySymbol = Symbol.Create("TWX", SecurityType.Equity, Market.USA);
var symbol = Symbol.CreateBase(type, equitySymbol, Market.USA);
var symbolIDSymbol = symbol.ID.Symbol.Split(new[] { ".BaseData" }, StringSplitOptions.None).First();
Assert.IsTrue(symbol.SecurityType == SecurityType.Base);
Assert.IsTrue(symbol.HasUnderlying);
Assert.AreEqual(symbol.Underlying, equitySymbol);
Assert.AreEqual(symbol.ID.Date, new DateTime(1998, 1, 2));
Assert.AreEqual("AOL", symbolIDSymbol);
Assert.AreEqual(symbol.Underlying.ID.Symbol, symbolIDSymbol);
Assert.AreEqual(symbol.Underlying.ID.Date, symbol.ID.Date);
Assert.AreEqual(symbol.Underlying.Value, equitySymbol.Value);
Assert.AreEqual(symbol.Underlying.Value, symbol.Value);
}
[Test]
public void SymbolCreateBaseWithUnderlyingOption()
{
var type = typeof(BaseData);
var optionSymbol = Symbol.CreateOption("TWX", Market.USA, OptionStyle.American, OptionRight.Call, 100, new DateTime(2050, 12, 31));
var symbol = Symbol.CreateBase(type, optionSymbol, Market.USA);
var symbolIDSymbol = symbol.ID.Symbol.Split(new[] { ".BaseData" }, StringSplitOptions.None).First();
Assert.IsTrue(symbol.SecurityType == SecurityType.Base);
Assert.IsTrue(symbol.HasUnderlying);
Assert.AreEqual(symbol.Underlying, optionSymbol);
Assert.IsTrue(symbol.Underlying.HasUnderlying);
Assert.AreEqual(symbol.Underlying.Underlying.SecurityType, SecurityType.Equity);
Assert.AreEqual(new DateTime(2050, 12, 31), symbol.ID.Date);
Assert.AreEqual("AOL", symbolIDSymbol);
Assert.AreEqual(symbol.Underlying.ID.Symbol, symbolIDSymbol);
Assert.AreEqual(symbol.Underlying.ID.Date, symbol.ID.Date);
Assert.AreEqual(symbol.Underlying.Value, symbol.Value);
Assert.AreEqual(symbol.Underlying.Underlying.ID.Symbol, symbolIDSymbol);
Assert.AreNotEqual(symbol.Underlying.Underlying.ID.Date, symbol.ID.Date);
Assert.IsTrue(symbol.Value.StartsWith(symbol.Underlying.Underlying.Value));
Assert.AreEqual(symbol.Underlying.Underlying.ID.Symbol, symbol.Underlying.ID.Symbol);
Assert.AreNotEqual(symbol.Underlying.Underlying.ID.Date, symbol.Underlying.ID.Date);
Assert.IsTrue(symbol.Underlying.Value.StartsWith(symbol.Underlying.Underlying.Value));
}
[Test]
public void SymbolCreateWithOptionSecurityTypeCreatesCanonicalOptionSymbol()
{
var symbol = Symbol.Create("SPY", SecurityType.Option, Market.USA);
var sid = symbol.ID;
Assert.AreEqual(SecurityIdentifier.DefaultDate, sid.Date);
Assert.AreEqual(0m, sid.StrikePrice);
Assert.AreEqual(default(OptionRight), sid.OptionRight);
Assert.AreEqual(default(OptionStyle), sid.OptionStyle);
}
[Test]
public void CanonicalOptionSymbolAliasHasQuestionMark()
{
var symbol = Symbol.Create("SPY", SecurityType.Option, Market.USA);
Assert.AreEqual("?SPY", symbol.Value);
}
[Test]
public void UsesSidForDictionaryKey()
{
var sid = SecurityIdentifier.GenerateEquity("SPY", Market.USA);
var dictionary = new Dictionary<Symbol, int>
{
{new Symbol(sid, "value"), 1}
};
var key = new Symbol(sid, "other value");
Assert.IsTrue(dictionary.ContainsKey(key));
}
[Test]
public void CreatesOptionWithUnderlying()
{
var option = Symbol.CreateOption("XLRE", Market.USA, OptionStyle.American, OptionRight.Call, 21m, new DateTime(2016, 08, 19));
Assert.AreEqual(option.ID.Date, new DateTime(2016, 08, 19));
Assert.AreEqual(option.ID.StrikePrice, 21m);
Assert.AreEqual(option.ID.OptionRight, OptionRight.Call);
Assert.AreEqual(option.ID.OptionStyle, OptionStyle.American);
Assert.AreEqual(option.Underlying.ID.Symbol, "XLRE");
}
[Test]
public void CompareToItselfReturnsZero()
{
var sym = new Symbol(SecurityIdentifier.GenerateForex("sym", Market.FXCM), "sym");
Assert.AreEqual(0, sym.CompareTo(sym));
}
[Test]
public void ComparesTheSameAsStringCompare()
{
var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a");
var z = new Symbol(SecurityIdentifier.GenerateForex("z", Market.FXCM), "z");
Assert.AreEqual(string.Compare("a", "z", StringComparison.Ordinal), a.CompareTo(z));
Assert.AreEqual(string.Compare("z", "a", StringComparison.Ordinal), z.CompareTo(a));
}
[Test]
public void ComparesTheSameAsStringCompareAndIgnoresCase()
{
var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a");
var z = new Symbol(SecurityIdentifier.GenerateForex("z", Market.FXCM), "z");
Assert.AreEqual(string.Compare("a", "Z", StringComparison.OrdinalIgnoreCase), a.CompareTo(z));
Assert.AreEqual(string.Compare("z", "A", StringComparison.OrdinalIgnoreCase), z.CompareTo(a));
}
[Test]
public void ComparesAgainstStringWithoutException()
{
var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a");
Assert.AreEqual(0, a.CompareTo("a"));
}
[Test]
public void ComparesAgainstStringIgnoringCase()
{
var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a");
Assert.AreEqual(0, a.CompareTo("A"));
}
[Test]
public void EqualsAgainstNullOrEmpty()
{
var validSymbol = Symbols.SPY;
var emptySymbol = Symbol.Empty;
var emptySymbolInstance = new Symbol(SecurityIdentifier.Empty, string.Empty);
Symbol nullSymbol = null;
Assert.IsTrue(emptySymbol.Equals(nullSymbol));
Assert.IsTrue(Symbol.Empty.Equals(nullSymbol));
Assert.IsTrue(emptySymbolInstance.Equals(nullSymbol));
Assert.IsTrue(emptySymbol.Equals(emptySymbol));
Assert.IsTrue(Symbol.Empty.Equals(emptySymbol));
Assert.IsTrue(emptySymbolInstance.Equals(emptySymbol));
Assert.IsFalse(validSymbol.Equals(nullSymbol));
Assert.IsFalse(validSymbol.Equals(emptySymbol));
Assert.IsFalse(validSymbol.Equals(emptySymbolInstance));
Assert.IsFalse(Symbol.Empty.Equals(validSymbol));
}
[Test]
public void ComparesAgainstNullOrEmpty()
{
var validSymbol = Symbols.SPY;
var emptySymbol = Symbol.Empty;
Symbol nullSymbol = null;
Assert.IsTrue(nullSymbol == emptySymbol);
Assert.IsFalse(nullSymbol != emptySymbol);
Assert.IsTrue(emptySymbol == nullSymbol);
Assert.IsFalse(emptySymbol != nullSymbol);
Assert.IsTrue(validSymbol != null);
Assert.IsTrue(emptySymbol == null);
Assert.IsTrue(nullSymbol == null);
Assert.IsFalse(validSymbol == null);
Assert.IsFalse(emptySymbol != null);
Assert.IsFalse(nullSymbol != null);
Assert.IsTrue(validSymbol != Symbol.Empty);
Assert.IsTrue(emptySymbol == Symbol.Empty);
Assert.IsTrue(nullSymbol == Symbol.Empty);
Assert.IsFalse(validSymbol == Symbol.Empty);
Assert.IsFalse(emptySymbol != Symbol.Empty);
Assert.IsFalse(nullSymbol != Symbol.Empty);
Assert.IsTrue(null != validSymbol);
Assert.IsTrue(null == emptySymbol);
Assert.IsTrue(null == nullSymbol);
Assert.IsFalse(null == validSymbol);
Assert.IsFalse(null != emptySymbol);
Assert.IsFalse(null != nullSymbol);
Assert.IsTrue(Symbol.Empty != validSymbol);
Assert.IsTrue(Symbol.Empty == emptySymbol);
Assert.IsTrue(Symbol.Empty == nullSymbol);
Assert.IsFalse(Symbol.Empty == validSymbol);
Assert.IsFalse(Symbol.Empty != emptySymbol);
Assert.IsFalse(Symbol.Empty != nullSymbol);
}
[Test]
public void ImplicitOperatorsAreInverseFunctions()
{
#pragma warning disable 0618 // This test requires implicit operators
var eurusd = new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD");
string stringEurusd = eurusd;
Symbol symbolEurusd = stringEurusd;
Assert.AreEqual(eurusd, symbolEurusd);
#pragma warning restore 0618
}
[Test]
public void ImplicitOperatorsReturnSIDOnFailure()
{
#pragma warning disable 0618 // This test requires implicit operators
// this doesn't exist in the symbol cache
var eurusd = new Symbol(SecurityIdentifier.GenerateForex("NOT-A-SECURITY", Market.FXCM), "EURUSD");
string stringEurusd = eurusd;
Assert.AreEqual(eurusd.ID.ToString(), stringEurusd);
Assert.Throws<ArgumentException>(() =>
{
Symbol symbol = "this will not resolve to a proper Symbol instance";
});
Symbol notASymbol = "NotASymbol";
Assert.AreNotEqual(Symbol.Empty, notASymbol);
Assert.IsTrue(notASymbol.ToString().Contains("NotASymbol"));
#pragma warning restore 0618
}
[Test]
public void ImplicitFromStringChecksSymbolCache()
{
#pragma warning disable 0618 // This test requires implicit operators
SymbolCache.Set("EURUSD", Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM));
string ticker = "EURUSD";
Symbol actual = ticker;
var expected = SymbolCache.GetSymbol(ticker);
Assert.AreEqual(expected, actual);
SymbolCache.Clear();
#pragma warning restore 0618
}
[Test]
public void ImplicitFromStringParsesSid()
{
#pragma warning disable 0618 // This test requires implicit operators
SymbolCache.Set("EURUSD", Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM));
var expected = SymbolCache.GetSymbol("EURUSD");
string sid = expected.ID.ToString();
Symbol actual = sid;
Assert.AreEqual(expected, actual);
SymbolCache.Clear();
#pragma warning restore 0618
}
[Test]
public void ImplicitFromWithinStringLiftsSecondArgument()
{
#pragma warning disable 0618 // This test requires implicit operators
SymbolCache.Clear();
SymbolCache.Set("EURUSD", Symbols.EURUSD);
var expected = SymbolCache.GetSymbol("EURUSD");
string stringValue = expected;
string notFound = "EURGBP 8G";
var expectedNotFoundSymbol = Symbols.EURGBP;
string sid = expected.ID.ToString();
Symbol actual = sid;
if (!(expected == stringValue))
{
Assert.Fail("Failed expected == string");
}
else if (!(stringValue == expected))
{
Assert.Fail("Failed string == expected");
}
else if (expected != stringValue)
{
Assert.Fail("Failed expected != string");
}
else if (stringValue != expected)
{
Assert.Fail("Failed string != expected");
}
Symbol notFoundSymbol = notFound;
Assert.AreEqual(expectedNotFoundSymbol, notFoundSymbol);
SymbolCache.Clear();
#pragma warning restore 0618
}
[Test]
public void TestIfWeDetectCorrectlyWeekliesAndStandardOptionsBeforeFeb2015()
{
var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2012, 09, 22));
var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2012, 09, 07));
Assert.True(OptionSymbol.IsStandard(symbol));
Assert.False(OptionSymbol.IsStandard(weeklySymbol));
Assert.AreEqual(new DateTime(2012, 09, 21)/*Friday*/, OptionSymbol.GetLastDayOfTrading(symbol));
Assert.AreEqual(new DateTime(2012, 09, 07)/*Friday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol));
}
[Test]
public void TestIfWeDetectCorrectlyWeekliesAndStandardOptionsAfterFeb2015()
{
var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2016, 02, 19));
var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2016, 02, 05));
Assert.True(OptionSymbol.IsStandard(symbol));
Assert.False(OptionSymbol.IsStandard(weeklySymbol));
Assert.AreEqual(new DateTime(2016, 02, 19)/*Friday*/, OptionSymbol.GetLastDayOfTrading(symbol));
Assert.AreEqual(new DateTime(2016, 02, 05)/*Friday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol));
}
[Test]
public void TestIfWeDetectCorrectlyWeeklies()
{
var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 10));
var monthlysymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 17));
Assert.True(OptionSymbol.IsWeekly(weeklySymbol));
Assert.False(OptionSymbol.IsWeekly(monthlysymbol));
Assert.AreEqual(new DateTime(2020, 04, 17)/*Friday*/, OptionSymbol.GetLastDayOfTrading(monthlysymbol));
//Good Friday on 10th so should be 9th
Assert.AreEqual(new DateTime(2020, 04, 09)/*Thursday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol));
}
[Test]
public void HasUnderlyingSymbolReturnsTrueWhenSpecifyingCorrectUnderlying()
{
Assert.IsTrue(Symbols.SPY_C_192_Feb19_2016.HasUnderlyingSymbol(Symbols.SPY));
}
[Test]
public void HasUnderlyingSymbolReturnsFalsWhenSpecifyingIncorrectUnderlying()
{
Assert.IsFalse(Symbols.SPY_C_192_Feb19_2016.HasUnderlyingSymbol(Symbols.AAPL));
}
[Test]
public void TestIfFridayLastTradingDayIsHolidaysThenMoveToPreviousThursday()
{
var saturdayAfterGoodFriday = new DateTime(2014, 04, 19);
var thursdayBeforeGoodFriday = saturdayAfterGoodFriday.AddDays(-2);
var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, saturdayAfterGoodFriday);
Assert.AreEqual(thursdayBeforeGoodFriday, OptionSymbol.GetLastDayOfTrading(symbol));
}
[TestCase("ES", "ES")]
[TestCase("GC", "OG")]
[TestCase("ZT", "OZT")]
public void FutureOptionsWithDifferentUnderlyingGlobexTickersAreMapped(string futureTicker, string expectedFutureOptionTicker)
{
var future = Symbol.CreateFuture(futureTicker, Market.CME, DateTime.UtcNow.Date);
var canonicalFutureOption = Symbol.CreateOption(
future,
Market.CME,
default(OptionStyle),
default(OptionRight),
default(decimal),
SecurityIdentifier.DefaultDate);
var nonCanonicalFutureOption = Symbol.CreateOption(
future,
Market.CME,
default(OptionStyle),
default(OptionRight),
default(decimal),
new DateTime(2020, 12, 18));
Assert.AreEqual(canonicalFutureOption.Underlying.ID.Symbol, futureTicker);
Assert.AreEqual(canonicalFutureOption.ID.Symbol, expectedFutureOptionTicker);
Assert.IsTrue(canonicalFutureOption.Value.StartsWith("?" + futureTicker));
Assert.AreEqual(nonCanonicalFutureOption.Underlying.ID.Symbol, futureTicker);
Assert.AreEqual(nonCanonicalFutureOption.ID.Symbol, expectedFutureOptionTicker);
Assert.IsTrue(nonCanonicalFutureOption.Value.StartsWith(expectedFutureOptionTicker));
}
[Test]
public void SymbolWithSidContainingUnderlyingCreatedWithoutNullUnderlying()
{
var future = Symbol.CreateFuture("ES", Market.CME, new DateTime(2020, 6, 19));
var optionSid = SecurityIdentifier.GenerateOption(
future.ID.Date,
future.ID,
future.ID.Market,
3500m,
OptionRight.Call,
OptionStyle.American);
var option = new Symbol(optionSid, "ES");
Assert.IsNotNull(option.Underlying);
Assert.AreEqual(future, option.Underlying);
}
[TestCase("CL XKJAZ588SI4H", "CL", "CL21F21")] // Future
[TestCase("CL JL", "CL", "/CL")] // Canonical Future
[TestCase("ES 1S4 | ES XLDTU1KH5XC1", "CL", "?ES21F21")] // Future Option Canonical
[TestCase("ES XKGCMV4QK9VO | ES XLDTU1KH5XC1", "ES", "ES21F21 201218C00000000")] // Future Option
[TestCase("SPY 2U | SPY R735QTJ8XC9X", "SPY", "?SPY")] // Option Canonical
[TestCase("GOOCV 305RBQ2BZBZT2 | GOOCV VP83T1ZUHROL", "GOOCV", "GOOCV 151224P00750000")] // Option
[TestCase("SPY R735QTJ8XC9X", "SPY", "SPY")] // Equity
[TestCase("EURGBP 8G", "EURGBP", "EURGBP")] // Forex
[TestCase("BTCUSD XJ", "BTCUSD", "BTCUSD")] // Crypto
public void SymbolAlias(string identifier, string ticker, string expectedValue)
{
var symbol = new Symbol(SecurityIdentifier.Parse(identifier), ticker);
Assert.AreEqual(expectedValue, symbol.Value);
}
[TestCase("CL XKJAZ588SI4H", "CL", "CL21F21")] // Future
[TestCase("CL JL", "CL", "/CL")] // Canonical Future
[TestCase("ES 1S4 | ES XLDTU1KH5XC1", "ES", "?ES21F21")] // Future Option Canonical
[TestCase("ES XKGCMV4QK9VO | ES XLDTU1KH5XC1", "ES", "ES21F21 201218C00000000")] // Future Option
[TestCase("SPY 2U | SPY R735QTJ8XC9X", "SPY", "?SPY")] // Option Canonical
[TestCase("GOOCV 305RBQ2BZBZT2 | GOOCV VP83T1ZUHROL", "GOOCV", "GOOCV 151224P00750000")] // Option
[TestCase("SPY R735QTJ8XC9X", "SPY", null)] // Equity
[TestCase("EURGBP 8G", "EURGBP", null)] // Forex
[TestCase("BTCUSD XJ", "BTCUSD", null)] // Crypto
public void SymbolCanonical(string identifier, string ticker, string expectedValue)
{
var symbol = new Symbol(SecurityIdentifier.Parse(identifier), ticker);
if (expectedValue != null)
{
var result = symbol.Canonical;
Assert.IsNotNull(result);
Assert.AreSame(result, symbol.Canonical);
Assert.IsTrue(result.IsCanonical());
Assert.IsTrue(result.Value.Contains(ticker));
Assert.AreEqual(symbol.SecurityType, result.SecurityType);
Assert.AreEqual(symbol.ID.Market, result.ID.Market);
}
else
{
Assert.Throws<InvalidOperationException>(() =>
{
var canonical = symbol.Canonical;
});
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Timers;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using OpenMetaverse;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Avatar.Chat
{
public class IRCConnector
{
#region Global (static) state
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Local constants
private static readonly Vector3 CenterOfRegion = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 20);
private static readonly char[] CS_SPACE = { ' ' };
private const int WD_INTERVAL = 1000; // base watchdog interval
private static int PING_PERIOD = 15; // WD intervals per PING
private static int ICCD_PERIOD = 10; // WD intervals between Connects
private static int L_TIMEOUT = 25; // Login time out interval
private static int _idk_ = 0; // core connector identifier
private static int _pdk_ = 0; // ping interval counter
private static int _icc_ = ICCD_PERIOD; // IRC connect counter
// List of configured connectors
private static List<IRCConnector> m_connectors = new List<IRCConnector>();
// Watchdog state
private static System.Timers.Timer m_watchdog = null;
// The watch-dog gets started as soon as the class is instantiated, and
// ticks once every second (WD_INTERVAL)
static IRCConnector()
{
m_log.DebugFormat("[IRC-Connector]: Static initialization started");
m_watchdog = new System.Timers.Timer(WD_INTERVAL);
m_watchdog.Elapsed += new ElapsedEventHandler(WatchdogHandler);
m_watchdog.AutoReset = true;
m_watchdog.Start();
m_log.DebugFormat("[IRC-Connector]: Static initialization complete");
}
#endregion
#region Instance state
// Connector identity
internal int idn = _idk_++;
// How many regions depend upon this connection
// This count is updated by the ChannelState object and reflects the sum
// of the region clients associated with the set of associated channel
// state instances. That's why it cannot be managed here.
internal int depends = 0;
// This variable counts the number of resets that have been performed
// on the connector. When a listener thread terminates, it checks to
// see of the reset count has changed before it schedules another
// reset.
internal int m_resetk = 0;
// Working threads
private Thread m_listener = null;
private Object msyncConnect = new Object();
internal bool m_randomizeNick = true; // add random suffix
internal string m_baseNick = null; // base name for randomizing
internal string m_nick = null; // effective nickname
public string Nick // Public property
{
get { return m_nick; }
set { m_nick = value; }
}
private bool m_enabled = false; // connector enablement
public bool Enabled
{
get { return m_enabled; }
}
private bool m_connected = false; // connection status
private bool m_pending = false; // login disposition
private int m_timeout = L_TIMEOUT; // login timeout counter
public bool Connected
{
get { return m_connected; }
}
private string m_ircChannel; // associated channel id
public string IrcChannel
{
get { return m_ircChannel; }
set { m_ircChannel = value; }
}
private uint m_port = 6667; // session port
public uint Port
{
get { return m_port; }
set { m_port = value; }
}
private string m_server = null; // IRC server name
public string Server
{
get { return m_server; }
set { m_server = value; }
}
private string m_password = null;
public string Password
{
get { return m_password; }
set { m_password = value; }
}
private string m_user = "USER OpenSimBot 8 * :I'm an OpenSim to IRC bot";
public string User
{
get { return m_user; }
}
// Network interface
private TcpClient m_tcp;
private NetworkStream m_stream = null;
private StreamReader m_reader;
private StreamWriter m_writer;
// Channel characteristic info (if available)
internal string usermod = String.Empty;
internal string chanmod = String.Empty;
internal string version = String.Empty;
internal bool motd = false;
#endregion
#region connector instance management
internal IRCConnector(ChannelState cs)
{
// Prepare network interface
m_tcp = null;
m_writer = null;
m_reader = null;
// Setup IRC session parameters
m_server = cs.Server;
m_password = cs.Password;
m_baseNick = cs.BaseNickname;
m_randomizeNick = cs.RandomizeNickname;
m_ircChannel = cs.IrcChannel;
m_port = cs.Port;
m_user = cs.User;
if (m_watchdog == null)
{
// Non-differentiating
ICCD_PERIOD = cs.ConnectDelay;
PING_PERIOD = cs.PingDelay;
// Smaller values are not reasonable
if (ICCD_PERIOD < 5)
ICCD_PERIOD = 5;
if (PING_PERIOD < 5)
PING_PERIOD = 5;
_icc_ = ICCD_PERIOD; // get started right away!
}
// The last line of defense
if (m_server == null || m_baseNick == null || m_ircChannel == null || m_user == null)
throw new Exception("Invalid connector configuration");
// Generate an initial nickname if randomizing is enabled
if (m_randomizeNick)
{
m_nick = m_baseNick + Util.RandomClass.Next(1, 99);
}
m_log.InfoFormat("[IRC-Connector-{0}]: Initialization complete", idn);
}
~IRCConnector()
{
m_watchdog.Stop();
Close();
}
// Mark the connector as connectable. Harmless if already enabled.
public void Open()
{
if (!m_enabled)
{
if (!Connected)
{
Connect();
}
lock (m_connectors)
m_connectors.Add(this);
m_enabled = true;
}
}
// Only close the connector if the dependency count is zero.
public void Close()
{
m_log.InfoFormat("[IRC-Connector-{0}] Closing", idn);
lock (msyncConnect)
{
if ((depends == 0) && Enabled)
{
m_enabled = false;
if (Connected)
{
m_log.DebugFormat("[IRC-Connector-{0}] Closing interface", idn);
// Cleanup the IRC session
try
{
m_writer.WriteLine(String.Format("QUIT :{0} to {1} wormhole to {2} closing",
m_nick, m_ircChannel, m_server));
m_writer.Flush();
}
catch (Exception) {}
m_connected = false;
try { m_writer.Close(); } catch (Exception) {}
try { m_reader.Close(); } catch (Exception) {}
try { m_stream.Close(); } catch (Exception) {}
try { m_tcp.Close(); } catch (Exception) {}
}
lock (m_connectors)
m_connectors.Remove(this);
}
}
m_log.InfoFormat("[IRC-Connector-{0}] Closed", idn);
}
#endregion
#region session management
// Connect to the IRC server. A connector should always be connected, once enabled
public void Connect()
{
if (!m_enabled)
return;
// Delay until next WD cycle if this is too close to the last start attempt
while (_icc_ < ICCD_PERIOD)
return;
m_log.DebugFormat("[IRC-Connector-{0}]: Connection request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel);
lock (msyncConnect)
{
_icc_ = 0;
try
{
if (m_connected) return;
m_connected = true;
m_pending = true;
m_timeout = L_TIMEOUT;
m_tcp = new TcpClient(m_server, (int)m_port);
m_stream = m_tcp.GetStream();
m_reader = new StreamReader(m_stream);
m_writer = new StreamWriter(m_stream);
m_log.InfoFormat("[IRC-Connector-{0}]: Connected to {1}:{2}", idn, m_server, m_port);
m_listener = new Thread(new ThreadStart(ListenerRun));
m_listener.Name = "IRCConnectorListenerThread";
m_listener.IsBackground = true;
m_listener.Start();
ThreadTracker.Add(m_listener);
// This is the message order recommended by RFC 2812
if (m_password != null)
m_writer.WriteLine(String.Format("PASS {0}", m_password));
m_writer.WriteLine(String.Format("NICK {0}", m_nick));
m_writer.Flush();
m_writer.WriteLine(m_user);
m_writer.Flush();
m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel));
m_writer.Flush();
m_log.InfoFormat("[IRC-Connector-{0}]: {1} has asked to join {2}", idn, m_nick, m_ircChannel);
}
catch (Exception e)
{
m_log.ErrorFormat("[IRC-Connector-{0}] cannot connect {1} to {2}:{3}: {4}",
idn, m_nick, m_server, m_port, e.Message);
// It might seem reasonable to reset connected and pending status here
// Seeing as we know that the login has failed, but if we do that, then
// connection will be retried each time the interconnection interval
// expires. By leaving them as they are, the connection will be retried
// when the login timeout expires. Which is preferred.
}
}
return;
}
// Reconnect is used to force a re-cycle of the IRC connection. Should generally
// be a transparent event
public void Reconnect()
{
m_log.DebugFormat("[IRC-Connector-{0}]: Reconnect request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel);
// Don't do this if a Connect is in progress...
lock (msyncConnect)
{
if (m_connected)
{
m_log.InfoFormat("[IRC-Connector-{0}] Resetting connector", idn);
// Mark as disconnected. This will allow the listener thread
// to exit if still in-flight.
// The listener thread is not aborted - it *might* actually be
// the thread that is running the Reconnect! Instead just close
// the socket and it will disappear of its own accord, once this
// processing is completed.
try { m_writer.Close(); } catch (Exception) {}
try { m_reader.Close(); } catch (Exception) {}
try { m_tcp.Close(); } catch (Exception) {}
m_connected = false;
m_pending = false;
m_resetk++;
}
}
Connect();
}
#endregion
#region Outbound (to-IRC) message handlers
public void PrivMsg(string pattern, string from, string region, string msg)
{
// m_log.DebugFormat("[IRC-Connector-{0}] PrivMsg to IRC from {1}: <{2}>", idn, from,
// String.Format(pattern, m_ircChannel, from, region, msg));
// One message to the IRC server
try
{
m_writer.WriteLine(pattern, m_ircChannel, from, region, msg);
m_writer.Flush();
// m_log.DebugFormat("[IRC-Connector-{0}]: PrivMsg from {1} in {2}: {3}", idn, from, region, msg);
}
catch (IOException)
{
m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg I/O Error: disconnected from IRC server", idn);
Reconnect();
}
catch (Exception ex)
{
m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg exception : {1}", idn, ex.Message);
m_log.Debug(ex);
}
}
public void Send(string msg)
{
// m_log.DebugFormat("[IRC-Connector-{0}] Send to IRC : <{1}>", idn, msg);
try
{
m_writer.WriteLine(msg);
m_writer.Flush();
// m_log.DebugFormat("[IRC-Connector-{0}] Sent command string: {1}", idn, msg);
}
catch (IOException)
{
m_log.ErrorFormat("[IRC-Connector-{0}] Disconnected from IRC server.(Send)", idn);
Reconnect();
}
catch (Exception ex)
{
m_log.ErrorFormat("[IRC-Connector-{0}] Send exception trap: {0}", idn, ex.Message);
m_log.Debug(ex);
}
}
#endregion
public void ListenerRun()
{
string inputLine;
int resetk = m_resetk;
try
{
while (m_enabled && m_connected)
{
if ((inputLine = m_reader.ReadLine()) == null)
throw new Exception("Listener input socket closed");
// m_log.Info("[IRCConnector]: " + inputLine);
if (inputLine.Contains("PRIVMSG"))
{
Dictionary<string, string> data = ExtractMsg(inputLine);
// Any chat ???
if (data != null)
{
OSChatMessage c = new OSChatMessage();
c.Message = data["msg"];
c.Type = ChatTypeEnum.Region;
c.Position = CenterOfRegion;
c.From = data["nick"];
c.Sender = null;
c.SenderUUID = UUID.Zero;
// Is message "\001ACTION foo bar\001"?
// Then change to: "/me foo bar"
if ((1 == c.Message[0]) && c.Message.Substring(1).StartsWith("ACTION"))
c.Message = String.Format("/me {0}", c.Message.Substring(8, c.Message.Length - 9));
ChannelState.OSChat(this, c, false);
}
}
else
{
ProcessIRCCommand(inputLine);
}
}
}
catch (Exception /*e*/)
{
// m_log.ErrorFormat("[IRC-Connector-{0}]: ListenerRun exception trap: {1}", idn, e.Message);
// m_log.Debug(e);
}
// This is potentially circular, but harmless if so.
// The connection is marked as not connected the first time
// through reconnect.
if (m_enabled && (m_resetk == resetk))
Reconnect();
}
private Regex RE = new Regex(@":(?<nick>[\w-]*)!(?<user>\S*) PRIVMSG (?<channel>\S+) :(?<msg>.*)",
RegexOptions.Multiline);
private Dictionary<string, string> ExtractMsg(string input)
{
//examines IRC commands and extracts any private messages
// which will then be reboadcast in the Sim
// m_log.InfoFormat("[IRC-Connector-{0}]: ExtractMsg: {1}", idn, input);
Dictionary<string, string> result = null;
MatchCollection matches = RE.Matches(input);
// Get some direct matches $1 $4 is a
if ((matches.Count == 0) || (matches.Count != 1) || (matches[0].Groups.Count != 5))
{
// m_log.Info("[IRCConnector]: Number of matches: " + matches.Count);
// if (matches.Count > 0)
// {
// m_log.Info("[IRCConnector]: Number of groups: " + matches[0].Groups.Count);
// }
return null;
}
result = new Dictionary<string, string>();
result.Add("nick", matches[0].Groups[1].Value);
result.Add("user", matches[0].Groups[2].Value);
result.Add("channel", matches[0].Groups[3].Value);
result.Add("msg", matches[0].Groups[4].Value);
return result;
}
public void BroadcastSim(string sender, string format, params string[] args)
{
try
{
OSChatMessage c = new OSChatMessage();
c.From = sender;
c.Message = String.Format(format, args);
c.Type = ChatTypeEnum.Region; // ChatTypeEnum.Say;
c.Position = CenterOfRegion;
c.Sender = null;
c.SenderUUID = UUID.Zero;
ChannelState.OSChat(this, c, true);
}
catch (Exception ex) // IRC gate should not crash Sim
{
m_log.ErrorFormat("[IRC-Connector-{0}]: BroadcastSim Exception Trap: {1}\n{2}", idn, ex.Message, ex.StackTrace);
}
}
#region IRC Command Handlers
public void ProcessIRCCommand(string command)
{
string[] commArgs;
string c_server = m_server;
string pfx = String.Empty;
string cmd = String.Empty;
string parms = String.Empty;
// ":" indicates that a prefix is present
// There are NEVER more than 17 real
// fields. A parameter that starts with
// ":" indicates that the remainder of the
// line is a single parameter value.
commArgs = command.Split(CS_SPACE,2);
if (commArgs[0].StartsWith(":"))
{
pfx = commArgs[0].Substring(1);
commArgs = commArgs[1].Split(CS_SPACE,2);
}
cmd = commArgs[0];
parms = commArgs[1];
// m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}>", idn, pfx, cmd);
switch (cmd)
{
// Messages 001-004 are always sent
// following signon.
case "001" : // Welcome ...
case "002" : // Server information
case "003" : // Welcome ...
break;
case "004" : // Server information
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
commArgs = parms.Split(CS_SPACE);
c_server = commArgs[1];
m_server = c_server;
version = commArgs[2];
usermod = commArgs[3];
chanmod = commArgs[4];
break;
case "005" : // Server information
break;
case "042" :
case "250" :
case "251" :
case "252" :
case "254" :
case "255" :
case "265" :
case "266" :
case "332" : // Subject
case "333" : // Subject owner (?)
case "353" : // Name list
case "366" : // End-of-Name list marker
case "372" : // MOTD body
case "375" : // MOTD start
// m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
break;
case "376" : // MOTD end
// m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
motd = true;
break;
case "451" : // Not registered
break;
case "433" : // Nickname in use
// Gen a new name
m_nick = m_baseNick + Util.RandomClass.Next(1, 99);
m_log.ErrorFormat("[IRC-Connector-{0}]: [{1}] IRC SERVER reports NicknameInUse, trying {2}", idn, cmd, m_nick);
// Retry
m_writer.WriteLine(String.Format("NICK {0}", m_nick));
m_writer.Flush();
m_writer.WriteLine(m_user);
m_writer.Flush();
m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel));
m_writer.Flush();
break;
case "479" : // Bad channel name, etc. This will never work, so disable the connection
m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] Connector disabled", idn, cmd);
m_enabled = false;
m_connected = false;
m_pending = false;
break;
case "NOTICE" :
// m_log.WarnFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
break;
case "ERROR" :
m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
if (parms.Contains("reconnect too fast"))
ICCD_PERIOD++;
m_pending = false;
Reconnect();
break;
case "PING" :
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
m_writer.WriteLine(String.Format("PONG {0}", parms));
m_writer.Flush();
break;
case "PONG" :
break;
case "JOIN":
if (m_pending)
{
m_log.InfoFormat("[IRC-Connector-{0}] [{1}] Connected", idn, cmd);
m_pending = false;
}
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcJoin(pfx, cmd, parms);
break;
case "PART":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcPart(pfx, cmd, parms);
break;
case "MODE":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcMode(pfx, cmd, parms);
break;
case "NICK":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcNickChange(pfx, cmd, parms);
break;
case "KICK":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcKick(pfx, cmd, parms);
break;
case "QUIT":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcQuit(pfx, cmd, parms);
break;
default :
m_log.DebugFormat("[IRC-Connector-{0}] Command '{1}' ignored, parms = {2}", idn, cmd, parms);
break;
}
// m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}> complete", idn, pfx, cmd);
}
public void eventIrcJoin(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE,2);
string IrcUser = prefix.Split('!')[0];
string IrcChannel = args[0];
if (IrcChannel.StartsWith(":"))
IrcChannel = IrcChannel.Substring(1);
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCJoin {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(IrcUser, "/me joins {0}", IrcChannel);
}
public void eventIrcPart(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE,2);
string IrcUser = prefix.Split('!')[0];
string IrcChannel = args[0];
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCPart {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(IrcUser, "/me parts {0}", IrcChannel);
}
public void eventIrcMode(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE,2);
string UserMode = args[1];
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCMode {1}:{2}", idn, m_server, m_ircChannel);
if (UserMode.Substring(0, 1) == ":")
{
UserMode = UserMode.Remove(0, 1);
}
}
public void eventIrcNickChange(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE,2);
string UserOldNick = prefix.Split('!')[0];
string UserNewNick = args[0].Remove(0, 1);
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCNickChange {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(UserOldNick, "/me is now known as {0}", UserNewNick);
}
public void eventIrcKick(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE,3);
string UserKicker = prefix.Split('!')[0];
string IrcChannel = args[0];
string UserKicked = args[1];
string KickMessage = args[2];
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCKick {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(UserKicker, "/me kicks kicks {0} off {1} saying \"{2}\"", UserKicked, IrcChannel, KickMessage);
if (UserKicked == m_nick)
{
BroadcastSim(m_nick, "Hey, that was me!!!");
}
}
public void eventIrcQuit(string prefix, string command, string parms)
{
string IrcUser = prefix.Split('!')[0];
string QuitMessage = parms;
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCQuit {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(IrcUser, "/me quits saying \"{0}\"", QuitMessage);
}
#endregion
#region Connector Watch Dog
// A single watch dog monitors extant connectors and makes sure that they
// are re-connected as necessary. If a connector IS connected, then it is
// pinged, but only if a PING period has elapsed.
protected static void WatchdogHandler(Object source, ElapsedEventArgs args)
{
// m_log.InfoFormat("[IRC-Watchdog] Status scan, pdk = {0}, icc = {1}", _pdk_, _icc_);
_pdk_ = (_pdk_+1)%PING_PERIOD; // cycle the ping trigger
_icc_++; // increment the inter-consecutive-connect-delay counter
lock (m_connectors)
foreach (IRCConnector connector in m_connectors)
{
// m_log.InfoFormat("[IRC-Watchdog] Scanning {0}", connector);
if (connector.Enabled)
{
if (!connector.Connected)
{
try
{
// m_log.DebugFormat("[IRC-Watchdog] Connecting {1}:{2}", connector.idn, connector.m_server, connector.m_ircChannel);
connector.Connect();
}
catch (Exception e)
{
m_log.ErrorFormat("[IRC-Watchdog] Exception on connector {0}: {1} ", connector.idn, e.Message);
}
}
else
{
if (connector.m_pending)
{
if (connector.m_timeout == 0)
{
m_log.ErrorFormat("[IRC-Watchdog] Login timed-out for connector {0}, reconnecting", connector.idn);
connector.Reconnect();
}
else
connector.m_timeout--;
}
// Being marked connected is not enough to ping. Socket establishment can sometimes take a long
// time, in which case the watch dog might try to ping the server before the socket has been
// set up, with nasty side-effects.
else if (_pdk_ == 0)
{
try
{
connector.m_writer.WriteLine(String.Format("PING :{0}", connector.m_server));
connector.m_writer.Flush();
}
catch (Exception e)
{
m_log.ErrorFormat("[IRC-PingRun] Exception on connector {0}: {1} ", connector.idn, e.Message);
m_log.Debug(e);
connector.Reconnect();
}
}
}
}
}
// m_log.InfoFormat("[IRC-Watchdog] Status scan completed");
}
#endregion
}
}
| |
#if UNITY_EDITOR
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
#define BEFORE_UNITY_4_3
#else
#define AFTER_UNITY_4_3
#endif
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using AtlasSize = Uni2DTextureAtlas.AtlasSize;
[CustomEditor(typeof(Uni2DTextureAtlas))]
public class Uni2DTextureAtlasInspector : Editor
{
private static bool ms_bTexturesFoldout = true;
private static bool ms_bGeneratedMaterialsFoldout = true;
private static bool ms_bGeneratedTexturesFoldout = true;
private static Material[ ] ms_oAtlasMaterials = null;
private static Texture2D[ ] ms_oAtlasTextures = null;
private static Queue<Uni2DTextureAtlas> ms_oAtlasesWithUnappliedSettings = new Queue<Uni2DTextureAtlas>( );
// On enable
void OnEnable( )
{
Uni2DTextureAtlas rAtlas = target as Uni2DTextureAtlas;
rAtlas.RevertSettings( );
ms_oAtlasMaterials = rAtlas.GetAllMaterials( );
ms_oAtlasTextures = rAtlas.GetAllAtlasTextures( );
}
// On destroy
void OnDisable( )
{
Uni2DTextureAtlas rAtlas = target as Uni2DTextureAtlas;
if( rAtlas.UnappliedSettings )
{
ms_oAtlasesWithUnappliedSettings.Enqueue( rAtlas );
EditorApplication.delayCall += Uni2DTextureAtlasInspector.AskAboutUnappliedSettings;
}
}
private static void AskAboutUnappliedSettings( )
{
if( ms_oAtlasesWithUnappliedSettings.Count > 0 )
{
Uni2DTextureAtlas rAtlas = ms_oAtlasesWithUnappliedSettings.Dequeue( );
bool bApply = EditorUtility.DisplayDialog( "Unapplied atlas settings",
"Unapplied settings for '"+ rAtlas.name + "'",
"Apply",
"Revert" );
if( bApply )
{
Uni2DTextureAtlasInspector.ApplySettings( rAtlas );
}
else
{
rAtlas.RevertSettings( );
}
}
}
// On inspector gui
public override void OnInspectorGUI( )
{
Uni2DTextureAtlas rAtlas = target as Uni2DTextureAtlas;
#if BEFORE_UNITY_4_3
EditorGUIUtility.LookLikeInspector( );
#endif
// Material override
EditorGUILayout.BeginVertical( );
{
rAtlas.materialOverride = (Material) EditorGUILayout.ObjectField( "Material Override", rAtlas.materialOverride, typeof( Material ), false );
rAtlas.maximumAtlasSize = (AtlasSize) EditorGUILayout.EnumPopup( "Maximum Atlas Size", rAtlas.maximumAtlasSize );
rAtlas.padding = EditorGUILayout.IntField( "Padding", rAtlas.padding );
rAtlas.padding = Mathf.Abs( rAtlas.padding );
// Texture to pack list
// Custom list GUI: displays Texture2D objects, handles asset GUIDs
serializedObject.Update( );
SerializedProperty rSerializedProperty_Textures = serializedObject.FindProperty( "textures" );
int iContainerIndex = 0;
EditorGUILayout.Space( );
while( true )
{
string oPropertyPath = rSerializedProperty_Textures.propertyPath;
string oPropertyName = rSerializedProperty_Textures.name;
bool bIsTextureContainer = oPropertyPath.Contains( "textures" );
// Indent
EditorGUI.indentLevel = rSerializedProperty_Textures.depth;
if( bIsTextureContainer )
{
if( oPropertyName == "textures" )
{
GUIContent oGUIContentTexturesLabel = new GUIContent( "Textures" );
Rect rFoldoutRect = GUILayoutUtility.GetRect( oGUIContentTexturesLabel, EditorStyles.foldout );
Event rCurrentEvent = Event.current;
switch( rCurrentEvent.type )
{
// Drag performed
case EventType.DragPerform:
{
// Check if dragged objects are inside the foldout rect
if( rFoldoutRect.Contains( rCurrentEvent.mousePosition ) )
{
// Accept and use the event
DragAndDrop.AcceptDrag( );
rCurrentEvent.Use( );
EditorGUIUtility.hotControl = 0;
DragAndDrop.activeControlID = 0;
// Add the textures to the current list
foreach( Object rDraggedObject in DragAndDrop.objectReferences )
{
if( rDraggedObject is Texture2D )
{
int iCurrentSize = rSerializedProperty_Textures.arraySize;
++rSerializedProperty_Textures.arraySize;
SerializedProperty rSerializedProperty_Data = rSerializedProperty_Textures.GetArrayElementAtIndex( iCurrentSize );
rSerializedProperty_Data = rSerializedProperty_Data.FindPropertyRelative( "m_oTextureGUID" );
rSerializedProperty_Data.stringValue = rDraggedObject != null
? Uni2DEditorUtils.GetUnityAssetGUID( (Texture2D) rDraggedObject )
: null;
}
}
}
}
break;
case EventType.DragUpdated:
{
if( rFoldoutRect.Contains( rCurrentEvent.mousePosition ) )
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
break;
}
EditorGUI.indentLevel = 0;
ms_bTexturesFoldout = EditorGUI.Foldout( rFoldoutRect, ms_bTexturesFoldout, oGUIContentTexturesLabel );
}
else if( oPropertyName == "data" )
{
SerializedProperty rSerializedProperty_TextureGUID = rSerializedProperty_Textures.FindPropertyRelative( "m_oTextureGUID" );
Texture2D rTexture = Uni2DEditorUtils.GetAssetFromUnityGUID<Texture2D>( rSerializedProperty_TextureGUID.stringValue );
EditorGUI.BeginChangeCheck( );
{
rTexture = (Texture2D) EditorGUILayout.ObjectField( "Element " + iContainerIndex, rTexture, typeof( Texture2D ), false );
++iContainerIndex;
}
if( EditorGUI.EndChangeCheck( ) )
{
rSerializedProperty_TextureGUID.stringValue = rTexture != null
? Uni2DEditorUtils.GetUnityAssetGUID( rTexture )
: null;
}
}
else
{
// Default draw of the property field
EditorGUILayout.PropertyField( rSerializedProperty_Textures );
}
}
if( rSerializedProperty_Textures.NextVisible( ms_bTexturesFoldout ) == false )
{
break;
}
}
serializedObject.ApplyModifiedProperties( );
EditorGUILayout.Space( );
EditorGUI.indentLevel = 0;
///// Generated assets section /////
// Materials
ms_bGeneratedMaterialsFoldout = EditorGUILayout.Foldout( ms_bGeneratedMaterialsFoldout, "Generated Materials" );
if( ms_bGeneratedMaterialsFoldout )
{
++EditorGUI.indentLevel;
{
if( ms_oAtlasMaterials.Length > 0 )
{
foreach( Material rAtlasMaterial in ms_oAtlasMaterials )
{
EditorGUILayout.BeginHorizontal( );
{
GUILayout.Space( 16.0f );
if( GUILayout.Button( EditorGUIUtility.ObjectContent( rAtlasMaterial, typeof( Material ) ), EditorStyles.label, GUILayout.ExpandWidth( false ), GUILayout.MaxWidth( 225.0f ), GUILayout.MaxHeight( 16.0f ) ) )
{
EditorGUIUtility.PingObject( rAtlasMaterial );
}
}
EditorGUILayout.EndHorizontal( );
}
}
else
{
EditorGUILayout.PrefixLabel( "(None)" );
}
}
--EditorGUI.indentLevel;
}
EditorGUILayout.Space( );
// Atlas textures
ms_bGeneratedTexturesFoldout = EditorGUILayout.Foldout( ms_bGeneratedTexturesFoldout, "Generated Textures" );
if( ms_bGeneratedTexturesFoldout )
{
++EditorGUI.indentLevel;
{
if( ms_oAtlasTextures.Length > 0 )
{
foreach( Texture2D rAtlasTexture in ms_oAtlasTextures )
{
EditorGUILayout.BeginHorizontal( );
{
GUILayout.Space( 16.0f );
if( GUILayout.Button( EditorGUIUtility.ObjectContent( rAtlasTexture, typeof( Texture2D ) ), EditorStyles.label, GUILayout.ExpandWidth( false ), GUILayout.MaxWidth( 225.0f ), GUILayout.MaxHeight( 16.0f ) ) )
{
EditorGUIUtility.PingObject( rAtlasTexture );
}
}
EditorGUILayout.EndHorizontal( );
}
}
else
{
EditorGUILayout.PrefixLabel( "(None)" );
}
}
--EditorGUI.indentLevel;
}
bool bUnappliedSettings = rAtlas.UnappliedSettings;
EditorGUI.BeginDisabledGroup( bUnappliedSettings == false );
{
// Apply/Revert
EditorGUILayout.BeginHorizontal( );
{
if(GUILayout.Button( "Apply" ) )
{
this.ApplySettings( );
}
if( GUILayout.Button( "Revert" ) )
{
rAtlas.RevertSettings( );
}
}
EditorGUILayout.EndHorizontal( );
}
EditorGUI.EndDisabledGroup();
// Generate
if( GUILayout.Button( "Force atlas regeneration" ) )
{
this.ApplySettings( );
}
}
EditorGUILayout.EndVertical( );
}
private void ApplySettings( )
{
if( target != null )
{
Uni2DTextureAtlas rAtlas = (Uni2DTextureAtlas) target;
Uni2DTextureAtlasInspector.ApplySettings( rAtlas );
ms_oAtlasMaterials = rAtlas.GetAllMaterials( );
ms_oAtlasTextures = rAtlas.GetAllAtlasTextures( );
}
}
private static void ApplySettings( Uni2DTextureAtlas a_rAtlas )
{
if( a_rAtlas.ApplySettings( ) == false )
{
EditorUtility.DisplayDialog( "Uni2D Texture Atlasing",
"Uni2D could not pack all the specified textures into '" + a_rAtlas.name + "'.\n"
+ "Please check the maximum allowed atlas size and the input textures.",
"OK" );
}
}
}
#endif
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.DataSourcesRaster;
using CustomRasterBuilder;
namespace RasterTest
{
public class ThumbnailBuilderTest
{
[STAThread]
public static void Main(string[] args)
{
ESRI.ArcGIS.esriSystem.AoInitialize aoInit;
#region Initialize Licensing
try
{
Console.WriteLine("Obtaining License");
ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
aoInit = new AoInitializeClass();
esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
Console.WriteLine("Ready with license");
}
catch (Exception exc)
{
// If it fails at this point, shutdown the test and ignore any subsequent errors.
Console.WriteLine(exc.Message);
return;
}
#endregion
try
{
#region Specify input directory and dataset name
// Specify where to create the File Gdb
string fgdbFolder = @"c:\temp\CustomRasterType";
// Specify the folder to add the data from
string dataSource = @"c:\data\RasterDatasets";
// Specify whether to DELETE the fgdbFolder and create it again (clearing it).
bool clearFGdbFolder = false;
// Specify whether to save the Custom Raster Type generated to an art file.
bool saveToArtFile = true;
// Specify the path and filename to save the custom type.
string customTypeFilePath = @"C:\temp\ThumbnailType.art";
#endregion
#region Raster Type Parameters
string rasterTypeName = @"Thumbnail Raster Dataset";
// Specify the file filter to use to add data (Optional)
string dataSourceFilter = "*.tif";
string rasterTypeProductFilter = @"";
string rasterTypeProductName = @"";
#endregion
TestThumbnailBuilder(rasterTypeName, rasterTypeProductFilter, rasterTypeProductName,
dataSource, dataSourceFilter, fgdbFolder, saveToArtFile, customTypeFilePath, clearFGdbFolder);
#region Shutdown
Console.WriteLine("Press any key...");
Console.ReadKey();
aoInit.Shutdown();
#endregion
}
catch (Exception exc)
{
#region Shutdown
Console.WriteLine("Exception Caught in Main: " + exc.Message);
Console.WriteLine("Failed.");
Console.WriteLine("Shutting down.");
Console.WriteLine("Press any key...");
Console.ReadKey();
// Shutdown License
aoInit.Shutdown();
#endregion
}
}
public static void TestThumbnailBuilder(string rasterTypeName, string rasterTypeProductFilter,
string rasterTypeProductName, string dataSource, string dataSourceFilter, string fgdbParentFolder,
bool saveToArt, string customTypeFilePath, bool clearGdbDirectory)
{
try
{
string[] rasterProductNames = rasterTypeProductName.Split(';');
string nameString = rasterTypeName.Replace(" ", "") + rasterTypeProductFilter.Replace(" ", "") +
rasterProductNames[0].Replace(" ", "");
#region Directory Declarations
string fgdbName = nameString + ".gdb";
string fgdbDir = fgdbParentFolder + "\\" + fgdbName;
string MosaicDatasetName = nameString + "MD";
#endregion
#region Global Declarations
IMosaicDataset theMosaicDataset = null;
IMosaicDatasetOperation theMosaicDatasetOperation = null;
IMosaicWorkspaceExtensionHelper mosaicExtHelper = null;
IMosaicWorkspaceExtension mosaicExt = null;
#endregion
#region Create File GDB
Console.WriteLine("Creating File GDB: " + fgdbName);
if (clearGdbDirectory)
{
try
{
Console.WriteLine("Emptying Gdb folder.");
System.IO.Directory.Delete(fgdbParentFolder, true);
System.IO.Directory.CreateDirectory(fgdbParentFolder);
}
catch (System.IO.IOException EX)
{
Console.WriteLine(EX.Message);
return;
}
}
// Create a File Gdb
Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
IWorkspaceFactory FgdbFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
FgdbFactory.Create(fgdbParentFolder,
fgdbName, null, 0);
#endregion
#region Create Mosaic Dataset
try
{
Console.WriteLine("Create Mosaic Dataset: " + MosaicDatasetName);
// Setup workspaces.
IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
IWorkspace fgdbWorkspace = workspaceFactory.OpenFromFile(fgdbDir, 0);
// Create Srs
ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
ISpatialReference mosaicSrs = spatialrefFactory.CreateProjectedCoordinateSystem(
(int)(esriSRProjCSType.esriSRProjCS_World_Mercator));
// Create the mosaic dataset creation parameters object.
ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass();
// Create the mosaic workspace extension helper class.
mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass();
// Find the right extension from the workspace.
mosaicExt = mosaicExtHelper.FindExtension(fgdbWorkspace);
// Use the extension to create a new mosaic dataset, supplying the
// spatial reference and the creation parameters object created above.
theMosaicDataset = mosaicExt.CreateMosaicDataset(MosaicDatasetName,
mosaicSrs, creationPars, "");
theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset);
}
catch (Exception exc)
{
Console.WriteLine("Error: Failed to create Mosaic Dataset : {0}.",
MosaicDatasetName + " " + exc.Message);
return;
}
#endregion
#region Create Custom Raster Type
Console.WriteLine("Preparing Raster Type");
// Create a Raster Type Name object.
IRasterTypeName theRasterTypeName = new RasterTypeNameClass();
// Assign the name of the Raster Type to the name object.
// The Name field accepts a path to an .art file as well
// the name for a built in Raster Type.
theRasterTypeName.Name = rasterTypeName;
// Use the Open function from the IName interface to get the Raster Type object.
IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open());
if (theRasterType == null)
{
Console.WriteLine("Error:Raster Type not found " + rasterTypeName);
return;
}
#endregion
#region Prepare Raster Type
// Set the URI Filter on the loaded raster type.
if (rasterTypeProductFilter != "")
{
// Get the supported URI filters from the raster type object using the
// raster type properties interface.
IArray mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters;
IItemURIFilter productFilter = null;
for (int i = 0; i < mySuppFilters.Count; ++i)
{
// Set the desired filter from the supported filters.
productFilter = (IItemURIFilter)mySuppFilters.get_Element(i);
if (productFilter.Name == rasterTypeProductFilter)
theRasterType.URIFilter = productFilter;
}
}
// Enable the correct templates in the raster type.
bool enableTemplate = false;
if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != ""))
{
// Get the supported item templates from the raster type.
IItemTemplateArray templateArray = theRasterType.ItemTemplates;
for (int i = 0; i < templateArray.Count; ++i)
{
// Go through the supported item templates and enable the ones needed.
IItemTemplate template = templateArray.get_Element(i);
enableTemplate = false;
for (int j = 0; j < rasterProductNames.Length; ++j)
if (template.Name == rasterProductNames[j])
enableTemplate = true;
if (enableTemplate)
template.Enabled = true;
else
template.Enabled = false;
}
}
((IRasterTypeProperties)theRasterType).DataSourceFilter = dataSourceFilter;
#endregion
#region Save Custom Raster Type
if (saveToArt)
{
IRasterTypeProperties rasterTypeProperties = (IRasterTypeProperties)theRasterType;
IRasterTypeEnvironment rasterTypeHelper = new RasterTypeEnvironmentClass();
rasterTypeProperties.Name = customTypeFilePath;
IMemoryBlobStream ipBlob = rasterTypeHelper.SaveRasterType(theRasterType);
ipBlob.SaveToFile(customTypeFilePath);
}
#endregion
#region Preparing Data Source Crawler
Console.WriteLine("Preparing Data Source Crawler");
// Create a new property set to specify crawler properties.
IPropertySet crawlerProps = new PropertySetClass();
// Specify a file filter
crawlerProps.SetProperty("Filter", dataSourceFilter);
// Specify whether to search subdirectories.
crawlerProps.SetProperty("Recurse", true);
// Specify the source path.
crawlerProps.SetProperty("Source", dataSource);
// Get the recommended crawler from the raster type based on the specified
// properties using the IRasterBuilder interface.
// Pass on the Thumbnailtype to the crawler...
IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps);
#endregion
#region Add Rasters
try
{
Console.WriteLine("Adding Rasters");
// Create a AddRaster parameters object.
IAddRastersParameters AddRastersArgs = new AddRastersParametersClass();
// Specify the data crawler to be used to crawl the data.
AddRastersArgs.Crawler = theCrawler;
// Specify the Thumbnail raster type to be used to add the data.
AddRastersArgs.RasterType = theRasterType;
// Use the mosaic dataset operation interface to add
// rasters to the mosaic dataset.
theMosaicDatasetOperation.AddRasters(AddRastersArgs, null);
}
catch (Exception ex)
{
Console.WriteLine("Error: Add raster Failed." + ex.Message);
return;
}
#endregion
#region Compute Pixel Size Ranges
Console.WriteLine("Computing Pixel Size Ranges.");
try
{
// Create a calculate cellsize ranges parameters object.
ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass();
// Use the mosaic dataset operation interface to calculate cellsize ranges.
theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null);
}
catch (Exception ex)
{
Console.WriteLine("Error: Compute Pixel Size Failed." + ex.Message);
return;
}
#endregion
#region Building Boundary
Console.WriteLine("Building Boundary");
try
{
// Create a build boundary parameters object.
IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass();
// Set flags that control boundary generation.
boundaryArgs.AppendToExistingBoundary = true;
// Use the mosaic dataset operation interface to build boundary.
theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null);
}
catch (Exception ex)
{
Console.WriteLine("Error: Build Boundary Failed." + ex.Message);
return;
}
#endregion
#region Report
Console.WriteLine("Successfully created MD: " + MosaicDatasetName + ". ");
#endregion
}
catch (Exception exc)
{
#region Report
Console.WriteLine("Exception Caught in TestThumbnailBuilder: " + exc.Message);
Console.WriteLine("Failed.");
Console.WriteLine("Shutting down.");
#endregion
}
}
}
}
| |
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 frmPackSize
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmPackSize() : base()
{
FormClosed += frmPackSize_FormClosed;
KeyPress += frmPackSize_KeyPress;
Resize += frmPackSize_Resize;
Load += frmPackSize_Load;
//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;
public System.Windows.Forms.TextBox _txtFields_2;
public System.Windows.Forms.TextBox _txtFields_1;
public System.Windows.Forms.TextBox _txtFloat_0;
public System.Windows.Forms.TextBox _txtFields_0;
private System.Windows.Forms.Button withEventsField_cmdCancel;
public System.Windows.Forms.Button cmdCancel {
get { return withEventsField_cmdCancel; }
set {
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click -= cmdCancel_Click;
}
withEventsField_cmdCancel = value;
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click += cmdCancel_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.Label _lblLabels_2;
public System.Windows.Forms.Label _lblLabels_1;
public System.Windows.Forms.Label _lblLabels_0;
public System.Windows.Forms.Label _lblLabels_38;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public System.Windows.Forms.Label _lbl_5;
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//Public WithEvents txtFloat As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
public RectangleShapeArray Shape1;
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()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPackSize));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this._txtFields_2 = new System.Windows.Forms.TextBox();
this._txtFields_1 = new System.Windows.Forms.TextBox();
this._txtFloat_0 = new System.Windows.Forms.TextBox();
this._txtFields_0 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this._lblLabels_2 = new System.Windows.Forms.Label();
this._lblLabels_1 = new System.Windows.Forms.Label();
this._lblLabels_0 = new System.Windows.Forms.Label();
this._lblLabels_38 = new System.Windows.Forms.Label();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._lbl_5 = new System.Windows.Forms.Label();
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
//Me.txtFloat = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
this.Shape1 = new RectangleShapeArray(components);
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtFloat, System.ComponentModel.ISupportInitialize).BeginInit()
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Edit Pack Size";
this.ClientSize = new System.Drawing.Size(455, 138);
this.Location = new System.Drawing.Point(73, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmPackSize";
this._txtFields_2.AutoSize = false;
this._txtFields_2.Size = new System.Drawing.Size(147, 19);
this._txtFields_2.Location = new System.Drawing.Point(292, 96);
this._txtFields_2.TabIndex = 10;
this._txtFields_2.AcceptsReturn = true;
this._txtFields_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this._txtFields_2.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_2.CausesValidation = true;
this._txtFields_2.Enabled = true;
this._txtFields_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_2.HideSelection = true;
this._txtFields_2.ReadOnly = false;
this._txtFields_2.MaxLength = 0;
this._txtFields_2.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_2.Multiline = false;
this._txtFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_2.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtFields_2.TabStop = true;
this._txtFields_2.Visible = true;
this._txtFields_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_2.Name = "_txtFields_2";
this._txtFields_1.AutoSize = false;
this._txtFields_1.Size = new System.Drawing.Size(91, 19);
this._txtFields_1.Location = new System.Drawing.Point(88, 96);
this._txtFields_1.TabIndex = 8;
this._txtFields_1.AcceptsReturn = true;
this._txtFields_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this._txtFields_1.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_1.CausesValidation = true;
this._txtFields_1.Enabled = true;
this._txtFields_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_1.HideSelection = true;
this._txtFields_1.ReadOnly = false;
this._txtFields_1.MaxLength = 0;
this._txtFields_1.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_1.Multiline = false;
this._txtFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_1.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtFields_1.TabStop = true;
this._txtFields_1.Visible = true;
this._txtFields_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_1.Name = "_txtFields_1";
this._txtFloat_0.AutoSize = false;
this._txtFloat_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtFloat_0.Size = new System.Drawing.Size(64, 19);
this._txtFloat_0.Location = new System.Drawing.Point(375, 66);
this._txtFloat_0.TabIndex = 3;
this._txtFloat_0.Text = "9,999.99";
this._txtFloat_0.AcceptsReturn = true;
this._txtFloat_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_0.CausesValidation = true;
this._txtFloat_0.Enabled = true;
this._txtFloat_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_0.HideSelection = true;
this._txtFloat_0.ReadOnly = false;
this._txtFloat_0.MaxLength = 0;
this._txtFloat_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_0.Multiline = false;
this._txtFloat_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_0.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtFloat_0.TabStop = true;
this._txtFloat_0.Visible = true;
this._txtFloat_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_0.Name = "_txtFloat_0";
this._txtFields_0.AutoSize = false;
this._txtFields_0.Size = new System.Drawing.Size(219, 19);
this._txtFields_0.Location = new System.Drawing.Point(87, 66);
this._txtFields_0.TabIndex = 1;
this._txtFields_0.AcceptsReturn = true;
this._txtFields_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this._txtFields_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_0.CausesValidation = true;
this._txtFields_0.Enabled = true;
this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_0.HideSelection = true;
this._txtFields_0.ReadOnly = false;
this._txtFields_0.MaxLength = 0;
this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_0.Multiline = false;
this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_0.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtFields_0.TabStop = true;
this._txtFields_0.Visible = true;
this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_0.Name = "_txtFields_0";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(455, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 6;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.Location = new System.Drawing.Point(5, 3);
this.cmdCancel.TabIndex = 5;
this.cmdCancel.TabStop = false;
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.CausesValidation = true;
this.cmdCancel.Enabled = true;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Name = "cmdCancel";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(372, 3);
this.cmdClose.TabIndex = 4;
this.cmdClose.TabStop = false;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Name = "cmdClose";
this._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_2.Text = "Container:";
this._lblLabels_2.Size = new System.Drawing.Size(48, 13);
this._lblLabels_2.Location = new System.Drawing.Point(239, 99);
this._lblLabels_2.TabIndex = 11;
this._lblLabels_2.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_2.Enabled = true;
this._lblLabels_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_2.UseMnemonic = true;
this._lblLabels_2.Visible = true;
this._lblLabels_2.AutoSize = true;
this._lblLabels_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_2.Name = "_lblLabels_2";
this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_1.Text = "Pack Type:";
this._lblLabels_1.Size = new System.Drawing.Size(55, 13);
this._lblLabels_1.Location = new System.Drawing.Point(28, 99);
this._lblLabels_1.TabIndex = 9;
this._lblLabels_1.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_1.Enabled = true;
this._lblLabels_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_1.UseMnemonic = true;
this._lblLabels_1.Visible = true;
this._lblLabels_1.AutoSize = true;
this._lblLabels_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_1.Name = "_lblLabels_1";
this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_0.Text = "Volume:";
this._lblLabels_0.Size = new System.Drawing.Size(38, 13);
this._lblLabels_0.Location = new System.Drawing.Point(332, 69);
this._lblLabels_0.TabIndex = 2;
this._lblLabels_0.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_0.Enabled = true;
this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_0.UseMnemonic = true;
this._lblLabels_0.Visible = true;
this._lblLabels_0.AutoSize = true;
this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_0.Name = "_lblLabels_0";
this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_38.Text = "Pack Name:";
this._lblLabels_38.Size = new System.Drawing.Size(59, 13);
this._lblLabels_38.Location = new System.Drawing.Point(23, 69);
this._lblLabels_38.TabIndex = 0;
this._lblLabels_38.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_38.Enabled = true;
this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_38.UseMnemonic = true;
this._lblLabels_38.Visible = true;
this._lblLabels_38.AutoSize = true;
this._lblLabels_38.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_38.Name = "_lblLabels_38";
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.Size = new System.Drawing.Size(430, 71);
this._Shape1_2.Location = new System.Drawing.Point(15, 60);
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_2.BorderWidth = 1;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_2.Visible = true;
this._Shape1_2.Name = "_Shape1_2";
this._lbl_5.BackColor = System.Drawing.Color.Transparent;
this._lbl_5.Text = "&1. General";
this._lbl_5.Size = new System.Drawing.Size(60, 13);
this._lbl_5.Location = new System.Drawing.Point(15, 45);
this._lbl_5.TabIndex = 7;
this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_5.Enabled = true;
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.UseMnemonic = true;
this._lbl_5.Visible = true;
this._lbl_5.AutoSize = true;
this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_5.Name = "_lbl_5";
this.Controls.Add(_txtFields_2);
this.Controls.Add(_txtFields_1);
this.Controls.Add(_txtFloat_0);
this.Controls.Add(_txtFields_0);
this.Controls.Add(picButtons);
this.Controls.Add(_lblLabels_2);
this.Controls.Add(_lblLabels_1);
this.Controls.Add(_lblLabels_0);
this.Controls.Add(_lblLabels_38);
this.ShapeContainer1.Shapes.Add(_Shape1_2);
this.Controls.Add(_lbl_5);
this.Controls.Add(ShapeContainer1);
this.picButtons.Controls.Add(cmdCancel);
this.picButtons.Controls.Add(cmdClose);
//Me.lbl.SetIndex(_lbl_5, CType(5, Short))
//Me.lblLabels.SetIndex(_lblLabels_2, CType(2, Short))
//Me.lblLabels.SetIndex(_lblLabels_1, CType(1, Short))
//Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short))
//Me.lblLabels.SetIndex(_lblLabels_38, CType(38, Short))
//Me.txtFields.SetIndex(_txtFields_2, CType(2, Short))
//Me.txtFields.SetIndex(_txtFields_1, CType(1, Short))
//Me.txtFields.SetIndex(_txtFields_0, CType(0, Short))
//Me.txtFloat.SetIndex(_txtFloat_0, CType(0, Short))
this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2));
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
//CType(Me.txtFloat, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using Frapid.ApplicationState;
using Frapid.ApplicationState.CacheFactory;
using Frapid.Configuration;
using Serilog;
namespace Frapid.Areas.Caching
{
public sealed class FileOutputCacheAttribute : ActionFilterAttribute
{
private HttpContext _currentContext;
private StringWriter _writer;
public FileOutputCacheAttribute()
{
this.Factory = new DefaultCacheFactory();
}
private ICacheFactory Factory { get; }
private bool IsValid(string url)
{
if (this.Duration <= 0)
{
Log.Information("The file output cache on url \"{url}\" has an invalid duration: {Duration}.", url,
this.Duration);
return false;
}
return true;
}
private void Initialize()
{
string profile = this.ProfileName;
if (string.IsNullOrWhiteSpace(profile))
{
return;
}
string tenant = TenantConvention.GetTenant();
var config = CacheConfig.Get(tenant, profile);
if (config == null)
{
return;
}
this.Duration = config.Duration;
this.Location = config.Location;
this.NoStore = config.NoStore;
this.VaryByCustom = config.VaryByCustom;
}
private string GetCacheKey(ControllerContext context)
{
var request = context.RequestContext.HttpContext.Request;
if (request?.Url != null)
{
Log.Verbose("Getting cache key for the current request: {Url}.", request.Url);
var locator = TenantConvention.GetTenantLocator();
string defaultTenant = TenantConvention.GetDefaultTenantName();
var keyGen = new CacheKeyGenerator(request.Url, locator, defaultTenant);
string key = keyGen.Generate();
Log.Verbose("The cache key for the current request is {key}.", key);
return key;
}
Log.Verbose("Cannot get the cache key for the current request because the Request context is null.");
return null;
}
private bool IsServerCachingEnabled()
{
switch (this.Location)
{
case OutputCacheLocation.Any:
case OutputCacheLocation.Server:
case OutputCacheLocation.ServerAndClient:
return true;
}
Log.Verbose(
"Server caching is not enabled on the current context with file output cache location: {Location}.",
this.Location);
return false;
}
private BinaryCacheItem GetCacheItemByKey(string key)
{
return this.Factory.Get<BinaryCacheItem>(key);
}
private void SetCacheItemByKey(string key, BinaryCacheItem item, DateTimeOffset expiresOn)
{
this.Factory.Add(key, item, expiresOn);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
this.Initialize();
string url = filterContext.HttpContext.Request.Url?.ToString();
if (this.IsServerCachingEnabled() && this.IsValid(url))
{
string key = this.GetCacheKey(filterContext);
Log.Verbose("Fetching the cached item by key: {key}.", key);
var binaryCache = this.GetCacheItemByKey(key);
if (binaryCache != null)
{
Log.Verbose("Returning the cached item {key} with content type {ContentType}.", key,
binaryCache.ContentType);
filterContext.HttpContext.Response.BinaryWrite(binaryCache.Data);
filterContext.HttpContext.Response.ContentType = binaryCache.ContentType;
Log.Verbose("Cancelling the result excution context. Cache key: {key}.", key);
filterContext.Cancel = true;
}
else
{
Log.Verbose("The cache item {key} was not found.", key);
Log.Verbose("Replacing the current context with a new string writer context.");
this._currentContext = HttpContext.Current;
this._writer = new StringWriter();
var response = new HttpResponse(this._writer);
var context = new HttpContext(this._currentContext.Request, response)
{
User = this._currentContext.User
};
Log.Verbose("Copying all context items.");
// Copy all items in the context (especially done for session availability in the component)
foreach (var itemKey in this._currentContext.Items.Keys)
{
Log.Verbose("Copying the context item with key: {itemKey}.", itemKey);
context.Items[itemKey] = this._currentContext.Items[itemKey];
}
Log.Verbose("Setting current HttpContext with new string writer context.");
HttpContext.Current = context;
}
this.RegisterHeaders(HttpContext.Current.Response);
}
}
private HttpCacheability GetHttpCacheability()
{
var cacheability = HttpCacheability.NoCache;
switch (this.Location)
{
case OutputCacheLocation.Any:
case OutputCacheLocation.Downstream:
cacheability = HttpCacheability.Public;
break;
case OutputCacheLocation.Client:
case OutputCacheLocation.ServerAndClient:
cacheability = HttpCacheability.Private;
break;
}
return cacheability;
}
private void RegisterHeaders(HttpResponse response)
{
var cacheability = this.GetHttpCacheability();
response.Cache.SetCacheability(cacheability);
if (this.NoTransform)
{
response.Cache.SetNoTransforms();
}
if (!string.IsNullOrWhiteSpace(this.VaryByCustom))
{
response.Cache.SetVaryByCustom(this.VaryByCustom);
}
response.Cache.SetSlidingExpiration(this.SlidingExpiration);
if (cacheability != HttpCacheability.NoCache)
{
if (this.Duration > 0)
{
response.Cache.SetExpires(DateTime.Now.AddSeconds(this.Duration));
response.Cache.SetMaxAge(new TimeSpan(0, 0, this.Duration));
response.Cache.SetProxyMaxAge(new TimeSpan(0, 0, this.Duration));
}
}
if (this.NoStore)
{
response.Cache.SetNoStore();
}
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
this.Initialize();
if (this.IsServerCachingEnabled())
{
string key = this.GetCacheKey(filterContext);
Log.Verbose("Server side caching is enabled.");
Log.Verbose("Restoring current context with our string writer context.");
HttpContext.Current = this._currentContext;
Log.Verbose("Writing the rendered data.");
this._currentContext.Response.Write(this._writer.ToString());
Log.Verbose(
"Trying to create an instance of BinaryCacheItem item with key {key} to store in the cache.", key);
var item = this.CreateCacheItem(this._currentContext, filterContext);
if (item != null)
{
Log.Verbose("Adding BinaryCacheItem with key \"{key}\" to cache store.", key);
this.SetCacheItemByKey(key, item, DateTimeOffset.Now.AddSeconds(this.Duration));
return;
}
Log.Verbose(
"Could not store the BinaryCacheItem because the instance of item with key \"{key}\" was null.", key);
this.RegisterHeaders(HttpContext.Current.Response);
}
}
private BinaryCacheItem CreateCacheItem(HttpContext httpContext, ResultExecutedContext resultContext)
{
Log.Verbose("Trying to get binary file contents from current context.");
var result = resultContext.Result as FileContentResult;
if (result != null)
{
string contentType = httpContext.Response.ContentType;
Log.Verbose("Creating a new instance of \"BinaryCacheItem\" of MIME type: {contentType}.", contentType);
return new BinaryCacheItem
{
Data = result.FileContents,
ContentType = contentType
};
}
Log.Verbose(
"Could not get binary file contents because the current context result is not of type \"FileContentResult\".");
return null;
}
#region Properties
/// <summary>
/// Gets or sets the file output cache duration, in seconds.
/// </summary>
public int Duration { get; set; }
public bool NoTransform { get; set; } = true;
public bool SlidingExpiration { get; set; } = true;
/// <summary>
/// Gets or sets the file output cache location.
/// </summary>
public OutputCacheLocation Location { get; set; } = OutputCacheLocation.Any;
/// <summary>
/// Gets or sets the cache profile name.
/// </summary>
public string ProfileName { get; set; }
/// <summary>
/// Gets or sets a value that indicates whether to store the cache.
/// </summary>
public bool NoStore { get; set; }
/// <summary>
/// Gets or sets the vary-by-custom value.
/// </summary>
public string VaryByCustom { get; set; }
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Data;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
public class PGSQLEstateStore : IEstateDataStore
{
private const string _migrationStore = "EstateStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private PGSQLManager _Database;
private string m_connectionString;
private FieldInfo[] _Fields;
private Dictionary<string, FieldInfo> _FieldMap = new Dictionary<string, FieldInfo>();
#region Public methods
public PGSQLEstateStore()
{
}
public PGSQLEstateStore(string connectionString)
{
Initialise(connectionString);
}
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
/// <summary>
/// Initialises the estatedata class.
/// </summary>
/// <param name="connectionString">connectionString.</param>
public void Initialise(string connectionString)
{
if (!string.IsNullOrEmpty(connectionString))
{
m_connectionString = connectionString;
_Database = new PGSQLManager(connectionString);
}
//Migration settings
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "EstateStore");
m.Update();
}
//Interesting way to get parameters! Maybe implement that also with other types
Type t = typeof(EstateSettings);
_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in _Fields)
{
if (f.Name.Substring(0, 2) == "m_")
_FieldMap[f.Name.Substring(2)] = f;
}
}
/// <summary>
/// Loads the estate settings.
/// </summary>
/// <param name="regionID">region ID.</param>
/// <returns></returns>
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
string sql = "select estate_settings.\"" + String.Join("\",estate_settings.\"", FieldList) +
"\" from estate_map left join estate_settings on estate_map.\"EstateID\" = estate_settings.\"EstateID\" " +
" where estate_settings.\"EstateID\" is not null and \"RegionID\" = :RegionID";
bool insertEstate = false;
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("RegionID", regionID));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
foreach (string name in FieldList)
{
FieldInfo f = _FieldMap[name];
object v = reader[name];
if (f.FieldType == typeof(bool))
{
f.SetValue(es, v);
}
else if (f.FieldType == typeof(UUID))
{
UUID estUUID = UUID.Zero;
UUID.TryParse(v.ToString(), out estUUID);
f.SetValue(es, estUUID);
}
else if (f.FieldType == typeof(string))
{
f.SetValue(es, v.ToString());
}
else if (f.FieldType == typeof(UInt32))
{
f.SetValue(es, Convert.ToUInt32(v));
}
else if (f.FieldType == typeof(Single))
{
f.SetValue(es, Convert.ToSingle(v));
}
else
f.SetValue(es, v);
}
}
else
{
insertEstate = true;
}
}
}
if (insertEstate && create)
{
DoCreate(es);
LinkRegion(regionID, (int)es.EstateID);
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
//Set event
es.OnSave += StoreEstateSettings;
return es;
}
public EstateSettings CreateNewEstate()
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
DoCreate(es);
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
private void DoCreate(EstateSettings es)
{
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = string.Format("insert into estate_settings (\"{0}\") values ( :{1} )", String.Join("\",\"", names.ToArray()), String.Join(", :", names.ToArray()));
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand insertCommand = new NpgsqlCommand(sql, conn))
{
insertCommand.CommandText = sql;
foreach (string name in names)
{
insertCommand.Parameters.Add(_Database.CreateParameter("" + name, _FieldMap[name].GetValue(es)));
}
//NpgsqlParameter idParameter = new NpgsqlParameter("ID", SqlDbType.Int);
//idParameter.Direction = ParameterDirection.Output;
//insertCommand.Parameters.Add(idParameter);
conn.Open();
es.EstateID = 100;
if (insertCommand.ExecuteNonQuery() > 0)
{
insertCommand.CommandText = "Select cast(lastval() as int) as ID ;";
using (NpgsqlDataReader result = insertCommand.ExecuteReader())
{
if (result.Read())
{
es.EstateID = (uint)result.GetInt32(0);
}
}
}
}
//TODO check if this is needed??
es.Save();
}
/// <summary>
/// Stores the estate settings.
/// </summary>
/// <param name="es">estate settings</param>
public void StoreEstateSettings(EstateSettings es)
{
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = string.Format("UPDATE estate_settings SET ");
foreach (string name in names)
{
sql += "\"" + name + "\" = :" + name + ", ";
}
sql = sql.Remove(sql.LastIndexOf(","));
sql += " WHERE \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
foreach (string name in names)
{
cmd.Parameters.Add(_Database.CreateParameter("" + name, _FieldMap[name].GetValue(es)));
}
cmd.Parameters.Add(_Database.CreateParameter("EstateID", es.EstateID));
conn.Open();
cmd.ExecuteNonQuery();
}
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
#endregion
#region Private methods
private string[] FieldList
{
get { return new List<string>(_FieldMap.Keys).ToArray(); }
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
string sql = "select \"bannedUUID\" from estateban where \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
NpgsqlParameter idParameter = new NpgsqlParameter("EstateID", DbType.Int32);
idParameter.Value = es.EstateID;
cmd.Parameters.Add(idParameter);
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
EstateBan eb = new EstateBan();
eb.BannedUserID = new UUID((Guid)reader["bannedUUID"]); //uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
}
}
}
private UUID[] LoadUUIDList(uint estateID, string table)
{
List<UUID> uuids = new List<UUID>();
string sql = string.Format("select uuid from {0} where \"EstateID\" = :EstateID", table);
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("EstateID", estateID));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
uuids.Add(new UUID((Guid)reader["uuid"])); //uuid);
}
}
}
return uuids.ToArray();
}
private void SaveBanList(EstateSettings es)
{
//Delete first
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "delete from estateban where \"EstateID\" = :EstateID";
cmd.Parameters.AddWithValue("EstateID", (int)es.EstateID);
cmd.ExecuteNonQuery();
//Insert after
cmd.CommandText = "insert into estateban (\"EstateID\", \"bannedUUID\",\"bannedIp\", \"bannedIpHostMask\", \"bannedNameMask\") values ( :EstateID, :bannedUUID, '','','' )";
cmd.Parameters.AddWithValue("bannedUUID", Guid.Empty);
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters["bannedUUID"].Value = b.BannedUserID.Guid;
cmd.ExecuteNonQuery();
}
}
}
}
private void SaveUUIDList(uint estateID, string table, UUID[] data)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = conn.CreateCommand())
{
cmd.Parameters.AddWithValue("EstateID", (int)estateID);
cmd.CommandText = string.Format("delete from {0} where \"EstateID\" = :EstateID", table);
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format("insert into {0} (\"EstateID\", uuid) values ( :EstateID, :uuid )", table);
cmd.Parameters.AddWithValue("uuid", Guid.Empty);
foreach (UUID uuid in data)
{
cmd.Parameters["uuid"].Value = uuid.Guid; //.ToString(); //TODO check if this works
cmd.ExecuteNonQuery();
}
}
}
}
public EstateSettings LoadEstateSettings(int estateID)
{
EstateSettings es = new EstateSettings();
string sql = "select estate_settings.\"" + String.Join("\",estate_settings.\"", FieldList) + "\" from estate_settings where \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("EstateID", (int)estateID);
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
foreach (string name in FieldList)
{
FieldInfo f = _FieldMap[name];
object v = reader[name];
if (f.FieldType == typeof(bool))
{
f.SetValue(es, Convert.ToInt32(v) != 0);
}
else if (f.FieldType == typeof(UUID))
{
f.SetValue(es, new UUID((Guid)v)); // uuid);
}
else if (f.FieldType == typeof(string))
{
f.SetValue(es, v.ToString());
}
else if (f.FieldType == typeof(UInt32))
{
f.SetValue(es, Convert.ToUInt32(v));
}
else if (f.FieldType == typeof(Single))
{
f.SetValue(es, Convert.ToSingle(v));
}
else
f.SetValue(es, v);
}
}
}
}
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
//Set event
es.OnSave += StoreEstateSettings;
return es;
}
public List<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> allEstateSettings = new List<EstateSettings>();
List<int> allEstateIds = GetEstatesAll();
foreach (int estateId in allEstateIds)
allEstateSettings.Add(LoadEstateSettings(estateId));
return allEstateSettings;
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
string sql = "select \"EstateID\" from estate_settings where lower(\"EstateName\") = lower(:EstateName)";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("EstateName", search);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public List<int> GetEstatesAll()
{
List<int> result = new List<int>();
string sql = "select \"EstateID\" from estate_settings";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
string sql = "select \"estateID\" from estate_settings where \"EstateOwner\" = :EstateOwner";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("EstateOwner", ownerID);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
string deleteSQL = "delete from estate_map where \"RegionID\" = :RegionID";
string insertSQL = "insert into estate_map values (:RegionID, :EstateID)";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
NpgsqlTransaction transaction = conn.BeginTransaction();
try
{
using (NpgsqlCommand cmd = new NpgsqlCommand(deleteSQL, conn))
{
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("RegionID", regionID.Guid);
cmd.ExecuteNonQuery();
}
using (NpgsqlCommand cmd = new NpgsqlCommand(insertSQL, conn))
{
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("RegionID", regionID.Guid);
cmd.Parameters.AddWithValue("EstateID", estateID);
int ret = cmd.ExecuteNonQuery();
if (ret != 0)
transaction.Commit();
else
transaction.Rollback();
return (ret != 0);
}
}
catch (Exception ex)
{
m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message);
transaction.Rollback();
}
}
return false;
}
public List<UUID> GetRegions(int estateID)
{
List<UUID> result = new List<UUID>();
string sql = "select \"RegionID\" from estate_map where \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("EstateID", estateID);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(DBGuid.FromDB(reader["RegionID"]));
}
reader.Close();
}
}
}
return result;
}
public bool DeleteEstate(int estateID)
{
// TODO: Implementation!
return false;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Creating
{
public sealed class AtomicCreateResourceWithToManyRelationshipTests
: IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext;
private readonly OperationsFakers _fakers = new();
public AtomicCreateResourceWithToManyRelationshipTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OperationsController>();
// These routes need to be registered in ASP.NET for rendering links to resource/relationship endpoints.
testContext.UseController<PlaylistsController>();
testContext.UseController<MusicTracksController>();
}
[Fact]
public async Task Can_create_OneToMany_relationship()
{
// Arrange
List<Performer> existingPerformers = _fakers.Performer.Generate(2);
string newTitle = _fakers.MusicTrack.Generate().Title;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Performers.AddRange(existingPerformers);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
attributes = new
{
title = newTitle
},
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers",
id = existingPerformers[0].StringId
},
new
{
type = "performers",
id = existingPerformers[1].StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.Should().HaveCount(1);
responseDocument.Results[0].Data.SingleValue.Should().NotBeNull();
responseDocument.Results[0].Data.SingleValue.Type.Should().Be("musicTracks");
responseDocument.Results[0].Data.SingleValue.Attributes.Should().NotBeEmpty();
responseDocument.Results[0].Data.SingleValue.Relationships.Should().NotBeEmpty();
Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue.Id);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId);
trackInDatabase.Performers.Should().HaveCount(2);
trackInDatabase.Performers.Should().ContainSingle(performer => performer.Id == existingPerformers[0].Id);
trackInDatabase.Performers.Should().ContainSingle(performer => performer.Id == existingPerformers[1].Id);
});
}
[Fact]
public async Task Can_create_ManyToMany_relationship()
{
// Arrange
List<MusicTrack> existingTracks = _fakers.MusicTrack.Generate(3);
string newName = _fakers.Playlist.Generate().Name;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.AddRange(existingTracks);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "playlists",
attributes = new
{
name = newName
},
relationships = new
{
tracks = new
{
data = new[]
{
new
{
type = "musicTracks",
id = existingTracks[0].StringId
},
new
{
type = "musicTracks",
id = existingTracks[1].StringId
},
new
{
type = "musicTracks",
id = existingTracks[2].StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.Should().HaveCount(1);
responseDocument.Results[0].Data.SingleValue.Should().NotBeNull();
responseDocument.Results[0].Data.SingleValue.Type.Should().Be("playlists");
responseDocument.Results[0].Data.SingleValue.Attributes.Should().NotBeEmpty();
responseDocument.Results[0].Data.SingleValue.Relationships.Should().NotBeEmpty();
long newPlaylistId = long.Parse(responseDocument.Results[0].Data.SingleValue.Id);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(newPlaylistId);
playlistInDatabase.Tracks.Should().HaveCount(3);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[0].Id);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[1].Id);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[2].Id);
});
}
[Fact]
public async Task Cannot_create_for_missing_relationship_type()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = new[]
{
new
{
id = Unknown.StringId.For<Performer, int>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element.");
error.Detail.Should().Be("Expected 'type' element in 'performers' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_unknown_relationship_type()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = Unknown.ResourceType,
id = Unknown.StringId.For<Performer, int>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_missing_relationship_ID()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers"
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' or 'lid' element.");
error.Detail.Should().Be("Expected 'id' or 'lid' element in 'performers' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_unknown_relationship_IDs()
{
// Arrange
string newTitle = _fakers.MusicTrack.Generate().Title;
string performerId1 = Unknown.StringId.For<Performer, int>();
string performerId2 = Unknown.StringId.AltFor<Performer, int>();
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
attributes = new
{
title = newTitle
},
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers",
id = performerId1
},
new
{
type = "performers",
id = performerId2
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(2);
ErrorObject error1 = responseDocument.Errors[0];
error1.StatusCode.Should().Be(HttpStatusCode.NotFound);
error1.Title.Should().Be("A related resource does not exist.");
error1.Detail.Should().Be($"Related resource of type 'performers' with ID '{performerId1}' in relationship 'performers' does not exist.");
error1.Source.Pointer.Should().Be("/atomic:operations[0]");
ErrorObject error2 = responseDocument.Errors[1];
error2.StatusCode.Should().Be(HttpStatusCode.NotFound);
error2.Title.Should().Be("A related resource does not exist.");
error2.Detail.Should().Be($"Related resource of type 'performers' with ID '{performerId2}' in relationship 'performers' does not exist.");
error2.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_on_relationship_type_mismatch()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "playlists",
id = Unknown.StringId.For<Playlist, long>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Relationship contains incompatible resource type.");
error.Detail.Should().Be("Relationship 'performers' contains incompatible resource type 'playlists'.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Can_create_with_duplicates()
{
// Arrange
Performer existingPerformer = _fakers.Performer.Generate();
string newTitle = _fakers.MusicTrack.Generate().Title;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Performers.Add(existingPerformer);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
attributes = new
{
title = newTitle
},
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers",
id = existingPerformer.StringId
},
new
{
type = "performers",
id = existingPerformer.StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.Should().HaveCount(1);
responseDocument.Results[0].Data.SingleValue.Should().NotBeNull();
responseDocument.Results[0].Data.SingleValue.Type.Should().Be("musicTracks");
responseDocument.Results[0].Data.SingleValue.Attributes.Should().NotBeEmpty();
responseDocument.Results[0].Data.SingleValue.Relationships.Should().NotBeEmpty();
Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue.Id);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId);
trackInDatabase.Performers.Should().HaveCount(1);
trackInDatabase.Performers[0].Id.Should().Be(existingPerformer.Id);
});
}
[Fact]
public async Task Cannot_create_with_null_data_in_OneToMany_relationship()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = (object)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected data[] element for to-many relationship.");
error.Detail.Should().Be("Expected data[] element for 'performers' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_with_null_data_in_ManyToMany_relationship()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "playlists",
relationships = new
{
tracks = new
{
data = (object)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected data[] element for to-many relationship.");
error.Detail.Should().Be("Expected data[] element for 'tracks' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
}
}
| |
// Code sourced under MIT License from alphaleonis/AlphaVSS
using System;
using System.Collections.Generic;
using System.Linq;
using AlphaShadow.Options;
using System.Text;
using System.Diagnostics;
namespace AlphaShadow
{
public class ConsoleHost : IUIHost
{
private int m_indent = 0;
public ConsoleHost()
{
IsWordWrapEnabled = true;
}
public void WriteHeader(string message, params object[] args)
{
WriteLine(ConsoleColor.Cyan, WordWrap(message, args));
}
public void WriteLine(string message, params object[] args)
{
WriteLine(Console.ForegroundColor, WordWrap(message, args));
}
public void WriteWarning(string message, params object[] args)
{
WriteMessage(ConsoleColor.Red, "Warning:", message, args);
}
public void WriteError(string message, params object[] args)
{
WriteMessage(ConsoleColor.Red, "Error:", message, args);
}
public void WriteVerbose(string message, params object[] args)
{
if (VerboseOutputEnabled)
WriteLine(ConsoleColor.DarkGray, WordWrap(message, args));
}
private void WriteMessage(ConsoleColor color, string label, string message, params object[] args)
{
if (IsWordWrapEnabled)
{
int col1Width = label.Length;
int col2Width = Math.Max(1, Console.WindowWidth - col1Width - 2);
string text = StringFormatter.FormatInColumns(m_indent, 1,
new StringFormatter.ColumnInfo(col1Width, label),
new StringFormatter.ColumnInfo(col2Width, String.Format(message, args)));
WriteLine(color, text);
}
else
{
WriteLine(color, label + " " + String.Format(message, args));
}
}
private void WriteLine(ConsoleColor color, string message)
{
ConsoleColor temp = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(message);
Console.ForegroundColor = temp;
}
private string WordWrap(string message, params object[] args)
{
if (IsWordWrapEnabled)
{
StringBuilder sb = new StringBuilder();
string wrappedString = StringFormatter.WordWrap((args == null || args.Length == 0) ? message : String.Format(message, args), Console.WindowWidth - 5 - m_indent, StringFormatter.WordWrappingMethod.Greedy);
IList<string> splitString = StringFormatter.SplitAtLineBreaks(wrappedString);
for (int i = 0; i < splitString.Count; i++)
{
if (i != 0)
sb.AppendLine();
sb.Append(String.Format("{0}{1}", new String(' ', m_indent), splitString[i]));
}
return sb.ToString();
}
else
{
return new String(' ', m_indent) + String.Format(message, args);
}
}
public void WriteLine()
{
Console.WriteLine();
}
public bool VerboseOutputEnabled
{
get;
set;
}
public bool IsWordWrapEnabled { get; set; }
public void WriteTable(StringTable table, int columnSpacing = 3, bool addVerticalSeparation = false)
{
if (table == null)
throw new ArgumentNullException("table", "table is null.");
if (IsWordWrapEnabled)
{
int indent = m_indent;
if (indent >= Console.WindowWidth - columnSpacing - 2)
indent = 0;
int maxWidth = Console.WindowWidth - indent;
int col1Width = Math.Min(table.Labels.Max(text => text.Length), maxWidth / 2);
int colSpacing = columnSpacing;
int col2Width = maxWidth - col1Width - colSpacing - 1;
for (int i = 0; i < table.Count; i++)
{
if (i > 0 && addVerticalSeparation)
Console.WriteLine();
Console.WriteLine(
StringFormatter.FormatInColumns(indent, colSpacing,
new StringFormatter.ColumnInfo(col1Width, table.Labels[i]),
new StringFormatter.ColumnInfo(col2Width, table.Values[i])));
}
}
else
{
for (int i = 0; i < table.Count; i++)
{
Console.WriteLine("{0}{1}{2}{3}", new String(' ', m_indent), table.Labels[i], new String(' ', columnSpacing), table.Values[i]);
}
}
}
public void PushIndent()
{
m_indent += 3;
}
public void PopIndent()
{
m_indent -= 3;
if (m_indent < 0)
m_indent = 0;
}
public IDisposable GetIndent()
{
return new Indenter(this);
}
private class Indenter : IDisposable
{
IUIHost m_host;
public Indenter(IUIHost host)
{
m_host = host;
m_host.PushIndent();
}
public void Dispose()
{
m_host.PopIndent();
}
}
public void ExecCommand(string execCommand, string args)
{
WriteLine("- Executing command '{0}' ...", execCommand);
WriteLine("-----------------------------------------------------");
ProcessStartInfo ps = new ProcessStartInfo(execCommand, args);
ps.CreateNoWindow = false;
ps.UseShellExecute = false;
Process p = Process.Start(ps);
p.WaitForExit();
WriteLine("-----------------------------------------------------");
if (p.ExitCode != 0)
{
WriteError("Command line '{0}' failed!. Aborting the backup...", execCommand);
WriteError("Returned error code: {0}", p.ExitCode);
throw new CommandAbortedException();
}
}
public bool ShouldContinue()
{
WriteHeader("Continue? [Y/N]");
string response = Console.ReadLine();
return response.Equals("y", StringComparison.OrdinalIgnoreCase) || response.Equals("yes", StringComparison.OrdinalIgnoreCase);
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Text;
namespace LumiSoft.Net.Mime
{
/// <summary>
/// Mime entry.
/// </summary>
[Obsolete("Use Mime classes instead, this class will be removed !")]
public class MimeEntry
{
private string m_Headers = "";
private string m_ContentType = "";
private string m_CharSet = "";
private string m_ContentEncoding = "";
private byte[] m_Data = null;
private ArrayList m_Entries = null;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="mimeEntry"></param>
/// <param name="mime"></param>
public MimeEntry(byte[] mimeEntry,MimeParser mime)
{
MemoryStream entryStrm = new MemoryStream(mimeEntry);
m_Headers = MimeParser.ParseHeaders(entryStrm);
m_ContentType = mime.ParseContentType(m_Headers);
m_Entries = new ArrayList();
// != multipart content
if(m_ContentType.ToLower().IndexOf("multipart") == -1){
m_CharSet = ParseCharSet(m_Headers);
m_ContentEncoding = ParseEncoding(m_Headers);
m_Data = new byte[entryStrm.Length - entryStrm.Position];
entryStrm.Read(m_Data,0,m_Data.Length);
}
// multipart content, get nested entries
else{
long s = (int)entryStrm.Position;
string boundaryID = MimeParser.ParseHeaderFiledSubField("Content-Type:","boundary",m_Headers);
m_Entries = mime.ParseEntries(entryStrm,(int)entryStrm.Position,boundaryID);
entryStrm.Position = s;
m_Data = new byte[entryStrm.Length - s];
entryStrm.Read(m_Data,0,m_Data.Length);
}
}
#region function ParseCharSet
/// <summary>
/// Parse charset.
/// </summary>
/// <param name="headers"></param>
/// <returns></returns>
private string ParseCharSet(string headers)
{
string charset = MimeParser.ParseHeaderFiledSubField("Content-Type:","charset",headers);
// charset ends with ; remove it.
if(charset.EndsWith(";")){
charset = charset.Substring(0,charset.Length - 1);
}
if(charset.Length > 0){
try{
Encoding.GetEncoding(charset);
return charset;
}
catch{
return "ascii";
}
}
// If no charset, consider it as ascii
else{
return "ascii";
}
}
#endregion
#region function ParseEncoding
/// <summary>
/// Parse encoding. quoted-printable,7bit,8bit,base64 is supported.
/// </summary>
/// <param name="headers"></param>
/// <returns></returns>
private string ParseEncoding(string headers)
{
string encoding = MimeParser.ParseHeaderField("CONTENT-TRANSFER-ENCODING:",headers);
if(encoding.Length > 0){
return encoding;
}
// If no encoding, consider it as ascii
else{
return "7bit";
}
}
#endregion
#region function ParseContentDisposition
private Disposition ParseContentDisposition(string headers)
{
string disposition = MimeParser.ParseHeaderField("CONTENT-DISPOSITION:",headers);
if(disposition.ToUpper().IndexOf("ATTACHMENT") > -1){
return Disposition.Attachment;
}
if(disposition.ToUpper().IndexOf("INLINE") > -1){
return Disposition.Inline;
}
return Disposition.Unknown;
}
#endregion
#region function DecodeData
/// <summary>
/// Decode entry data.
/// </summary>
/// <param name="mimeDataEntry"></param>
/// <returns></returns>
private byte[] DecodeData(byte[] mimeDataEntry)
{
switch(m_ContentEncoding.ToLower())
{
case "quoted-printable":
if(m_ContentType.ToLower().IndexOf("text") > -1){
return Core.QuotedPrintableDecodeB(mimeDataEntry,true);
}
else{
return Core.QuotedPrintableDecodeB(mimeDataEntry,false);
}
// case "7bit":
// return mimeDataEntry;
// case "8bit":
// return mimeDataEntry;
case "base64":
string dataStr = Encoding.Default.GetString(mimeDataEntry);
if(dataStr.Trim().Length > 0){
return Convert.FromBase64String(dataStr);
}
else{
return new byte[]{};
}
default:
return mimeDataEntry;
}
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets content encoding.
/// </summary>
public string ContentEncoding
{
get{ return m_ContentEncoding; }
}
/// <summary>
/// Gets content type.
/// </summary>
public string ContentType
{
get{ return m_ContentType; }
}
/// <summary>
/// Gets content disposition type.
/// </summary>
public Disposition ContentDisposition
{
get{ return ParseContentDisposition(m_Headers); }
}
/// <summary>
/// Gets headers.
/// </summary>
public string Headers
{
get{ return m_Headers; }
}
/// <summary>
/// Gets file name. NOTE: available only if ContentDisposition.Attachment.
/// </summary>
public string FileName
{
get{ return Core.CanonicalDecode(MimeParser.ParseHeaderFiledSubField("Content-Disposition:","filename",m_Headers)); }
}
/// <summary>
/// Gets mime entry decoded data.
/// </summary>
public byte[] Data
{
get{ return DecodeData(m_Data); }
}
/// <summary>
/// Gets mime entry non decoded data.
/// </summary>
public byte[] DataNonDecoded
{
get{ return m_Data; }
}
/// <summary>
/// Gets string data. NOTE: available only if content-type=text/xxx.
/// </summary>
public string DataS
{
get{
try{
return Encoding.GetEncoding(m_CharSet).GetString(this.Data);
}
catch{
return Encoding.Default.GetString(this.Data);
}
}
}
/// <summary>
/// Gets nested mime entries.
/// </summary>
public ArrayList MimeEntries
{
get{ return m_Entries; }
}
#endregion
}
}
| |
// (c) Copyright Esri, 2010 - 2016
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.OSM.OSMClassExtension;
using ESRI.ArcGIS.Display;
using System.Text.RegularExpressions;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("ce7a2734-2414-4893-b4b2-88a78dde5527")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.OSMGPMultiLoader")]
public class OSMGPMultiLoader : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = String.Empty;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
int in_osmFileNumber, out_osmPointsNumber, out_osmLinesNumber, out_osmPolygonsNumber,
in_deleteSupportNodesNumber, in_deleteOSMSourceFileNumber, in_pointFieldNamesNumber,
in_lineFieldNamesNumber, in_polygonFieldNamesNumber;
Dictionary<string, string> m_editorConfigurationSettings = null;
public OSMGPMultiLoader()
{
osmGPFactory = new OSMGPFactory();
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
m_editorConfigurationSettings = OSMGPFactory.ReadOSMEditorSettings();
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return default(ESRI.ArcGIS.esriSystem.UID);
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_MultiLoaderName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
IFeatureClass osmPointFeatureClass = null;
IFeatureClass osmLineFeatureClass = null;
IFeatureClass osmPolygonFeatureClass = null;
OSMToolHelper osmToolHelper = null;
try
{
DateTime syncTime = DateTime.Now;
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
osmToolHelper = new OSMToolHelper();
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
IGPParameter osmFileParameter = paramvalues.get_Element(in_osmFileNumber) as IGPParameter;
IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue;
// ensure that the specified file does exist
bool osmFileExists = false;
try
{
osmFileExists = System.IO.File.Exists(osmFileLocationString.GetAsText());
}
catch (Exception ex)
{
message.AddError(120029, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_problemaccessingfile"), ex.Message));
return;
}
if (osmFileExists == false)
{
message.AddError(120030, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_osmfiledoesnotexist"), osmFileLocationString.GetAsText()));
return;
}
// determine the number of threads to be used
IGPEnvironment parallelProcessingFactorEnvironment = OSMToolHelper.getEnvironment(envMgr, "parallelProcessingFactor");
IGPString parallelProcessingFactorString = parallelProcessingFactorEnvironment.Value as IGPString;
// the default value is to use half the cores for additional threads - I am aware that we are comparing apples and oranges but I need a number
int numberOfThreads = Convert.ToInt32(System.Environment.ProcessorCount / 2);
if (!(parallelProcessingFactorEnvironment.Value.IsEmpty()))
{
if (!Int32.TryParse(parallelProcessingFactorString.Value, out numberOfThreads))
{
// this case we have a percent string
string resultString = Regex.Match(parallelProcessingFactorString.Value, @"\d+").Value;
numberOfThreads = Convert.ToInt32(Double.Parse(resultString) / 100 * System.Environment.ProcessorCount);
}
}
// tread the special case of 0
if (numberOfThreads <= 0)
numberOfThreads = 1;
IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword");
IGPString gpString = configKeyword.Value as IGPString;
string storageKeyword = String.Empty;
if (gpString != null)
{
storageKeyword = gpString.Value;
}
// determine the temp folder to be use for the intermediate files
IGPEnvironment scratchWorkspaceEnvironment = OSMToolHelper.getEnvironment(envMgr, "scratchWorkspace");
IDEWorkspace deWorkspace = scratchWorkspaceEnvironment.Value as IDEWorkspace;
String scratchWorkspaceFolder = String.Empty;
if (deWorkspace != null)
{
if (scratchWorkspaceEnvironment.Value.IsEmpty())
{
scratchWorkspaceFolder = (new System.IO.FileInfo(osmFileLocationString.GetAsText())).DirectoryName;
}
else
{
if (deWorkspace.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
scratchWorkspaceFolder = System.IO.Path.GetTempPath();
}
else if (deWorkspace.WorkspaceType == esriWorkspaceType.esriFileSystemWorkspace)
{
scratchWorkspaceFolder = ((IDataElement)deWorkspace).CatalogPath;
// check if the path indeed does exist
if (System.IO.Directory.Exists(scratchWorkspaceFolder) == false)
{
message.AddWarning(resourceManager.GetString("GPTools_OSMGPMultiLoader_scratch_replace"));
scratchWorkspaceFolder = System.IO.Path.GetTempPath();
}
}
else
{
scratchWorkspaceFolder = (new System.IO.FileInfo(((IDataElement)deWorkspace).CatalogPath)).DirectoryName;
// check if the path indeed does exist
if (System.IO.Directory.Exists(scratchWorkspaceFolder) == false)
{
message.AddWarning(resourceManager.GetString("GPTools_OSMGPMultiLoader_scratch_replace"));
scratchWorkspaceFolder = System.IO.Path.GetTempPath();
}
}
}
}
else
{
scratchWorkspaceFolder = (new System.IO.FileInfo(osmFileLocationString.GetAsText())).DirectoryName;
}
string metadataAbstract = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_abstract");
string metadataPurpose = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_purpose");
IGPParameter osmPointsFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter;
IGPValue osmPointsFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmPointsFeatureClassParameter) as IGPValue;
IGPParameter osmLineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter;
IGPValue osmLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmLineFeatureClassParameter) as IGPValue;
IGPParameter osmPolygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter;
IGPValue osmPolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmPolygonFeatureClassParameter) as IGPValue;
List<string> fcTargets = new List<string>() { osmPointsFeatureClassGPValue.GetAsText(),
osmLineFeatureClassGPValue.GetAsText(), osmPolygonFeatureClassGPValue.GetAsText() };
IEnumerable<string> uniqueFeatureClassTargets = fcTargets.Distinct();
if (uniqueFeatureClassTargets.Count() != 3)
{
message.AddError(120201, String.Format(resourceManager.GetString("GPTools_OSMGPRelationLoader_not_unique_fc_names")));
return;
}
// determine the number of nodes, ways and relation in the OSM file
long nodeCapacity = 0;
long wayCapacity = 0;
long relationCapacity = 0;
// this assume a clean, tidy XML file - if this is not the case, there will by sync issues later on
List<string> remarks = osmToolHelper.countOSMStuffFast(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel);
if (nodeCapacity == 0 && wayCapacity == 0 && relationCapacity == 0)
{
return;
}
// report any remarks in the OSM file
if (remarks.Count > 0)
{
foreach (string remark in remarks)
message.AddWarning(remark);
}
message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_countedElements"), nodeCapacity, wayCapacity, relationCapacity));
string pointFCName = osmPointsFeatureClassGPValue.GetAsText();
string[] pointFCNameElements = pointFCName.Split(System.IO.Path.DirectorySeparatorChar);
IName workspaceName = null;
try
{
workspaceName = gpUtilities3.CreateParentFromCatalogPath(pointFCName);
if (workspaceName is IDatasetName)
{
message.AddError(120200, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_fc_only"),
pointFCNameElements[pointFCNameElements.Length - 1]));
return;
}
if (workspaceName is IWorkspaceName)
{
IWorkspaceName workspaceNameItself = workspaceName as IWorkspaceName;
if (workspaceNameItself.Type != esriWorkspaceType.esriLocalDatabaseWorkspace)
{
message.AddError(120202, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_remote_gdb_not_supported")));
return;
}
}
}
catch (Exception ex)
{
message.AddError(120200, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_fc_only"),
pointFCNameElements[pointFCNameElements.Length - 1]));
return;
}
IWorkspace2 pointFeatureWorkspace = workspaceName.Open() as IWorkspace2;
IGPParameter tagPointCollectionParameter = paramvalues.get_Element(in_pointFieldNamesNumber) as IGPParameter;
IGPMultiValue tagPointCollectionGPValue = gpUtilities3.UnpackGPValue(tagPointCollectionParameter) as IGPMultiValue;
string targetPointFeatureClassLocation = String.Empty;
List<String> pointTagstoExtract = null;
if (tagPointCollectionGPValue.Count > 0)
{
pointTagstoExtract = new List<string>();
for (int valueIndex = 0; valueIndex < tagPointCollectionGPValue.Count; valueIndex++)
{
string nameOfTag = tagPointCollectionGPValue.get_Value(valueIndex).GetAsText();
pointTagstoExtract.Add(nameOfTag);
}
}
else
{
pointTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields();
}
// points
try
{
osmPointFeatureClass = osmToolHelper.CreateSmallPointFeatureClass(pointFeatureWorkspace,
pointFCNameElements[pointFCNameElements.Length - 1], storageKeyword, metadataAbstract,
metadataPurpose, pointTagstoExtract);
targetPointFeatureClassLocation = System.IO.Path.Combine(((IDataset)osmPointFeatureClass).Workspace.PathName, ((IDataset)osmPointFeatureClass).BrowseName);
}
catch (Exception ex)
{
message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message));
return;
}
if (osmPointFeatureClass == null)
{
return;
}
int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
Dictionary<string, int> mainPointAttributeFieldIndices = new Dictionary<string, int>();
foreach (string fieldName in OSMToolHelper.OSMSmallFeatureClassFields())
{
int currentFieldIndex = osmPointFeatureClass.FindField(fieldName);
if (currentFieldIndex != -1)
{
mainPointAttributeFieldIndices.Add(fieldName, currentFieldIndex);
}
}
int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags");
int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement");
string targetLineFeatureClassLocation = osmLineFeatureClassGPValue.GetAsText();
string[] lineFCNameElements = targetLineFeatureClassLocation.Split(System.IO.Path.DirectorySeparatorChar);
IName lineWorkspaceName = null;
try
{
lineWorkspaceName = gpUtilities3.CreateParentFromCatalogPath(targetLineFeatureClassLocation);
if (lineWorkspaceName is IDatasetName)
{
message.AddError(120200, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_fc_only"),
lineFCNameElements[lineFCNameElements.Length - 1]));
return;
}
if (lineWorkspaceName is IWorkspaceName)
{
IWorkspaceName workspaceNameItself = lineWorkspaceName as IWorkspaceName;
if (workspaceNameItself.Type != esriWorkspaceType.esriLocalDatabaseWorkspace)
{
message.AddError(120202, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_remote_gdb_not_supported")));
return;
}
}
}
catch (Exception ex)
{
message.AddError(120200, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_fc_only"),
lineFCNameElements[lineFCNameElements.Length - 1]));
return;
}
IWorkspace2 lineFeatureWorkspace = lineWorkspaceName.Open() as IWorkspace2;
string dbName = String.Empty;
string ownerName = String.Empty;
string lineFeatureClassName = String.Empty;
ISQLSyntax lineFCSQLSyntax = lineFeatureWorkspace as ISQLSyntax;
if (lineFCSQLSyntax != null)
lineFCSQLSyntax.ParseTableName(lineFCNameElements[lineFCNameElements.Length - 1], out dbName, out ownerName, out lineFeatureClassName);
else
lineFeatureClassName = lineFCNameElements[lineFCNameElements.Length - 1];
IGPParameter tagLineCollectionParameter = paramvalues.get_Element(in_lineFieldNamesNumber) as IGPParameter;
IGPMultiValue tagLineCollectionGPValue = gpUtilities3.UnpackGPValue(tagLineCollectionParameter) as IGPMultiValue;
List<String> lineTagstoExtract = null;
if (tagLineCollectionGPValue.Count > 0)
{
lineTagstoExtract = new List<string>();
for (int valueIndex = 0; valueIndex < tagLineCollectionGPValue.Count; valueIndex++)
{
string nameOfTag = tagLineCollectionGPValue.get_Value(valueIndex).GetAsText();
lineTagstoExtract.Add(nameOfTag);
}
}
else
{
lineTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields();
}
// lines
try
{
osmLineFeatureClass = osmToolHelper.CreateSmallLineFeatureClass(lineFeatureWorkspace, lineFCNameElements[lineFCNameElements.Length -1],
storageKeyword, metadataAbstract, metadataPurpose, lineTagstoExtract);
targetLineFeatureClassLocation = System.IO.Path.Combine(((IDataset)osmLineFeatureClass).Workspace.PathName, ((IDataset)osmLineFeatureClass).BrowseName);
}
catch (Exception ex)
{
message.AddError(120036, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nulllinefeatureclass"), ex.Message));
return;
}
if (osmLineFeatureClass == null)
{
return;
}
int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID");
Dictionary<string, int> mainLineAttributeFieldIndices = new Dictionary<string, int>();
foreach (string fieldName in OSMToolHelper.OSMSmallFeatureClassFields())
{
int currentFieldIndex = osmLineFeatureClass.FindField(fieldName);
if (currentFieldIndex != -1)
{
mainLineAttributeFieldIndices.Add(fieldName, currentFieldIndex);
}
}
int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags");
int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement");
string targetPolygonFeatureClassLocation = osmPolygonFeatureClassGPValue.GetAsText();
string[] polygonFCNameElements = targetPolygonFeatureClassLocation.Split(System.IO.Path.DirectorySeparatorChar);
IName polygonWorkspaceName = null;
try
{
polygonWorkspaceName = gpUtilities3.CreateParentFromCatalogPath(targetPolygonFeatureClassLocation);
if (polygonWorkspaceName is IDatasetName)
{
message.AddError(120200, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_fc_only"),
polygonFCNameElements[polygonFCNameElements.Length - 1]));
return;
}
if (polygonWorkspaceName is IWorkspaceName)
{
IWorkspaceName workspaceNameItself = polygonWorkspaceName as IWorkspaceName;
if (workspaceNameItself.Type != esriWorkspaceType.esriLocalDatabaseWorkspace)
{
message.AddError(120202, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_remote_gdb_not_supported")));
return;
}
}
}
catch (Exception ex)
{
message.AddError(120200, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_fc_only"),
polygonFCNameElements[polygonFCNameElements.Length - 1]));
return;
}
IWorkspace2 polygonFeatureWorkspace = polygonWorkspaceName.Open() as IWorkspace2;
string polygonFeatureClassName = String.Empty;
ISQLSyntax polygonFCSQLSyntax = polygonFeatureWorkspace as ISQLSyntax;
if (polygonFCSQLSyntax != null)
polygonFCSQLSyntax.ParseTableName(polygonFCNameElements[polygonFCNameElements.Length - 1], out dbName, out ownerName, out polygonFeatureClassName);
else
polygonFeatureClassName = polygonFCNameElements[polygonFCNameElements.Length - 1];
IGPParameter tagPolygonCollectionParameter = paramvalues.get_Element(in_polygonFieldNamesNumber) as IGPParameter;
IGPMultiValue tagPolygonCollectionGPValue = gpUtilities3.UnpackGPValue(tagPolygonCollectionParameter) as IGPMultiValue;
List<String> polygonTagstoExtract = null;
if (tagPolygonCollectionGPValue.Count > 0)
{
polygonTagstoExtract = new List<string>();
for (int valueIndex = 0; valueIndex < tagPolygonCollectionGPValue.Count; valueIndex++)
{
string nameOfTag = tagPolygonCollectionGPValue.get_Value(valueIndex).GetAsText();
polygonTagstoExtract.Add(nameOfTag);
}
}
else
{
polygonTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields();
}
// polygons
try
{
osmPolygonFeatureClass = osmToolHelper.CreateSmallPolygonFeatureClass(polygonFeatureWorkspace,
polygonFCNameElements[polygonFCNameElements.Length -1], storageKeyword, metadataAbstract,
metadataPurpose, polygonTagstoExtract);
targetPolygonFeatureClassLocation = System.IO.Path.Combine(((IDataset)osmPolygonFeatureClass).Workspace.PathName, ((IDataset)osmPolygonFeatureClass).BrowseName);
}
catch (Exception ex)
{
message.AddError(120037, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpolygonfeatureclass"), ex.Message));
return;
}
if (osmPolygonFeatureClass == null)
{
return;
}
int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID");
Dictionary<string, int> mainPolygonAttributeFieldIndices = new Dictionary<string, int>();
foreach (var fieldName in OSMToolHelper.OSMSmallFeatureClassFields())
{
int currentFieldIndex = osmPolygonFeatureClass.FindField(fieldName);
if (currentFieldIndex != -1)
{
mainPolygonAttributeFieldIndices.Add(fieldName, currentFieldIndex);
}
}
int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags");
int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement");
ComReleaser.ReleaseCOMObject(osmPointFeatureClass);
osmPointFeatureClass = null;
ComReleaser.ReleaseCOMObject(osmLineFeatureClass);
osmLineFeatureClass = null;
ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass);
osmPolygonFeatureClass = null;
List<string> nodeOSMFileNames = new List<string>(numberOfThreads);
List<string> nodeGDBFileNames = new List<string>(numberOfThreads);
List<string> wayOSMFileNames = new List<string>(numberOfThreads);
List<string> wayGDBFileNames = new List<string>(numberOfThreads);
List<string> relationOSMFileNames = new List<string>(numberOfThreads);
List<string> relationGDBFileNames = new List<string>(numberOfThreads);
if (TrackCancel.Continue() == false)
{
return;
}
// split the original OSM XML file into smaller pieces for the python processes
osmToolHelper.splitOSMFile(osmFileLocationString.GetAsText(), scratchWorkspaceFolder, nodeCapacity, wayCapacity, relationCapacity, numberOfThreads,
out nodeOSMFileNames, out nodeGDBFileNames, out wayOSMFileNames, out wayGDBFileNames, out relationOSMFileNames, out relationGDBFileNames);
IGPParameter deleteSourceOSMFileParameter = paramvalues.get_Element(in_deleteOSMSourceFileNumber) as IGPParameter;
IGPBoolean deleteSourceOSMFileGPValue = gpUtilities3.UnpackGPValue(deleteSourceOSMFileParameter) as IGPBoolean;
if (deleteSourceOSMFileGPValue.Value)
{
try
{
System.IO.File.Delete(osmFileLocationString.GetAsText());
}
catch (Exception ex)
{
message.AddWarning(ex.Message);
}
}
if (TrackCancel.Continue() == false)
{
return;
}
if (nodeOSMFileNames.Count == 0)
{
nodeOSMFileNames.Add(osmFileLocationString.GetAsText());
nodeGDBFileNames.Add(((IWorkspace)pointFeatureWorkspace).PathName);
wayOSMFileNames.Add(osmFileLocationString.GetAsText());
wayGDBFileNames.Add(((IWorkspace)lineFeatureWorkspace).PathName);
relationOSMFileNames.Add(osmFileLocationString.GetAsText());
relationGDBFileNames.Add(((IWorkspace)polygonFeatureWorkspace).PathName);
}
else if (nodeOSMFileNames.Count == 1)
{
nodeGDBFileNames[0] = ((IWorkspace)pointFeatureWorkspace).PathName;
wayGDBFileNames[0] = ((IWorkspace)lineFeatureWorkspace).PathName;
relationGDBFileNames[0] = ((IWorkspace)polygonFeatureWorkspace).PathName;
}
else
{
// for the nodes let's load one of the parts directly into the target file geodatabase
nodeGDBFileNames[0] = ((IWorkspace)pointFeatureWorkspace).PathName;
}
// define variables helping to invoke core tools for data management
IGeoProcessorResult2 gpResults2 = null;
IGeoProcessor2 geoProcessor = new GeoProcessorClass();
geoProcessor.AddToResults = false;
IGPParameter deleteSupportingNodesParameter = paramvalues.get_Element(in_deleteSupportNodesNumber) as IGPParameter;
IGPBoolean deleteSupportingNodesGPValue = gpUtilities3.UnpackGPValue(deleteSupportingNodesParameter) as IGPBoolean;
#region load points
osmToolHelper.loadOSMNodes(nodeOSMFileNames, nodeGDBFileNames, pointFCNameElements[pointFCNameElements.Length - 1],
pointFCName, pointTagstoExtract, deleteSupportingNodesGPValue.Value, ref message, ref TrackCancel);
#endregion
if (TrackCancel.Continue() == false)
{
return;
}
#region load ways
osmToolHelper.loadOSMWays(wayOSMFileNames, targetPointFeatureClassLocation, wayGDBFileNames, lineFeatureClassName,
targetLineFeatureClassLocation, polygonFeatureClassName, targetPolygonFeatureClassLocation, lineTagstoExtract, polygonTagstoExtract,
ref message, ref TrackCancel);
#endregion
#region for local geodatabases enforce spatial integrity
bool storedOriginalLocal = geoProcessor.AddOutputsToMap;
geoProcessor.AddOutputsToMap = false;
try
{
osmLineFeatureClass = ((IFeatureWorkspace)lineFeatureWorkspace).OpenFeatureClass(lineFCNameElements[lineFCNameElements.Length - 1]);
if (osmLineFeatureClass != null)
{
if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
{
IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter;
IGPValue lineFeatureClassGPValue = gpUtilities3.UnpackGPValue(outLinesParameter);
DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass);
IVariantArray repairGeometryParameterArray = new VarArrayClass();
repairGeometryParameterArray.Add(lineFeatureClassGPValue.GetAsText());
repairGeometryParameterArray.Add("DELETE_NULL");
gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2;
message.AddMessages(gpResults2.GetResultMessages());
}
}
}
catch { }
finally
{
ComReleaser.ReleaseCOMObject(osmLineFeatureClass);
}
try
{
osmPolygonFeatureClass = ((IFeatureWorkspace)polygonFeatureWorkspace).OpenFeatureClass(polygonFCNameElements[polygonFCNameElements.Length - 1]);
if (osmPolygonFeatureClass != null)
{
if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
{
IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter;
IGPValue polygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(outPolygonParameter);
DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass);
IVariantArray repairGeometryParameterArray = new VarArrayClass();
repairGeometryParameterArray.Add(polygonFeatureClassGPValue.GetAsText());
repairGeometryParameterArray.Add("DELETE_NULL");
gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2;
message.AddMessages(gpResults2.GetResultMessages());
}
}
}
catch { }
finally
{
ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass);
}
geoProcessor.AddOutputsToMap = storedOriginalLocal;
#endregion
if (TrackCancel.Continue() == false)
{
return;
}
#region load relations
osmToolHelper.loadOSMRelations(relationOSMFileNames, lineFeatureClassName, targetLineFeatureClassLocation,
polygonFeatureClassName, targetPolygonFeatureClassLocation, relationGDBFileNames, lineTagstoExtract,
polygonTagstoExtract, ref TrackCancel, ref message);
#endregion
// check for user interruption
if (TrackCancel.Continue() == false)
{
return;
}
#region for local geodatabases enforce spatial integrity
storedOriginalLocal = geoProcessor.AddOutputsToMap;
geoProcessor.AddOutputsToMap = false;
gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;
try
{
osmLineFeatureClass = ((IFeatureWorkspace)lineFeatureWorkspace).OpenFeatureClass(lineFCNameElements[lineFCNameElements.Length - 1]);
if (osmLineFeatureClass != null)
{
if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
{
IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter;
IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter);
DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass);
IVariantArray repairGeometryParameterArray = new VarArrayClass();
repairGeometryParameterArray.Add(lineFeatureClass.GetAsText());
repairGeometryParameterArray.Add("DELETE_NULL");
gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2;
message.AddMessages(gpResults2.GetResultMessages());
}
}
}
catch { }
finally
{
ComReleaser.ReleaseCOMObject(osmLineFeatureClass);
}
try
{
osmPolygonFeatureClass = ((IFeatureWorkspace)polygonFeatureWorkspace).OpenFeatureClass(polygonFCNameElements[polygonFCNameElements.Length - 1]);
if (osmPolygonFeatureClass != null)
{
if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
{
IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter;
IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter);
DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass);
IVariantArray repairGeometryParameterArray = new VarArrayClass();
repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText());
repairGeometryParameterArray.Add("DELETE_NULL");
gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2;
message.AddMessages(gpResults2.GetResultMessages());
}
}
}
catch { }
finally
{
ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass);
}
geoProcessor.AddOutputsToMap = storedOriginalLocal;
#endregion
if (TrackCancel.Continue() == false)
{
return;
}
gpUtilities3 = new GPUtilitiesClass();
if (deleteSupportingNodesGPValue.Value)
{
message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_remove_supportNodes")));
geoProcessor = new GeoProcessorClass();
storedOriginalLocal = geoProcessor.AddOutputsToMap;
geoProcessor.AddOutputsToMap = false;
geoProcessor.AddToResults = false;
// create a layer file to select the points that have attributes
osmPointFeatureClass = gpUtilities3.OpenFeatureClassFromString(pointFCName);
IQueryFilter supportElementQueryFilter = new QueryFilterClass();
supportElementQueryFilter.WhereClause = String.Format("{0} = 'no'", osmPointFeatureClass.SqlIdentifier("osmSupportingElement"));
IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace;
string tempFeatureClass = pointFCName + "_tmp";
string shapeFieldName = osmPointFeatureClass.ShapeFieldName;
int shapeFieldIndex = osmPointFeatureClass.FindField(shapeFieldName);
IField shapeField = osmPointFeatureClass.Fields.get_Field(shapeFieldIndex);
IGeometryDef geometryDef = ((IClone)shapeField.GeometryDef).Clone() as IGeometryDef;
IFeatureDataConverter2 featureDataConverter = new FeatureDataConverterClass() as IFeatureDataConverter2;
featureDataConverter.ConvertFeatureClass(gpUtilities3.CreateFeatureClassName(pointFCName) as IDatasetName,
supportElementQueryFilter, null, null,
gpUtilities3.CreateFeatureClassName(tempFeatureClass) as IFeatureClassName,
geometryDef,
osmPointFeatureClass.Fields, "", 50000, 0);
// delete the original feature class
IVariantArray deleteParameterArray = new VarArrayClass();
deleteParameterArray.Add(osmPointsFeatureClassGPValue.GetAsText());
geoProcessor.Execute("Delete_management", deleteParameterArray, TrackCancel);
// rename the temp feature class back to the original
IVariantArray renameParameterArray = new VarArrayClass();
renameParameterArray.Add(tempFeatureClass);
renameParameterArray.Add(osmPointsFeatureClassGPValue.GetAsText());
geoProcessor.Execute("Rename_management", renameParameterArray, TrackCancel);
storedOriginalLocal = geoProcessor.AddOutputsToMap;
ComReleaser.ReleaseCOMObject(pointWorkspace);
ComReleaser.ReleaseCOMObject(osmPointFeatureClass);
ComReleaser.ReleaseCOMObject(geoProcessor);
}
// repackage the feature class into their respective gp values
IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter;
IGPValue pointFeatureClassGPValue = gpUtilities3.UnpackGPValue(pointFeatureClassParameter);
gpUtilities3.PackGPValue(pointFeatureClassGPValue, pointFeatureClassParameter);
IGPParameter lineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter;
IGPValue line1FeatureClassGPValue = gpUtilities3.UnpackGPValue(lineFeatureClassParameter);
gpUtilities3.PackGPValue(line1FeatureClassGPValue, lineFeatureClassParameter);
IGPParameter polygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter;
IGPValue polygon1FeatureClassGPValue = gpUtilities3.UnpackGPValue(polygonFeatureClassParameter);
gpUtilities3.PackGPValue(polygon1FeatureClassGPValue, polygonFeatureClassParameter);
ComReleaser.ReleaseCOMObject(osmFileLocationString);
gpUtilities3.ReleaseInternals();
ComReleaser.ReleaseCOMObject(gpUtilities3);
}
catch (Exception ex)
{
message.AddError(120055, ex.Message);
message.AddError(120055, ex.StackTrace);
}
finally
{
try
{
osmToolHelper = null;
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
message.AddError(120056, ex.ToString());
}
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_MultiLoaderName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return default(object);
}
public int HelpContext
{
get
{
return default(int);
}
}
public string HelpFile
{
get
{
return default(string);
}
}
public bool IsLicensed()
{
return true;
}
public string MetadataFile
{
get
{
string metadafile = "osmgpmultiloader.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_MultiLoaderName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
//
IArray parameterArray = new ArrayClass();
// osm file to load (required)
IGPParameterEdit3 osmLoadFile = new GPParameterClass() as IGPParameterEdit3;
osmLoadFile.DataType = new DEFileTypeClass();
osmLoadFile.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
osmLoadFile.DisplayName = resourceManager.GetString("GPTools_OSMGPMultiLoader_osmfile_desc");
osmLoadFile.Name = "in_osmFile";
osmLoadFile.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
IGPParameterEdit3 osmPoints = new GPParameterClass() as IGPParameterEdit3;
osmPoints.DataType = new DEFeatureClassTypeClass();
osmPoints.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
osmPoints.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
osmPoints.DisplayName = resourceManager.GetString("GPTools_OSMGPMultiLoader_osmPoints_desc");
osmPoints.Name = "out_osmPoints";
IGPFeatureClassDomain osmPointFeatureClassDomain = new GPFeatureClassDomainClass();
osmPointFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple);
osmPointFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint);
osmPoints.Domain = osmPointFeatureClassDomain as IGPDomain;
IGPParameterEdit3 osmLines = new GPParameterClass() as IGPParameterEdit3;
osmLines.DataType = new DEFeatureClassTypeClass();
osmLines.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
osmLines.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
osmLines.DisplayName = resourceManager.GetString("GPTools_OSMGPMultiLoader_osmLine_desc");
osmLines.Name = "out_osmLines";
IGPFeatureClassDomain osmPolylineFeatureClassDomain = new GPFeatureClassDomainClass();
osmPolylineFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple);
osmPolylineFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline);
osmLines.Domain = osmPolylineFeatureClassDomain as IGPDomain;
IGPParameterEdit3 osmPolygons = new GPParameterClass() as IGPParameterEdit3;
osmPolygons.DataType = new DEFeatureClassTypeClass();
osmPolygons.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
osmPolygons.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
osmPolygons.DisplayName = resourceManager.GetString("GPTools_OSMGPMultiLoader_osmPolygon_desc");
osmPolygons.Name = "out_osmPolygons";
IGPFeatureClassDomain osmPolygonFeatureClassDomain = new GPFeatureClassDomainClass();
osmPolygonFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple);
osmPolygonFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon);
osmPolygons.Domain = osmPolygonFeatureClassDomain as IGPDomain;
IGPParameterEdit3 deleteOSMSourceFileParameter = new GPParameterClass() as IGPParameterEdit3;
IGPCodedValueDomain deleteOSMSourceFileDomain = new GPCodedValueDomainClass();
IGPBoolean deleteOSMSourceFileTrue = new GPBooleanClass();
deleteOSMSourceFileTrue.Value = true;
IGPBoolean deleteOSMSourceFileFalse = new GPBooleanClass();
deleteOSMSourceFileFalse.Value = false;
deleteOSMSourceFileDomain.AddCode((IGPValue)deleteOSMSourceFileTrue, "DELETE_OSM_FILE");
deleteOSMSourceFileDomain.AddCode((IGPValue)deleteOSMSourceFileFalse, "DO_NOT_DELETE_OSM_FILE");
deleteOSMSourceFileParameter.Domain = (IGPDomain)deleteOSMSourceFileDomain;
deleteOSMSourceFileParameter.Value = (IGPValue)deleteOSMSourceFileFalse;
deleteOSMSourceFileParameter.DataType = new GPBooleanTypeClass();
deleteOSMSourceFileParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
deleteOSMSourceFileParameter.ParameterType = esriGPParameterType.esriGPParameterTypeOptional;
deleteOSMSourceFileParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPMultiLoader_deleteOSMSource_desc");
deleteOSMSourceFileParameter.Name = "in_deleteOSMSourceFile";
IGPParameterEdit3 deleteSupportNodesParameter = new GPParameterClass() as IGPParameterEdit3;
IGPCodedValueDomain deleteSupportNodesDomain = new GPCodedValueDomainClass();
IGPBoolean deleteSupportNodesTrue = new GPBooleanClass();
deleteSupportNodesTrue.Value = true;
IGPBoolean deleteSupportNodesFalse = new GPBooleanClass();
deleteSupportNodesFalse.Value = false;
deleteSupportNodesDomain.AddCode((IGPValue)deleteSupportNodesTrue, "DELETE_NODES");
deleteSupportNodesDomain.AddCode((IGPValue)deleteSupportNodesFalse, "DO_NOT_DELETE_NODES");
deleteSupportNodesParameter.Domain = (IGPDomain)deleteSupportNodesDomain;
deleteSupportNodesParameter.Value = (IGPValue)deleteSupportNodesTrue;
deleteSupportNodesParameter.DataType = new GPBooleanTypeClass();
deleteSupportNodesParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
deleteSupportNodesParameter.ParameterType = esriGPParameterType.esriGPParameterTypeOptional;
deleteSupportNodesParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPMultiLoader_deleteNodes_desc");
deleteSupportNodesParameter.Name = "in_deleteSupportNodes";
// field multi parameter
IGPParameterEdit3 loadLineFieldsParameter = new GPParameterClass() as IGPParameterEdit3;
IGPDataType fieldNameDataType = new GPStringTypeClass();
IGPMultiValue fieldNameMultiValue = new GPMultiValueClass();
fieldNameMultiValue.MemberDataType = fieldNameDataType;
IGPMultiValueType fieldNameDataType2 = new GPMultiValueTypeClass();
fieldNameDataType2.MemberDataType = fieldNameDataType;
loadLineFieldsParameter.Name = "in_polyline_fieldNames";
loadLineFieldsParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPWayLoader_lineFieldNames_desc");
loadLineFieldsParameter.Category = resourceManager.GetString("GPTools_OSMGPMultiLoader_schemaCategory_desc");
loadLineFieldsParameter.ParameterType = esriGPParameterType.esriGPParameterTypeOptional;
loadLineFieldsParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
loadLineFieldsParameter.DataType = (IGPDataType)fieldNameDataType2;
loadLineFieldsParameter.Value = (IGPValue)fieldNameMultiValue;
IGPParameterEdit3 loadPolygonFieldsParameter = new GPParameterClass() as IGPParameterEdit3;
loadPolygonFieldsParameter.Name = "in_polygon_fieldNames";
loadPolygonFieldsParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPWayLoader_polygonFieldNames_desc");
loadPolygonFieldsParameter.Category = resourceManager.GetString("GPTools_OSMGPMultiLoader_schemaCategory_desc");
loadPolygonFieldsParameter.ParameterType = esriGPParameterType.esriGPParameterTypeOptional;
loadPolygonFieldsParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
loadPolygonFieldsParameter.DataType = (IGPDataType)fieldNameDataType2;
loadPolygonFieldsParameter.Value = (IGPValue)fieldNameMultiValue;
IGPParameterEdit3 loadPointFieldsParameter = new GPParameterClass() as IGPParameterEdit3;
loadPointFieldsParameter.Name = "in_point_fieldNames";
loadPointFieldsParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPNodeLoader_fieldNames_desc");
loadPointFieldsParameter.Category = resourceManager.GetString("GPTools_OSMGPMultiLoader_schemaCategory_desc");
loadPointFieldsParameter.ParameterType = esriGPParameterType.esriGPParameterTypeOptional;
loadPointFieldsParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
loadPointFieldsParameter.DataType = (IGPDataType)fieldNameDataType2;
loadPointFieldsParameter.Value = (IGPValue)fieldNameMultiValue;
parameterArray.Add(osmLoadFile);
in_osmFileNumber = 0;
parameterArray.Add(loadPointFieldsParameter);
in_pointFieldNamesNumber = 1;
parameterArray.Add(loadLineFieldsParameter);
in_lineFieldNamesNumber = 2;
parameterArray.Add(loadPolygonFieldsParameter);
in_polygonFieldNamesNumber = 3;
parameterArray.Add(deleteSupportNodesParameter);
in_deleteSupportNodesNumber = 4;
parameterArray.Add(deleteOSMSourceFileParameter);
in_deleteOSMSourceFileNumber = 5;
parameterArray.Add(osmPoints);
out_osmPointsNumber = 6;
parameterArray.Add(osmLines);
out_osmLinesNumber = 7;
parameterArray.Add(osmPolygons);
out_osmPolygonsNumber = 8;
return parameterArray;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using ModestTree;
namespace Zenject
{
// Zero parameters
public class IFactoryResolveProvider<TValue> : IProvider
{
readonly object _subIdentifier;
readonly DiContainer _container;
public IFactoryResolveProvider(
DiContainer container,
object subIdentifier)
{
_subIdentifier = subIdentifier;
_container = container;
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TValue);
}
public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEmpty(args);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
// Do this even when validating in case it has its own dependencies
var factory = _container.ResolveId<IFactory<TValue>>(_subIdentifier);
if (_container.IsValidating)
{
// In case users define a custom IFactory that needs to be validated
if (factory is IValidatable)
{
((IValidatable)factory).Validate();
}
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>() { factory.Create() };
}
}
}
// One parameters
public class IFactoryResolveProvider<TParam1, TValue> : IProvider
{
readonly object _subIdentifier;
readonly DiContainer _container;
public IFactoryResolveProvider(
DiContainer container,
object subIdentifier)
{
_subIdentifier = subIdentifier;
_container = container;
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TValue);
}
public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 1);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
// Do this even when validating in case it has its own dependencies
var factory = _container.ResolveId<IFactory<TParam1, TValue>>(_subIdentifier);
if (_container.IsValidating)
{
// In case users define a custom IFactory that needs to be validated
if (factory is IValidatable)
{
((IValidatable)factory).Validate();
}
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
factory.Create((TParam1)args[0].Value)
};
}
}
}
// Two parameters
public class IFactoryResolveProvider<TParam1, TParam2, TValue> : IProvider
{
readonly object _subIdentifier;
readonly DiContainer _container;
public IFactoryResolveProvider(
DiContainer container,
object subIdentifier)
{
_subIdentifier = subIdentifier;
_container = container;
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TValue);
}
public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 2);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
// Do this even when validating in case it has its own dependencies
var factory = _container.ResolveId<IFactory<TParam1, TParam2, TValue>>(_subIdentifier);
if (_container.IsValidating)
{
// In case users define a custom IFactory that needs to be validated
if (factory is IValidatable)
{
((IValidatable)factory).Validate();
}
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
factory.Create(
(TParam1)args[0].Value,
(TParam2)args[1].Value)
};
}
}
}
// Three parameters
public class IFactoryResolveProvider<TParam1, TParam2, TParam3, TValue> : IProvider
{
readonly object _subIdentifier;
readonly DiContainer _container;
public IFactoryResolveProvider(
DiContainer container,
object subIdentifier)
{
_subIdentifier = subIdentifier;
_container = container;
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TValue);
}
public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 3);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
// Do this even when validating in case it has its own dependencies
var factory = _container.ResolveId<IFactory<TParam1, TParam2, TParam3, TValue>>(_subIdentifier);
if (_container.IsValidating)
{
// In case users define a custom IFactory that needs to be validated
if (factory is IValidatable)
{
((IValidatable)factory).Validate();
}
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
factory.Create(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value)
};
}
}
}
// Four parameters
public class IFactoryResolveProvider<TParam1, TParam2, TParam3, TParam4, TValue> : IProvider
{
readonly object _subIdentifier;
readonly DiContainer _container;
public IFactoryResolveProvider(
DiContainer container,
object subIdentifier)
{
_subIdentifier = subIdentifier;
_container = container;
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TValue);
}
public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 4);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>());
// Do this even when validating in case it has its own dependencies
var factory = _container.ResolveId<IFactory<TParam1, TParam2, TParam3, TParam4, TValue>>(_subIdentifier);
if (_container.IsValidating)
{
// In case users define a custom IFactory that needs to be validated
if (factory is IValidatable)
{
((IValidatable)factory).Validate();
}
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
factory.Create(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value)
};
}
}
}
// Five parameters
public class IFactoryResolveProvider<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : IProvider
{
readonly object _subIdentifier;
readonly DiContainer _container;
public IFactoryResolveProvider(
DiContainer container,
object subIdentifier)
{
_subIdentifier = subIdentifier;
_container = container;
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TValue);
}
public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args)
{
Assert.IsEqual(args.Count, 5);
Assert.IsNotNull(context);
Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>());
Assert.That(args[4].Type.DerivesFromOrEqual<TParam5>());
// Do this even when validating in case it has its own dependencies
var factory = _container.ResolveId<IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>>(_subIdentifier);
if (_container.IsValidating)
{
// In case users define a custom IFactory that needs to be validated
if (factory is IValidatable)
{
((IValidatable)factory).Validate();
}
// We assume here that we are creating a user-defined factory so there's
// nothing else we can validate here
yield return new List<object>() { new ValidationMarker(typeof(TValue)) };
}
else
{
yield return new List<object>()
{
factory.Create(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value,
(TParam5)args[4].Value)
};
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookApplicationRequest.
/// </summary>
public partial class WorkbookApplicationRequest : BaseRequest, IWorkbookApplicationRequest
{
/// <summary>
/// Constructs a new WorkbookApplicationRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookApplicationRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookApplication using POST.
/// </summary>
/// <param name="workbookApplicationToCreate">The WorkbookApplication to create.</param>
/// <returns>The created WorkbookApplication.</returns>
public System.Threading.Tasks.Task<WorkbookApplication> CreateAsync(WorkbookApplication workbookApplicationToCreate)
{
return this.CreateAsync(workbookApplicationToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookApplication using POST.
/// </summary>
/// <param name="workbookApplicationToCreate">The WorkbookApplication to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookApplication.</returns>
public async System.Threading.Tasks.Task<WorkbookApplication> CreateAsync(WorkbookApplication workbookApplicationToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookApplication>(workbookApplicationToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookApplication.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookApplication.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookApplication>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookApplication.
/// </summary>
/// <returns>The WorkbookApplication.</returns>
public System.Threading.Tasks.Task<WorkbookApplication> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookApplication.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookApplication.</returns>
public async System.Threading.Tasks.Task<WorkbookApplication> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookApplication>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookApplication using PATCH.
/// </summary>
/// <param name="workbookApplicationToUpdate">The WorkbookApplication to update.</param>
/// <returns>The updated WorkbookApplication.</returns>
public System.Threading.Tasks.Task<WorkbookApplication> UpdateAsync(WorkbookApplication workbookApplicationToUpdate)
{
return this.UpdateAsync(workbookApplicationToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookApplication using PATCH.
/// </summary>
/// <param name="workbookApplicationToUpdate">The WorkbookApplication to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookApplication.</returns>
public async System.Threading.Tasks.Task<WorkbookApplication> UpdateAsync(WorkbookApplication workbookApplicationToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookApplication>(workbookApplicationToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookApplicationRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookApplicationRequest Expand(Expression<Func<WorkbookApplication, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookApplicationRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookApplicationRequest Select(Expression<Func<WorkbookApplication, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookApplicationToInitialize">The <see cref="WorkbookApplication"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookApplication workbookApplicationToInitialize)
{
}
}
}
| |
// 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.Globalization;
using System.Text;
using Microsoft.CSharp.RuntimeBinder.Semantics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Errors
{
internal sealed class UserStringBuilder
{
private bool m_buildingInProgress;
private GlobalSymbolContext m_globalSymbols;
private StringBuilder m_strBuilder;
public UserStringBuilder(
GlobalSymbolContext globalSymbols)
{
Debug.Assert(globalSymbols != null);
m_buildingInProgress = false;
m_globalSymbols = globalSymbols;
}
private void BeginString()
{
Debug.Assert(!m_buildingInProgress);
m_buildingInProgress = true;
m_strBuilder = new StringBuilder();
}
private void EndString(out string s)
{
Debug.Assert(m_buildingInProgress);
m_buildingInProgress = false;
s = m_strBuilder.ToString();
m_strBuilder = null;
}
private void ErrSK(out string psz, SYMKIND sk)
{
MessageID id;
switch (sk)
{
case SYMKIND.SK_MethodSymbol:
id = MessageID.SK_METHOD;
break;
case SYMKIND.SK_AggregateSymbol:
id = MessageID.SK_CLASS;
break;
case SYMKIND.SK_NamespaceSymbol:
id = MessageID.SK_NAMESPACE;
break;
case SYMKIND.SK_FieldSymbol:
id = MessageID.SK_FIELD;
break;
case SYMKIND.SK_LocalVariableSymbol:
id = MessageID.SK_VARIABLE;
break;
case SYMKIND.SK_PropertySymbol:
id = MessageID.SK_PROPERTY;
break;
case SYMKIND.SK_EventSymbol:
id = MessageID.SK_EVENT;
break;
case SYMKIND.SK_TypeParameterSymbol:
id = MessageID.SK_TYVAR;
break;
default:
Debug.Assert(false, "impossible sk");
id = MessageID.SK_UNKNOWN;
break;
}
ErrId(out psz, id);
}
/*
* Create a fill-in string describing a parameter list.
* Does NOT include ()
*/
private void ErrAppendParamList(TypeArray @params, bool isVarargs, bool isParamArray)
{
if (null == @params)
return;
for (int i = 0; i < @params.Count; i++)
{
if (i > 0)
{
ErrAppendString(", ");
}
if (isParamArray && i == @params.Count - 1)
{
ErrAppendString("params ");
}
// parameter type name
ErrAppendType(@params[i], null);
}
if (isVarargs)
{
if (@params.Count != 0)
{
ErrAppendString(", ");
}
ErrAppendString("...");
}
}
private void ErrAppendString(string str)
{
m_strBuilder.Append(str);
}
private void ErrAppendChar(char ch)
{
m_strBuilder.Append(ch);
}
private void ErrAppendPrintf(string format, params object[] args)
{
ErrAppendString(string.Format(CultureInfo.InvariantCulture, format, args));
}
private void ErrAppendName(Name name)
{
if (name == NameManager.GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL))
{
ErrAppendString("this");
}
else
{
ErrAppendString(name.Text);
}
}
private void ErrAppendMethodParentSym(MethodSymbol sym, SubstContext pcxt, out TypeArray substMethTyParams)
{
substMethTyParams = null;
ErrAppendParentSym(sym, pcxt);
}
private void ErrAppendParentSym(Symbol sym, SubstContext pctx)
{
ErrAppendParentCore(sym.parent, pctx);
}
private void ErrAppendParentCore(Symbol parent, SubstContext pctx)
{
if (null == parent)
return;
if (parent == getBSymmgr().GetRootNS())
return;
if (pctx != null && !pctx.FNop() && parent is AggregateSymbol agg && 0 != agg.GetTypeVarsAll().Count)
{
CType pType = GetTypeManager().SubstType(agg.getThisType(), pctx);
ErrAppendType(pType, null);
}
else
{
ErrAppendSym(parent, null);
}
ErrAppendChar('.');
}
private void ErrAppendTypeParameters(TypeArray @params, SubstContext pctx, bool forClass)
{
if (@params != null && @params.Count != 0)
{
ErrAppendChar('<');
ErrAppendType(@params[0], pctx);
for (int i = 1; i < @params.Count; i++)
{
ErrAppendString(",");
ErrAppendType(@params[i], pctx);
}
ErrAppendChar('>');
}
}
private void ErrAppendMethod(MethodSymbol meth, SubstContext pctx, bool fArgs)
{
if (meth.IsExpImpl() && meth.swtSlot)
{
ErrAppendParentSym(meth, pctx);
// Get the type args from the explicit impl type and substitute using pctx (if there is one).
SubstContext ctx = new SubstContext(GetTypeManager().SubstType(meth.swtSlot.GetType(), pctx) as AggregateType);
ErrAppendSym(meth.swtSlot.Sym, ctx, fArgs);
// args already added
return;
}
if (meth.isPropertyAccessor())
{
PropertySymbol prop = meth.getProperty();
// this includes the parent class
ErrAppendSym(prop, pctx);
// add accessor name
if (prop.GetterMethod == meth)
{
ErrAppendString(".get");
}
else
{
Debug.Assert(meth == prop.SetterMethod);
ErrAppendString(".set");
}
// args already added
return;
}
if (meth.isEventAccessor())
{
EventSymbol @event = meth.getEvent();
// this includes the parent class
ErrAppendSym(@event, pctx);
// add accessor name
if (@event.methAdd == meth)
{
ErrAppendString(".add");
}
else
{
Debug.Assert(meth == @event.methRemove);
ErrAppendString(".remove");
}
// args already added
return;
}
ErrAppendMethodParentSym(meth, pctx, out TypeArray replacementTypeArray);
if (meth.IsConstructor())
{
// Use the name of the parent class instead of the name "<ctor>".
ErrAppendName(meth.getClass().name);
}
else if (meth.IsDestructor())
{
// Use the name of the parent class instead of the name "Finalize".
ErrAppendChar('~');
ErrAppendName(meth.getClass().name);
}
else if (meth.isConversionOperator())
{
// implicit/explicit
ErrAppendString(meth.isImplicit() ? "implicit" : "explicit");
ErrAppendString(" operator ");
// destination type name
ErrAppendType(meth.RetType, pctx);
}
else if (meth.isOperator)
{
// handle user defined operators
// map from CLS predefined names to "operator <X>"
ErrAppendString("operator ");
ErrAppendString(Operators.OperatorOfMethodName(meth.name));
}
else if (meth.IsExpImpl())
{
if (meth.errExpImpl != null)
ErrAppendType(meth.errExpImpl, pctx, fArgs);
}
else
{
// regular method
ErrAppendName(meth.name);
}
if (null == replacementTypeArray)
{
ErrAppendTypeParameters(meth.typeVars, pctx, false);
}
if (fArgs)
{
// append argument types
ErrAppendChar('(');
ErrAppendParamList(GetTypeManager().SubstTypeArray(meth.Params, pctx), meth.isVarargs, meth.isParamArray);
ErrAppendChar(')');
}
}
private void ErrAppendIndexer(IndexerSymbol indexer, SubstContext pctx)
{
ErrAppendString("this[");
ErrAppendParamList(GetTypeManager().SubstTypeArray(indexer.Params, pctx), false, indexer.isParamArray);
ErrAppendChar(']');
}
private void ErrAppendProperty(PropertySymbol prop, SubstContext pctx)
{
ErrAppendParentSym(prop, pctx);
if (prop.IsExpImpl() && prop.swtSlot.Sym != null)
{
SubstContext ctx = new SubstContext(GetTypeManager().SubstType(prop.swtSlot.GetType(), pctx) as AggregateType);
ErrAppendSym(prop.swtSlot.Sym, ctx);
}
else if (prop.IsExpImpl())
{
if (prop.errExpImpl != null)
ErrAppendType(prop.errExpImpl, pctx, false);
if (prop is IndexerSymbol indexer)
{
ErrAppendChar('.');
ErrAppendIndexer(indexer, pctx);
}
}
else if (prop is IndexerSymbol indexer)
{
ErrAppendIndexer(indexer, pctx);
}
else
{
ErrAppendName(prop.name);
}
}
private void ErrAppendEvent(EventSymbol @event, SubstContext pctx)
{
}
private void ErrAppendId(MessageID id)
{
string str;
ErrId(out str, id);
ErrAppendString(str);
}
/*
* Create a fill-in string describing a symbol.
*/
private void ErrAppendSym(Symbol sym, SubstContext pctx)
{
ErrAppendSym(sym, pctx, true);
}
private void ErrAppendSym(Symbol sym, SubstContext pctx, bool fArgs)
{
switch (sym.getKind())
{
case SYMKIND.SK_AggregateDeclaration:
ErrAppendSym(((AggregateDeclaration)sym).Agg(), pctx);
break;
case SYMKIND.SK_AggregateSymbol:
{
// Check for a predefined class with a special "nice" name for
// error reported.
string text = PredefinedTypes.GetNiceName(sym as AggregateSymbol);
if (text != null)
{
// Found a nice name.
ErrAppendString(text);
}
else
{
ErrAppendParentSym(sym, pctx);
ErrAppendName(sym.name);
ErrAppendTypeParameters(((AggregateSymbol)sym).GetTypeVars(), pctx, true);
}
break;
}
case SYMKIND.SK_MethodSymbol:
ErrAppendMethod((MethodSymbol)sym, pctx, fArgs);
break;
case SYMKIND.SK_PropertySymbol:
ErrAppendProperty((PropertySymbol)sym, pctx);
break;
case SYMKIND.SK_EventSymbol:
ErrAppendEvent((EventSymbol)sym, pctx);
break;
case SYMKIND.SK_NamespaceSymbol:
if (sym == getBSymmgr().GetRootNS())
{
ErrAppendId(MessageID.GlobalNamespace);
}
else
{
ErrAppendParentSym(sym, null);
ErrAppendName(sym.name);
}
break;
case SYMKIND.SK_FieldSymbol:
ErrAppendParentSym(sym, pctx);
ErrAppendName(sym.name);
break;
case SYMKIND.SK_TypeParameterSymbol:
if (null == sym.name)
{
var parSym = (TypeParameterSymbol)sym;
// It's a standard type variable.
if (parSym.IsMethodTypeParameter())
ErrAppendChar('!');
ErrAppendChar('!');
ErrAppendPrintf("{0}", parSym.GetIndexInTotalParameters());
}
else
ErrAppendName(sym.name);
break;
case SYMKIND.SK_LocalVariableSymbol:
// Generate symbol name.
ErrAppendName(sym.name);
break;
default:
// Shouldn't happen.
Debug.Assert(false, $"Bad symbol kind: {sym.getKind()}");
break;
}
}
private void ErrAppendType(CType pType, SubstContext pCtx)
{
ErrAppendType(pType, pCtx, true);
}
private void ErrAppendType(CType pType, SubstContext pctx, bool fArgs)
{
if (pctx != null)
{
if (!pctx.FNop())
{
pType = GetTypeManager().SubstType(pType, pctx);
}
// We shouldn't use the SubstContext again so set it to NULL.
pctx = null;
}
switch (pType.GetTypeKind())
{
case TypeKind.TK_AggregateType:
{
AggregateType pAggType = (AggregateType)pType;
// Check for a predefined class with a special "nice" name for
// error reported.
string text = PredefinedTypes.GetNiceName(pAggType.getAggregate());
if (text != null)
{
// Found a nice name.
ErrAppendString(text);
}
else
{
if (pAggType.outerType != null)
{
ErrAppendType(pAggType.outerType, pctx);
ErrAppendChar('.');
}
else
{
// In a namespace.
ErrAppendParentSym(pAggType.getAggregate(), pctx);
}
ErrAppendName(pAggType.getAggregate().name);
}
ErrAppendTypeParameters(pAggType.GetTypeArgsThis(), pctx, true);
break;
}
case TypeKind.TK_TypeParameterType:
if (null == pType.GetName())
{
var tpType = (TypeParameterType)pType;
// It's a standard type variable.
if (tpType.IsMethodTypeParameter())
{
ErrAppendChar('!');
}
ErrAppendChar('!');
ErrAppendPrintf("{0}", tpType.GetIndexInTotalParameters());
}
else
{
ErrAppendName(pType.GetName());
}
break;
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)pType;
if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
ErrAppendName(err.nameText);
ErrAppendTypeParameters(err.typeArgs, pctx, true);
}
else
{
// Load the string "<error>".
Debug.Assert(null == err.typeArgs);
ErrAppendId(MessageID.ERRORSYM);
}
break;
case TypeKind.TK_NullType:
// Load the string "<null>".
ErrAppendId(MessageID.NULL);
break;
case TypeKind.TK_MethodGroupType:
ErrAppendId(MessageID.MethodGroup);
break;
case TypeKind.TK_ArgumentListType:
ErrAppendString(TokenFacts.GetText(TokenKind.ArgList));
break;
case TypeKind.TK_ArrayType:
{
CType elementType = ((ArrayType)pType).GetBaseElementType();
if (null == elementType)
{
Debug.Assert(false, "No element type");
break;
}
ErrAppendType(elementType, pctx);
for (elementType = pType;
elementType is ArrayType arrType;
elementType = arrType.GetElementType())
{
int rank = arrType.rank;
// Add [] with (rank-1) commas inside
ErrAppendChar('[');
// known rank.
if (rank == 1)
{
if (!arrType.IsSZArray)
{
ErrAppendChar('*');
}
}
else
{
for (int i = rank; i > 1; --i)
{
ErrAppendChar(',');
}
}
ErrAppendChar(']');
}
break;
}
case TypeKind.TK_VoidType:
ErrAppendName(NameManager.Lookup(TokenFacts.GetText(TokenKind.Void)));
break;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType mod = (ParameterModifierType)pType;
// add ref or out
ErrAppendString(mod.isOut ? "out " : "ref ");
// add base type name
ErrAppendType(mod.GetParameterType(), pctx);
break;
case TypeKind.TK_PointerType:
// Generate the base type.
ErrAppendType(((PointerType)pType).GetReferentType(), pctx);
{
// add the trailing *
ErrAppendChar('*');
}
break;
case TypeKind.TK_NullableType:
ErrAppendType(((NullableType)pType).GetUnderlyingType(), pctx);
ErrAppendChar('?');
break;
default:
// Shouldn't happen.
Debug.Assert(false, "Bad type kind");
break;
}
}
// Returns true if the argument could be converted to a string.
public bool ErrArgToString(out string psz, ErrArg parg, out bool fUserStrings)
{
fUserStrings = false;
psz = null;
bool result = true;
switch (parg.eak)
{
case ErrArgKind.Ids:
ErrId(out psz, parg.ids);
break;
case ErrArgKind.SymKind:
ErrSK(out psz, parg.sk);
break;
case ErrArgKind.Type:
BeginString();
ErrAppendType(parg.pType, null);
EndString(out psz);
fUserStrings = true;
break;
case ErrArgKind.Sym:
BeginString();
ErrAppendSym(parg.sym, null);
EndString(out psz);
fUserStrings = true;
break;
case ErrArgKind.Name:
if (parg.name == NameManager.GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL))
{
psz = "this";
}
else
{
psz = parg.name.Text;
}
break;
case ErrArgKind.Str:
psz = parg.psz;
break;
case ErrArgKind.SymWithType:
{
SubstContext ctx = new SubstContext(parg.swtMemo.ats, null);
BeginString();
ErrAppendSym(parg.swtMemo.sym, ctx, true);
EndString(out psz);
fUserStrings = true;
break;
}
case ErrArgKind.MethWithInst:
{
SubstContext ctx = new SubstContext(parg.mpwiMemo.ats, parg.mpwiMemo.typeArgs);
BeginString();
ErrAppendSym(parg.mpwiMemo.sym, ctx, true);
EndString(out psz);
fUserStrings = true;
break;
}
default:
result = false;
break;
}
return result;
}
private TypeManager GetTypeManager()
{
return m_globalSymbols.GetTypes();
}
private BSYMMGR getBSymmgr()
{
return m_globalSymbols.GetGlobalSymbols();
}
private int GetTypeID(CType type)
{
return 0;
}
private void ErrId(out string s, MessageID id)
{
s = ErrorFacts.GetMessage(id);
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Wasm.Binary;
namespace Wasm
{
/// <summary>
/// Represents a type section in a WebAssembly file.
/// </summary>
public sealed class TypeSection : Section
{
/// <summary>
/// Creates an empty type section.
/// </summary>
public TypeSection()
: this(Enumerable.Empty<FunctionType>())
{
}
/// <summary>
/// Creates a type section from the given list of function types.
/// </summary>
/// <param name="functionTypes">The list of function types in this type section.</param>
public TypeSection(IEnumerable<FunctionType> functionTypes)
: this(functionTypes, new byte[0])
{
}
/// <summary>
/// Creates a type section from the given list of function types and an additional payload.
/// </summary>
/// <param name="functionTypes">The list of function types in this type section.</param>
/// <param name="extraPayload">The additional payload for this section, as an array of bytes.</param>
public TypeSection(IEnumerable<FunctionType> functionTypes, byte[] extraPayload)
{
this.FunctionTypes = new List<FunctionType>(functionTypes);
this.ExtraPayload = extraPayload;
}
/// <summary>
/// Gets this type section's list of function types.
/// </summary>
/// <returns>The list of function types in this type section.</returns>
public List<FunctionType> FunctionTypes { get; private set; }
/// <summary>
/// This type section's additional payload.
/// </summary>
/// <returns>The additional payload, as an array of bytes.</returns>
public byte[] ExtraPayload { get; set; }
/// <inheritdoc/>
public override SectionName Name => new SectionName(SectionCode.Type);
/// <inheritdoc/>
public override void WritePayloadTo(BinaryWasmWriter writer)
{
writer.WriteVarUInt32((uint)FunctionTypes.Count);
foreach (var type in FunctionTypes)
type.WriteTo(writer);
writer.Writer.Write(ExtraPayload);
}
/// <inheritdoc/>
public override void Dump(TextWriter writer)
{
writer.Write(Name.ToString());
writer.Write("; number of entries: ");
writer.Write(FunctionTypes.Count);
writer.WriteLine();
for (int i = 0; i < FunctionTypes.Count; i++)
{
writer.Write("#");
writer.Write(i);
writer.Write(" -> ");
FunctionTypes[i].Dump(writer);
writer.WriteLine();
}
if (ExtraPayload.Length > 0)
{
writer.Write("Extra payload size: ");
writer.Write(ExtraPayload.Length);
writer.WriteLine();
DumpHelpers.DumpBytes(ExtraPayload, writer);
writer.WriteLine();
}
}
/// <summary>
/// Reads a type section's payload from the given binary WebAssembly reader.
/// </summary>
/// <param name="header">The type section's header.</param>
/// <param name="reader">A reader for a binary WebAssembly file.</param>
/// <returns>A parsed type section.</returns>
public static TypeSection ReadSectionPayload(SectionHeader header, BinaryWasmReader reader)
{
long initPos = reader.Position;
uint typeCount = reader.ReadVarUInt32();
var types = new List<FunctionType>((int)typeCount);
for (uint i = 0; i < typeCount; i++)
{
types.Add(FunctionType.ReadFrom(reader));
}
var extraBytes = reader.ReadRemainingPayload(initPos, header);
return new TypeSection(types, extraBytes);
}
}
/// <summary>
/// Represents a function type entry in a type section.
/// </summary>
public sealed class FunctionType
{
/// <summary>
/// Creates a function type.
/// </summary>
public FunctionType()
{
this.ParameterTypes = new List<WasmValueType>();
this.ReturnTypes = new List<WasmValueType>();
}
/// <summary>
/// Creates a function type from the given parameter types and return types.
/// </summary>
/// <param name="parameterTypes">This function type's list of parameter types.</param>
/// <param name="returnTypes">This function type's list of return types.</param>
public FunctionType(
IEnumerable<WasmValueType> parameterTypes,
IEnumerable<WasmValueType> returnTypes)
{
this.ParameterTypes = new List<WasmValueType>(parameterTypes);
this.ReturnTypes = new List<WasmValueType>(returnTypes);
}
/// <summary>
/// Creates a function type that takes ownership of the given parameter types and return types.
/// </summary>
/// <param name="parameterTypes">This function type's list of parameter types.</param>
/// <param name="returnTypes">This function type's list of return types.</param>
private FunctionType(
List<WasmValueType> parameterTypes,
List<WasmValueType> returnTypes)
{
this.ParameterTypes = parameterTypes;
this.ReturnTypes = returnTypes;
}
/// <summary>
/// Gets this function type's form, which is always WasmType.Func.
/// </summary>
public WasmType Form => WasmType.Func;
/// <summary>
/// Gets this function type's list of parameter types.
/// </summary>
/// <returns>The list of parameter types for this function.</returns>
public List<WasmValueType> ParameterTypes { get; private set; }
/// <summary>
/// Gets this function type's list of return types.
/// </summary>
/// <returns>The list of return types for this function.</returns>
public List<WasmValueType> ReturnTypes { get; private set; }
/// <summary>
/// Writes this function type to the given binary WebAssembly file.
/// </summary>
/// <param name="writer">The writer for a binary WebAssembly file.</param>
public void WriteTo(BinaryWasmWriter writer)
{
writer.WriteWasmType(Form);
writer.WriteVarUInt32((uint)ParameterTypes.Count);
foreach (var item in ParameterTypes)
writer.WriteWasmValueType(item);
writer.WriteVarUInt32((uint)ReturnTypes.Count);
foreach (var item in ReturnTypes)
writer.WriteWasmValueType(item);
}
/// <summary>
/// Writes a textual representation of this exported value to the given writer.
/// </summary>
/// <param name="writer">The writer to which text is written.</param>
public void Dump(TextWriter writer)
{
writer.Write("func(");
for (int i = 0; i < ParameterTypes.Count; i++)
{
if (i > 0)
writer.Write(", ");
DumpHelpers.DumpWasmType(ParameterTypes[i], writer);
}
writer.Write(") returns (");
for (int i = 0; i < ReturnTypes.Count; i++)
{
if (i > 0)
writer.Write(", ");
DumpHelpers.DumpWasmType(ReturnTypes[i], writer);
}
writer.Write(")");
}
/// <inheritdoc/>
public override string ToString()
{
var writer = new StringWriter();
Dump(writer);
return writer.ToString();
}
/// <summary>
/// Reads a single function type from the given reader.
/// </summary>
/// <returns>The function type.</returns>
public static FunctionType ReadFrom(BinaryWasmReader reader)
{
WasmType form = (WasmType)reader.ReadWasmType();
if (form != WasmType.Func)
throw new WasmException("Invalid 'form' value ('" + form + "') for function type.");
uint paramCount = reader.ReadVarUInt32();
var paramTypes = new List<WasmValueType>((int)paramCount);
for (uint i = 0; i < paramCount; i++)
{
paramTypes.Add(reader.ReadWasmValueType());
}
uint retCount = reader.ReadVarUInt32();
var retTypes = new List<WasmValueType>((int)retCount);
for (uint i = 0; i < retCount; i++)
{
retTypes.Add(reader.ReadWasmValueType());
}
return new FunctionType(paramTypes, retTypes);
}
}
}
| |
/* Copyright (c) 2006-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
using System;
using System.Xml;
using System.Collections;
using System.Text;
using Google.GData.Client;
using System.Globalization;
namespace Google.GData.Extensions
{
/// <summary>
/// GData schema extension describing a webcontent for the calendar
/// </summary>
public class WebContent : IExtensionElementFactory
{
private string url;
private string display;
private uint width;
private uint height;
private SortedList gadgetPrefs;
//////////////////////////////////////////////////////////////////////
/// <summary>url of content</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Url
{
get { return this.url; }
set { this.url = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>Display property</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Display
{
get { return this.display; }
set { this.display = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>width of the iframe/gif</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
[CLSCompliant(false)]
public uint Width
{
get { return this.width; }
set { this.width = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>Height of the iframe/gif</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
[CLSCompliant(false)]
public uint Height
{
get { return this.height; }
set { this.height = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public SortedList GadgetPreferences</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public SortedList GadgetPreferences
{
get
{
if (this.gadgetPrefs == null)
{
this.gadgetPrefs = new SortedList();
}
return this.gadgetPrefs;
}
set {this.gadgetPrefs = value;}
}
// end of accessor public SortedList GadgetPreferences
#region WebContent Parser
//////////////////////////////////////////////////////////////////////
/// <summary>Parses an xml node to create a webcontent object.</summary>
/// <param name="node">xml node</param>
/// <param name="parser">the atomfeedparser to use for deep dive parsing</param>
/// <returns>the created SimpleElement object</returns>
//////////////////////////////////////////////////////////////////////
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
Tracing.TraceCall();
if (node != null)
{
object localname = node.LocalName;
if (!localname.Equals(this.XmlName) ||
!node.NamespaceURI.Equals(this.XmlNameSpace))
{
return null;
}
}
WebContent webContent = null;
webContent = new WebContent();
if (node.Attributes != null)
{
String value = node.Attributes[GDataParserNameTable.XmlAttributeUrl] != null ?
node.Attributes[GDataParserNameTable.XmlAttributeUrl].Value : null;
if (value != null)
{
webContent.Url = value;
}
value = node.Attributes[GDataParserNameTable.XmlAttributeDisplay] != null ?
node.Attributes[GDataParserNameTable.XmlAttributeDisplay].Value : null;
if (value != null)
{
webContent.Display = value;
}
value = node.Attributes[GDataParserNameTable.XmlAttributeWidth] != null ?
node.Attributes[GDataParserNameTable.XmlAttributeWidth].Value : null;
if (value != null)
{
webContent.Width = uint.Parse(value, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
}
value = node.Attributes[GDataParserNameTable.XmlAttributeHeight] != null ?
node.Attributes[GDataParserNameTable.XmlAttributeHeight].Value : null;
if (value != null)
{
webContent.Height = uint.Parse(value, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
}
}
// single event, g:reminder is inside g:when
if (node.HasChildNodes)
{
XmlNode gadgetPrefs = node.FirstChild;
while (gadgetPrefs != null && gadgetPrefs is XmlElement)
{
if (String.Compare(gadgetPrefs.NamespaceURI, XmlNameSpace, true) == 0)
{
if (String.Compare(gadgetPrefs.LocalName, GDataParserNameTable.XmlWebContentGadgetElement) == 0)
{
if (gadgetPrefs.Attributes != null)
{
string value = gadgetPrefs.Attributes[BaseNameTable.XmlValue] != null ?
gadgetPrefs.Attributes[BaseNameTable.XmlValue].Value : null;
string name = gadgetPrefs.Attributes[BaseNameTable.XmlName] != null ?
gadgetPrefs.Attributes[BaseNameTable.XmlName].Value : null;
if (name != null)
{
webContent.GadgetPreferences.Add(name, value);
}
}
}
}
gadgetPrefs = gadgetPrefs.NextSibling;
}
}
return webContent;
}
#endregion
#region overloaded for persistence
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.
/// </summary>
//////////////////////////////////////////////////////////////////////
public string XmlName
{
get { return GDataParserNameTable.XmlWebContentElement; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public string XmlNameSpace
{
get { return GDataParserNameTable.NSGCal; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public string XmlPrefix
{
get { return GDataParserNameTable.gCalPrefix; }
}
/// <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(this.Url))
{
writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace);
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeUrl, this.Url);
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeDisplay, this.Display);
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHeight, this.Height.ToString());
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeWidth, this.Width.ToString());
if (this.gadgetPrefs != null && this.gadgetPrefs.Count > 0)
{
for (int i=0; i < this.gadgetPrefs.Count; i++)
{
string name = this.gadgetPrefs.GetKey(i) as string;
string value = this.gadgetPrefs.GetByIndex(i) as string;
if (name != null)
{
writer.WriteStartElement(XmlPrefix,
GDataParserNameTable.XmlWebContentGadgetElement,
XmlNameSpace);
writer.WriteAttributeString(BaseNameTable.XmlName, name);
if (value != null)
{
writer.WriteAttributeString(BaseNameTable.XmlValue, value);
}
writer.WriteEndElement();
}
}
}
writer.WriteEndElement();
}
}
#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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.CSharp.RenameTracking;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.VisualBasic.RenameTracking;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
internal sealed class RenameTrackingTestState : IDisposable
{
private readonly ITagger<RenameTrackingTag> _tagger;
public readonly TestWorkspace Workspace;
private readonly IWpfTextView _view;
private readonly ITextUndoHistoryRegistry _historyRegistry;
private string _notificationMessage = null;
private readonly TestHostDocument _hostDocument;
public TestHostDocument HostDocument { get { return _hostDocument; } }
private readonly IEditorOperations _editorOperations;
public IEditorOperations EditorOperations { get { return _editorOperations; } }
private readonly MockRefactorNotifyService _mockRefactorNotifyService;
public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } }
private readonly CodeFixProvider _codeFixProvider;
private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler();
public RenameTrackingTestState(
string markup,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
this.Workspace = CreateTestWorkspace(markup, languageName, TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic());
_hostDocument = Workspace.Documents.First();
_view = _hostDocument.GetTextView();
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
_editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
_historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
_mockRefactorNotifyService = new MockRefactorNotifyService
{
OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
};
var optionService = this.Workspace.Services.GetService<IOptionService>();
// Mock the action taken by the workspace INotificationService
var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback;
var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
notificationService.NotificationCallback = callback;
var tracker = new RenameTrackingTaggerProvider(
_historyRegistry,
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService),
Workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>());
_tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());
if (languageName == LanguageNames.CSharp)
{
_codeFixProvider = new CSharpRenameTrackingCodeFixProvider(
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else if (languageName == LanguageNames.VisualBasic)
{
_codeFixProvider = new VisualBasicRenameTrackingCodeFixProvider(
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else
{
throw new ArgumentException("Invalid langauge name: " + languageName, "languageName");
}
}
private static TestWorkspace CreateTestWorkspace(string code, string languageName, ExportProvider exportProvider = null)
{
var xml = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document>{1}</Document>
</Project>
</Workspace>", languageName, code);
return TestWorkspaceFactory.CreateWorkspace(xml, exportProvider: exportProvider);
}
public void SendEscape()
{
_commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), () => { });
}
public void MoveCaret(int delta)
{
var position = _view.Caret.Position.BufferPosition.Position;
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta));
}
public void Undo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Undo(count);
}
public void Redo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Redo(count);
}
public void AssertNoTag()
{
WaitForAsyncOperations();
var tags = _tagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(_view.TextBuffer.CurrentSnapshot, new Span(0, _view.TextBuffer.CurrentSnapshot.Length))));
Assert.Equal(0, tags.Count());
}
public IList<Diagnostic> GetDocumentDiagnostics(Document document = null)
{
document = document ?? this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var analyzer = new RenameTrackingDiagnosticAnalyzer();
return DiagnosticProviderTestUtilities.GetDocumentDiagnostics(analyzer, document, document.GetSyntaxRootAsync(CancellationToken.None).Result.FullSpan).ToList();
}
public void AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false)
{
WaitForAsyncOperations();
var tags = _tagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(_view.TextBuffer.CurrentSnapshot, new Span(0, _view.TextBuffer.CurrentSnapshot.Length))));
// There should only ever be one tag
Assert.Equal(1, tags.Count());
var tag = tags.Single();
var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var diagnostics = GetDocumentDiagnostics(document);
// There should be a single rename tracking diagnostic
Assert.Equal(1, diagnostics.Count);
Assert.Equal(RenameTrackingDiagnosticAnalyzer.DiagnosticId, diagnostics[0].Id);
var actions = new List<CodeAction>();
var context = new CodeFixContext(document, diagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
_codeFixProvider.RegisterCodeFixesAsync(context).Wait();
// There should only be one code action
Assert.Equal(1, actions.Count);
Assert.Equal(string.Format(EditorFeaturesResources.RenameTo, expectedFromName, expectedToName), actions[0].Title);
if (invokeAction)
{
var operations = actions[0]
.GetOperationsAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None)
.ToArray();
Assert.Equal(1, operations.Length);
operations[0].Apply(this.Workspace, CancellationToken.None);
}
}
public void AssertNoNotificationMessage()
{
Assert.Null(_notificationMessage);
}
public void AssertNotificationMessage()
{
Assert.NotNull(_notificationMessage);
}
private void WaitForAsyncOperations()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
var tasks = waiters.Select(w => w.CreateWaitTask()).ToList();
tasks.PumpingWaitAll();
}
public void Dispose()
{
Workspace.Dispose();
}
}
}
| |
using System;
using System.Collections.Generic;
using SilentOrbit.Code;
namespace SilentOrbit.ProtocolBuffers
{
class MessageCode
{
readonly CodeWriter cw;
readonly Options options;
public MessageCode(CodeWriter cw, Options options)
{
this.cw = cw;
this.options = options;
}
public void GenerateClass(ProtoMessage m)
{
if (options.NoGenerateImported && m.IsImported)
{
Console.Error.WriteLine("Skipping imported " + m.FullProtoName);
return;
}
//Do not generate class code for external classes
if (m.OptionExternal)
{
cw.Comment("Written elsewhere");
cw.Comment(m.OptionAccess + " " + m.OptionType + " " + m.CsType + " {}");
return;
}
//Default class
cw.Summary(m.Comments);
cw.Bracket(m.OptionAccess + " partial " + m.OptionType + " " + m.CsType);
if (options.GenerateDefaultConstructors)
{
GenerateCtorForDefaults(m);
}
GenerateEnums(m);
GenerateProperties(m);
//if(options.GenerateToString...
// ...
if (m.OptionPreserveUnknown)
{
cw.Summary("Values for unknown fields.");
cw.WriteLine("public List<global::SilentOrbit.ProtocolBuffers.KeyValue> PreservedFields;");
cw.WriteLine();
}
if (m.OptionTriggers)
{
cw.Comment("protected virtual void BeforeSerialize() {}");
cw.Comment("protected virtual void AfterDeserialize() {}");
cw.WriteLine();
}
foreach (ProtoMessage sub in m.Messages.Values)
{
GenerateClass(sub);
cw.WriteLine();
}
cw.EndBracket();
return;
}
void GenerateCtorForDefaults(ProtoMessage m)
{
// Collect all fields with default values.
var fieldsWithDefaults = new List<Field>();
foreach (Field field in m.Fields.Values)
{
if (field.OptionDefault != null)
{
fieldsWithDefaults.Add(field);
}
}
if (fieldsWithDefaults.Count > 0)
{
cw.Bracket("public " + m.CsType + "()");
foreach (var field in fieldsWithDefaults)
{
string formattedValue = field.FormatDefaultForTypeAssignment();
string line = string.Format("{0} = {1};", field.CsName, formattedValue);
cw.WriteLine(line);
}
cw.EndBracket();
}
}
void GenerateEnums(ProtoMessage m)
{
foreach (ProtoEnum me in m.Enums.Values)
{
GenerateEnum(me);
}
}
public void GenerateEnum(ProtoEnum m)
{
if (options.NoGenerateImported && m.IsImported)
{
Console.Error.WriteLine("Skipping imported enum " + m.FullProtoName);
return;
}
if (m.OptionExternal)
{
cw.Comment("Written elsewhere");
cw.Comment(m.Comments);
cw.Comment(m.OptionAccess + " enum " + m.CsType);
cw.Comment("{");
foreach (var epair in m.Enums)
{
cw.Summary(epair.Comment);
cw.Comment(cw.IndentPrefix + epair.Name + " = " + epair.Value + ",");
}
cw.Comment("}");
return;
}
cw.Summary(m.Comments);
if (m.OptionFlags)
{
cw.Attribute("global::System.FlagsAttribute");
}
cw.Bracket(m.OptionAccess + " enum " + m.CsType);
foreach (var epair in m.Enums)
{
cw.Summary(epair.Comment);
cw.WriteLine(epair.Name + " = " + epair.Value + ",");
}
cw.EndBracket();
cw.WriteLine();
}
/// <summary>
/// Generates the properties.
/// </summary>
void GenerateProperties(ProtoMessage m)
{
foreach (Field f in m.Fields.Values)
{
if (f.Comments != null)
{
cw.Summary(f.Comments);
}
if (f.OptionExternal)
{
if (f.OptionDeprecated)
{
cw.WriteLine("// [Obsolete]");
}
cw.WriteLine("//" + GenerateProperty(f) + " // Implemented by user elsewhere");
}
else
{
if (f.OptionDeprecated)
{
cw.WriteLine("[Obsolete]");
}
cw.WriteLine(GenerateProperty(f));
}
cw.WriteLine();
}
//Wire format field ID
#if DEBUGx
cw.Comment("ProtocolBuffers wire field id");
foreach (Field f in m.Fields.Values)
{
cw.WriteLine("public const int " + f.CsName + "FieldID = " + f.ID + ";");
}
#endif
}
string GenerateProperty(Field f)
{
string type = f.ProtoType.FullCsType;
if (f.OptionCodeType != null)
{
type = f.OptionCodeType;
}
if (f.Rule == FieldRule.Repeated)
{
type = "List<" + type + ">";
}
if (f.Rule == FieldRule.Optional && !f.ProtoType.Nullable && options.Nullable)
{
type += "?";
}
if (f.OptionReadOnly)
{
return f.OptionAccess + " readonly " + type + " " + f.CsName + " = new " + type + "();";
}
else if (f.ProtoType is ProtoMessage && f.ProtoType.OptionType == "struct")
{
return f.OptionAccess + " " + type + " " + f.CsName + ";";
}
else
{
return f.OptionAccess + " " + type + " " + f.CsName + " { get; set; }";
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ReplicationEventsOperations operations.
/// </summary>
internal partial class ReplicationEventsOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationEventsOperations
{
/// <summary>
/// Initializes a new instance of the ReplicationEventsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ReplicationEventsOperations(SiteRecoveryManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SiteRecoveryManagementClient
/// </summary>
public SiteRecoveryManagementClient Client { get; private set; }
/// <summary>
/// Get the details of an Azure Site recovery event.
/// </summary>
/// <remarks>
/// The operation to get the details of an Azure Site recovery event.
/// </remarks>
/// <param name='eventName'>
/// The name of the Azure Site Recovery event.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<EventModel>> GetWithHttpMessagesAsync(string eventName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (eventName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "eventName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("eventName", eventName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationEvents/{eventName}").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{eventName}", System.Uri.EscapeDataString(eventName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<EventModel>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<EventModel>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the list of Azure Site Recovery events.
/// </summary>
/// <remarks>
/// Gets the list of Azure Site Recovery events for the vault.
/// </remarks>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<EventModel>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationEvents").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<EventModel>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<EventModel>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the list of Azure Site Recovery events.
/// </summary>
/// <remarks>
/// Gets the list of Azure Site Recovery events for the vault.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<EventModel>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<EventModel>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<EventModel>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;
namespace SoodaAddin.UI
{
/// <summary>
/// Summary description for WizardPageOptions.
/// </summary>
public class WizardPageOptions : SoodaAddin.UI.WizardPage
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Panel panelAdvancedOptions;
public System.Windows.Forms.ComboBox comboBoxConfigStyle;
public System.Windows.Forms.CheckBox checkBoxCreateConfig;
public System.Windows.Forms.CheckBox checkBoxModifyBuildEvent;
public System.Windows.Forms.CheckBox checkBoxSeparateStubs;
public System.Windows.Forms.CheckBox checkBoxAddAttributesToAssemblyInfo;
public System.Windows.Forms.CheckBox checkBoxCreateKeyGen;
public System.Windows.Forms.CheckBox checkBoxDisableIdentityColumns;
private System.Windows.Forms.GroupBox groupBox1;
public System.Windows.Forms.CheckBox checkBoxGenerateSchema;
private System.Windows.Forms.Button buttonAdvancedOptions;
public System.Windows.Forms.CheckBox checkBoxGenerateStubs;
private System.Windows.Forms.LinkLabel linkLabelCreateKeyGen;
private System.Windows.Forms.LinkLabel linkLabelDisableIdentityColumns;
private System.Windows.Forms.LinkLabel linkLabelSeparateStubs;
private System.Windows.Forms.LinkLabel linkLabelModifyBuildEvent;
private System.Windows.Forms.LinkLabel linkLabelCreateConfig;
private System.Windows.Forms.LinkLabel linkLabelAddAttributes;
private System.Windows.Forms.LinkLabel linkLabelGenerateSchema;
private System.Windows.Forms.LinkLabel linkLabelGenerateStubs;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public WizardPageOptions()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitializeComponent call
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.checkBoxGenerateStubs = new System.Windows.Forms.CheckBox();
this.panelAdvancedOptions = new System.Windows.Forms.Panel();
this.linkLabelCreateKeyGen = new System.Windows.Forms.LinkLabel();
this.comboBoxConfigStyle = new System.Windows.Forms.ComboBox();
this.checkBoxCreateConfig = new System.Windows.Forms.CheckBox();
this.checkBoxModifyBuildEvent = new System.Windows.Forms.CheckBox();
this.checkBoxSeparateStubs = new System.Windows.Forms.CheckBox();
this.checkBoxAddAttributesToAssemblyInfo = new System.Windows.Forms.CheckBox();
this.checkBoxCreateKeyGen = new System.Windows.Forms.CheckBox();
this.checkBoxDisableIdentityColumns = new System.Windows.Forms.CheckBox();
this.linkLabelDisableIdentityColumns = new System.Windows.Forms.LinkLabel();
this.linkLabelSeparateStubs = new System.Windows.Forms.LinkLabel();
this.linkLabelModifyBuildEvent = new System.Windows.Forms.LinkLabel();
this.linkLabelCreateConfig = new System.Windows.Forms.LinkLabel();
this.linkLabelAddAttributes = new System.Windows.Forms.LinkLabel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBoxGenerateSchema = new System.Windows.Forms.CheckBox();
this.linkLabelGenerateSchema = new System.Windows.Forms.LinkLabel();
this.buttonAdvancedOptions = new System.Windows.Forms.Button();
this.linkLabelGenerateStubs = new System.Windows.Forms.LinkLabel();
this.panelAdvancedOptions.SuspendLayout();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label1.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(238)));
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(520, 24);
this.label1.TabIndex = 5;
this.label1.Text = "Select options:";
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label2.Location = new System.Drawing.Point(8, 32);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(520, 16);
this.label2.TabIndex = 9;
this.label2.Text = "Choose the actions you would like the wizard to perform and click Finish.";
//
// checkBoxGenerateStubs
//
this.checkBoxGenerateStubs.Location = new System.Drawing.Point(8, 80);
this.checkBoxGenerateStubs.Name = "checkBoxGenerateStubs";
this.checkBoxGenerateStubs.Size = new System.Drawing.Size(432, 24);
this.checkBoxGenerateStubs.TabIndex = 6;
this.checkBoxGenerateStubs.Text = "Generate initial stubs and skeleton classes";
//
// panelAdvancedOptions
//
this.panelAdvancedOptions.AutoScroll = true;
this.panelAdvancedOptions.AutoScrollMargin = new System.Drawing.Size(8, 8);
this.panelAdvancedOptions.BackColor = System.Drawing.SystemColors.Control;
this.panelAdvancedOptions.Controls.Add(this.linkLabelCreateKeyGen);
this.panelAdvancedOptions.Controls.Add(this.comboBoxConfigStyle);
this.panelAdvancedOptions.Controls.Add(this.checkBoxCreateConfig);
this.panelAdvancedOptions.Controls.Add(this.checkBoxModifyBuildEvent);
this.panelAdvancedOptions.Controls.Add(this.checkBoxSeparateStubs);
this.panelAdvancedOptions.Controls.Add(this.checkBoxAddAttributesToAssemblyInfo);
this.panelAdvancedOptions.Controls.Add(this.checkBoxCreateKeyGen);
this.panelAdvancedOptions.Controls.Add(this.checkBoxDisableIdentityColumns);
this.panelAdvancedOptions.Controls.Add(this.linkLabelDisableIdentityColumns);
this.panelAdvancedOptions.Controls.Add(this.linkLabelSeparateStubs);
this.panelAdvancedOptions.Controls.Add(this.linkLabelModifyBuildEvent);
this.panelAdvancedOptions.Controls.Add(this.linkLabelCreateConfig);
this.panelAdvancedOptions.Controls.Add(this.linkLabelAddAttributes);
this.panelAdvancedOptions.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelAdvancedOptions.Location = new System.Drawing.Point(3, 18);
this.panelAdvancedOptions.Name = "panelAdvancedOptions";
this.panelAdvancedOptions.Size = new System.Drawing.Size(514, 203);
this.panelAdvancedOptions.TabIndex = 10;
//
// linkLabelCreateKeyGen
//
this.linkLabelCreateKeyGen.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelCreateKeyGen.Location = new System.Drawing.Point(448, 80);
this.linkLabelCreateKeyGen.Name = "linkLabelCreateKeyGen";
this.linkLabelCreateKeyGen.Size = new System.Drawing.Size(56, 23);
this.linkLabelCreateKeyGen.TabIndex = 24;
this.linkLabelCreateKeyGen.TabStop = true;
this.linkLabelCreateKeyGen.Text = "Explain";
this.linkLabelCreateKeyGen.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabelCreateKeyGen.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelCreateKeyGen_LinkClicked);
//
// comboBoxConfigStyle
//
this.comboBoxConfigStyle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxConfigStyle.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxConfigStyle.Items.AddRange(new object[] {
"App.config - private",
"Sooda.config.xml - shared"});
this.comboBoxConfigStyle.Location = new System.Drawing.Point(224, 8);
this.comboBoxConfigStyle.Name = "comboBoxConfigStyle";
this.comboBoxConfigStyle.Size = new System.Drawing.Size(216, 22);
this.comboBoxConfigStyle.TabIndex = 18;
//
// checkBoxCreateConfig
//
this.checkBoxCreateConfig.Checked = true;
this.checkBoxCreateConfig.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxCreateConfig.Location = new System.Drawing.Point(8, 8);
this.checkBoxCreateConfig.Name = "checkBoxCreateConfig";
this.checkBoxCreateConfig.Size = new System.Drawing.Size(208, 24);
this.checkBoxCreateConfig.TabIndex = 17;
this.checkBoxCreateConfig.Text = "Create configuration file:";
//
// checkBoxModifyBuildEvent
//
this.checkBoxModifyBuildEvent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxModifyBuildEvent.Checked = true;
this.checkBoxModifyBuildEvent.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxModifyBuildEvent.Location = new System.Drawing.Point(8, 56);
this.checkBoxModifyBuildEvent.Name = "checkBoxModifyBuildEvent";
this.checkBoxModifyBuildEvent.Size = new System.Drawing.Size(432, 24);
this.checkBoxModifyBuildEvent.TabIndex = 15;
this.checkBoxModifyBuildEvent.Text = "Modify project Pre-build Event to generate stubs on each build";
//
// checkBoxSeparateStubs
//
this.checkBoxSeparateStubs.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxSeparateStubs.Location = new System.Drawing.Point(8, 128);
this.checkBoxSeparateStubs.Name = "checkBoxSeparateStubs";
this.checkBoxSeparateStubs.Size = new System.Drawing.Size(432, 24);
this.checkBoxSeparateStubs.TabIndex = 12;
this.checkBoxSeparateStubs.Text = "Compile stubs to a separate DLL";
//
// checkBoxAddAttributesToAssemblyInfo
//
this.checkBoxAddAttributesToAssemblyInfo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxAddAttributesToAssemblyInfo.Checked = true;
this.checkBoxAddAttributesToAssemblyInfo.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxAddAttributesToAssemblyInfo.Location = new System.Drawing.Point(8, 32);
this.checkBoxAddAttributesToAssemblyInfo.Name = "checkBoxAddAttributesToAssemblyInfo";
this.checkBoxAddAttributesToAssemblyInfo.Size = new System.Drawing.Size(432, 24);
this.checkBoxAddAttributesToAssemblyInfo.TabIndex = 11;
this.checkBoxAddAttributesToAssemblyInfo.Text = "Add necessary attributes to the AssemblyInfo file";
//
// checkBoxCreateKeyGen
//
this.checkBoxCreateKeyGen.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxCreateKeyGen.Checked = true;
this.checkBoxCreateKeyGen.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxCreateKeyGen.Location = new System.Drawing.Point(8, 80);
this.checkBoxCreateKeyGen.Name = "checkBoxCreateKeyGen";
this.checkBoxCreateKeyGen.Size = new System.Drawing.Size(432, 24);
this.checkBoxCreateKeyGen.TabIndex = 14;
this.checkBoxCreateKeyGen.Text = "Create KeyGen table in the database if it does not exist";
//
// checkBoxDisableIdentityColumns
//
this.checkBoxDisableIdentityColumns.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxDisableIdentityColumns.Location = new System.Drawing.Point(8, 104);
this.checkBoxDisableIdentityColumns.Name = "checkBoxDisableIdentityColumns";
this.checkBoxDisableIdentityColumns.Size = new System.Drawing.Size(432, 24);
this.checkBoxDisableIdentityColumns.TabIndex = 13;
this.checkBoxDisableIdentityColumns.Text = "Disable IDENTITY columns";
//
// linkLabelDisableIdentityColumns
//
this.linkLabelDisableIdentityColumns.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelDisableIdentityColumns.Location = new System.Drawing.Point(448, 104);
this.linkLabelDisableIdentityColumns.Name = "linkLabelDisableIdentityColumns";
this.linkLabelDisableIdentityColumns.Size = new System.Drawing.Size(56, 23);
this.linkLabelDisableIdentityColumns.TabIndex = 23;
this.linkLabelDisableIdentityColumns.TabStop = true;
this.linkLabelDisableIdentityColumns.Text = "Explain";
this.linkLabelDisableIdentityColumns.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabelDisableIdentityColumns.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelDisableIdentityColumns_LinkClicked);
//
// linkLabelSeparateStubs
//
this.linkLabelSeparateStubs.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelSeparateStubs.Location = new System.Drawing.Point(448, 128);
this.linkLabelSeparateStubs.Name = "linkLabelSeparateStubs";
this.linkLabelSeparateStubs.Size = new System.Drawing.Size(56, 23);
this.linkLabelSeparateStubs.TabIndex = 26;
this.linkLabelSeparateStubs.TabStop = true;
this.linkLabelSeparateStubs.Text = "Explain";
this.linkLabelSeparateStubs.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabelSeparateStubs.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelSeparateStubs_LinkClicked);
//
// linkLabelModifyBuildEvent
//
this.linkLabelModifyBuildEvent.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelModifyBuildEvent.Location = new System.Drawing.Point(448, 56);
this.linkLabelModifyBuildEvent.Name = "linkLabelModifyBuildEvent";
this.linkLabelModifyBuildEvent.Size = new System.Drawing.Size(56, 23);
this.linkLabelModifyBuildEvent.TabIndex = 25;
this.linkLabelModifyBuildEvent.TabStop = true;
this.linkLabelModifyBuildEvent.Text = "Explain";
this.linkLabelModifyBuildEvent.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabelModifyBuildEvent.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelModifyBuildEvent_LinkClicked);
//
// linkLabelCreateConfig
//
this.linkLabelCreateConfig.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelCreateConfig.Location = new System.Drawing.Point(448, 8);
this.linkLabelCreateConfig.Name = "linkLabelCreateConfig";
this.linkLabelCreateConfig.Size = new System.Drawing.Size(56, 23);
this.linkLabelCreateConfig.TabIndex = 19;
this.linkLabelCreateConfig.TabStop = true;
this.linkLabelCreateConfig.Text = "Explain";
this.linkLabelCreateConfig.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabelCreateConfig.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelCreateConfig_LinkClicked);
//
// linkLabelAddAttributes
//
this.linkLabelAddAttributes.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelAddAttributes.Location = new System.Drawing.Point(448, 32);
this.linkLabelAddAttributes.Name = "linkLabelAddAttributes";
this.linkLabelAddAttributes.Size = new System.Drawing.Size(56, 23);
this.linkLabelAddAttributes.TabIndex = 21;
this.linkLabelAddAttributes.TabStop = true;
this.linkLabelAddAttributes.Text = "Explain";
this.linkLabelAddAttributes.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabelAddAttributes.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelAddAttributes_LinkClicked);
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.panelAdvancedOptions);
this.groupBox1.Location = new System.Drawing.Point(8, 112);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(520, 224);
this.groupBox1.TabIndex = 12;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Advanced Options";
this.groupBox1.Visible = false;
//
// checkBoxGenerateSchema
//
this.checkBoxGenerateSchema.Checked = true;
this.checkBoxGenerateSchema.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxGenerateSchema.Location = new System.Drawing.Point(8, 56);
this.checkBoxGenerateSchema.Name = "checkBoxGenerateSchema";
this.checkBoxGenerateSchema.Size = new System.Drawing.Size(440, 24);
this.checkBoxGenerateSchema.TabIndex = 23;
this.checkBoxGenerateSchema.Text = "Create approximate mapping schema by reverse-engineering the database";
//
// linkLabelGenerateSchema
//
this.linkLabelGenerateSchema.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelGenerateSchema.Location = new System.Drawing.Point(456, 56);
this.linkLabelGenerateSchema.Name = "linkLabelGenerateSchema";
this.linkLabelGenerateSchema.Size = new System.Drawing.Size(56, 23);
this.linkLabelGenerateSchema.TabIndex = 24;
this.linkLabelGenerateSchema.TabStop = true;
this.linkLabelGenerateSchema.Text = "Explain";
this.linkLabelGenerateSchema.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabelGenerateSchema.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelGenerateSchema_LinkClicked);
//
// buttonAdvancedOptions
//
this.buttonAdvancedOptions.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonAdvancedOptions.Location = new System.Drawing.Point(8, 112);
this.buttonAdvancedOptions.Name = "buttonAdvancedOptions";
this.buttonAdvancedOptions.Size = new System.Drawing.Size(128, 23);
this.buttonAdvancedOptions.TabIndex = 25;
this.buttonAdvancedOptions.Text = "Advanced Options";
this.buttonAdvancedOptions.Click += new System.EventHandler(this.buttonAdvancedOptions_Click);
//
// linkLabelGenerateStubs
//
this.linkLabelGenerateStubs.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelGenerateStubs.Location = new System.Drawing.Point(456, 80);
this.linkLabelGenerateStubs.Name = "linkLabelGenerateStubs";
this.linkLabelGenerateStubs.Size = new System.Drawing.Size(56, 23);
this.linkLabelGenerateStubs.TabIndex = 24;
this.linkLabelGenerateStubs.TabStop = true;
this.linkLabelGenerateStubs.Text = "Explain";
this.linkLabelGenerateStubs.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabelGenerateStubs.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelGenerateStubs_LinkClicked);
//
// WizardPageOptions
//
this.Controls.Add(this.buttonAdvancedOptions);
this.Controls.Add(this.checkBoxGenerateSchema);
this.Controls.Add(this.linkLabelGenerateSchema);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.checkBoxGenerateStubs);
this.Controls.Add(this.linkLabelGenerateStubs);
this.EnableFinish = true;
this.EnableNext = false;
this.Name = "WizardPageOptions";
this.Size = new System.Drawing.Size(536, 344);
this.Load += new System.EventHandler(this.WizardPageOptions_Load);
this.panelAdvancedOptions.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void WizardPageOptions_Load(object sender, System.EventArgs e)
{
comboBoxConfigStyle.SelectedIndex = 0;
}
private void OpenDocUrl(string url)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "iexplore.exe";
psi.Arguments = "http://sooda.sourceforge.net/documentation.html?from=wizard#" + url;
psi.UseShellExecute = true;
System.Diagnostics.Process.Start(psi);
}
internal void FillResult(WizardResult result)
{
result.ReverseEngineerDatabase = checkBoxGenerateSchema.Checked;
result.SeparateStubs = checkBoxSeparateStubs.Checked;
result.ModifyBuildEvent = checkBoxModifyBuildEvent.Checked;
result.ModifyAssemblyInfo = checkBoxAddAttributesToAssemblyInfo.Checked;
result.DisableIdentityColumns = checkBoxDisableIdentityColumns.Checked;
result.CreateAppConfigFile = checkBoxCreateConfig.Checked && comboBoxConfigStyle.SelectedIndex == 0;
result.CreateSoodaXmlConfigFile = checkBoxCreateConfig.Checked && comboBoxConfigStyle.SelectedIndex == 1;
result.CreateKeyGenTable = checkBoxCreateKeyGen.Checked;
}
private void buttonViewAdvancedOptions_Click(object sender, System.EventArgs e)
{
}
private void buttonAdvancedOptions_Click(object sender, System.EventArgs e)
{
groupBox1.Visible = true;
buttonAdvancedOptions.Visible = false;
}
private void linkLabelGenerateSchema_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
OpenDocUrl("soodaschematoolgenschema");
}
private void linkLabelGenerateStubs_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
OpenDocUrl("compilation");
}
private void linkLabelCreateConfig_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
OpenDocUrl("configuration");
}
private void linkLabelAddAttributes_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
OpenDocUrl("assemblyinfo");
}
private void linkLabelModifyBuildEvent_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
OpenDocUrl("compilationvisualstudio");
}
private void linkLabelCreateKeyGen_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
OpenDocUrl("keygeneration");
}
private void linkLabelDisableIdentityColumns_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
OpenDocUrl("keygeneration");
}
private void linkLabelSeparateStubs_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
OpenDocUrl("compilationprocessseparate");
}
}
}
| |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
#if WINDOWS_UWP
using Windows.UI.Xaml;
#else
using System.Windows;
#endif
namespace ReactNative.UIManager
{
/// <summary>
/// Class responsible for knowing how to create and update views of a given
/// type. It is also responsible for creating and updating
/// <see cref="ReactShadowNode"/> subclasses used for calculating position
/// and size for the corresponding native view.
/// </summary>
public abstract class DependencyObjectViewManager<TDependencyObject, TReactShadowNode> : IViewManager
where TDependencyObject : DependencyObject
where TReactShadowNode : ReactShadowNode
{
/// <summary>
/// The name of this view manager. This will be the name used to
/// reference this view manager from JavaScript.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// The <see cref="Type"/> instance that represents the type of shadow
/// node that this manager will return from
/// <see cref="CreateShadowNodeInstance"/>.
///
/// This method will be used in the bridge initialization phase to
/// collect properties exposed using the <see cref="Annotations.ReactPropAttribute"/>
/// annotation from the <see cref="ReactShadowNode"/> subclass.
/// </summary>
public virtual Type ShadowNodeType
{
get
{
return typeof(TReactShadowNode);
}
}
/// <summary>
/// The commands map for the view manager.
/// </summary>
public virtual IReadOnlyDictionary<string, object> CommandsMap { get; }
/// <summary>
/// The exported custom bubbling event types.
/// </summary>
public virtual IReadOnlyDictionary<string, object> ExportedCustomBubblingEventTypeConstants { get; }
/// <summary>
/// The exported custom direct event types.
/// </summary>
public virtual IReadOnlyDictionary<string, object> ExportedCustomDirectEventTypeConstants { get; }
/// <summary>
/// The exported view constants.
/// </summary>
public virtual IReadOnlyDictionary<string, object> ExportedViewConstants { get; }
/// <summary>
/// Creates a shadow node for the view manager.
/// </summary>
/// <returns>The shadow node instance.</returns>
public IReadOnlyDictionary<string, string> NativeProperties
{
get
{
return ViewManagersPropertyCache.GetNativePropertiesForView(GetType(), ShadowNodeType);
}
}
/// <summary>
/// Update the properties of the given view.
/// </summary>
/// <param name="viewToUpdate">The view to update.</param>
/// <param name="props">The properties.</param>
public void UpdateProperties(TDependencyObject viewToUpdate, ReactStylesDiffMap props)
{
var propertySetters =
ViewManagersPropertyCache.GetNativePropertySettersForViewManagerType(GetType());
var keys = props.Keys;
foreach (var key in keys)
{
var setter = default(IPropertySetter);
if (propertySetters.TryGetValue(key, out setter))
{
setter.UpdateViewManagerProperty(this, viewToUpdate, props);
}
}
OnAfterUpdateTransaction(viewToUpdate);
}
/// <summary>
/// Creates a view and installs event emitters on it.
/// </summary>
/// <param name="reactContext">The context.</param>
/// <returns>The view.</returns>
public TDependencyObject CreateView(ThemedReactContext reactContext)
{
var view = CreateViewInstance(reactContext);
AddEventEmitters(reactContext, view);
// TODO: enable touch intercepting view parents
return view;
}
/// <summary>
/// Called when view is detached from view hierarchy and allows for
/// additional cleanup by the <see cref="IViewManager"/>
/// subclass.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view.</param>
/// <remarks>
/// Derived classes do not need to call this base method.
/// </remarks>
public virtual void OnDropViewInstance(ThemedReactContext reactContext, TDependencyObject view)
{
}
/// <summary>
/// This method should return the subclass of <see cref="ReactShadowNode"/>
/// which will be then used for measuring the position and size of the
/// view.
/// </summary>
/// <remarks>
/// In most cases, this will just return an instance of
/// <see cref="ReactShadowNode"/>.
/// </remarks>
/// <returns>The shadow node instance.</returns>
public abstract TReactShadowNode CreateShadowNodeInstance();
/// <summary>
/// Implement this method to receive optional extra data enqueued from
/// the corresponding instance of <see cref="ReactShadowNode"/> in
/// <see cref="ReactShadowNode.OnCollectExtraUpdates"/>.
/// </summary>
/// <param name="root">The root view.</param>
/// <param name="extraData">The extra data.</param>
public abstract void UpdateExtraData(TDependencyObject root, object extraData);
/// <summary>
/// Implement this method to receive events/commands directly from
/// JavaScript through the <see cref="UIManagerModule"/>.
/// </summary>
/// <param name="view">
/// The view instance that should receive the command.
/// </param>
/// <param name="commandId">Identifer for the command.</param>
/// <param name="args">Optional arguments for the command.</param>
public virtual void ReceiveCommand(TDependencyObject view, int commandId, JArray args)
{
}
/// <summary>
/// Gets the dimensions of the view.
/// </summary>
/// <param name="view">The view.</param>
/// <returns>The view dimensions.</returns>
public abstract Dimensions GetDimensions(TDependencyObject view);
/// <summary>
/// Sets the dimensions of the view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="dimensions">The output buffer.</param>
public abstract void SetDimensions(TDependencyObject view, Dimensions dimensions);
/// <summary>
/// Creates a new view instance of type <typeparamref name="TDependencyObject"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <returns>The view instance.</returns>
protected abstract TDependencyObject CreateViewInstance(ThemedReactContext reactContext);
/// <summary>
/// Subclasses can override this method to install custom event
/// emitters on the given view.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view instance.</param>
/// <remarks>
/// Consider overriding this method if your view needs to emit events
/// besides basic touch events to JavaScript (e.g., scroll events).
/// </remarks>
protected virtual void AddEventEmitters(ThemedReactContext reactContext, TDependencyObject view)
{
}
/// <summary>
/// Callback that will be triggered after all properties are updated in
/// the current update transation (all <see cref="Annotations.ReactPropAttribute"/> handlers
/// for properties updated in the current transaction have been called).
/// </summary>
/// <param name="view">The view.</param>
protected virtual void OnAfterUpdateTransaction(TDependencyObject view)
{
}
#region IViewManager
void IViewManager.UpdateProperties(DependencyObject viewToUpdate, ReactStylesDiffMap props)
{
UpdateProperties((TDependencyObject)viewToUpdate, props);
}
DependencyObject IViewManager.CreateView(ThemedReactContext reactContext)
{
return CreateView(reactContext);
}
void IViewManager.OnDropViewInstance(ThemedReactContext reactContext, DependencyObject view)
{
OnDropViewInstance(reactContext, (TDependencyObject)view);
}
ReactShadowNode IViewManager.CreateShadowNodeInstance()
{
return CreateShadowNodeInstance();
}
void IViewManager.UpdateExtraData(DependencyObject root, object extraData)
{
UpdateExtraData((TDependencyObject)root, extraData);
}
void IViewManager.ReceiveCommand(DependencyObject view, int commandId, JArray args)
{
ReceiveCommand((TDependencyObject)view, commandId, args);
}
Dimensions IViewManager.GetDimensions(DependencyObject view)
{
return GetDimensions((TDependencyObject)view);
}
void IViewManager.SetDimensions(DependencyObject view, Dimensions dimensions)
{
SetDimensions((TDependencyObject)view, dimensions);
}
#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.
/*=============================================================================
**
**
**
** Purpose: Class for creating and managing a threadpool
**
**
=============================================================================*/
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Internal.Runtime.CompilerServices;
namespace System.Threading
{
internal static class ThreadPoolGlobals
{
public static readonly int processorCount = Environment.ProcessorCount;
public static volatile bool threadPoolInitialized;
public static bool enableWorkerTracking;
public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
/// <summary>Shim used to invoke <see cref="IAsyncStateMachineBox.MoveNext"/> of the supplied <see cref="IAsyncStateMachineBox"/>.</summary>
internal static readonly Action<object?> s_invokeAsyncStateMachineBox = state =>
{
if (!(state is IAsyncStateMachineBox box))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state);
return;
}
box.MoveNext();
};
}
[StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing
internal sealed class ThreadPoolWorkQueue
{
internal static class WorkStealingQueueList
{
#pragma warning disable CA1825 // avoid the extra generic instantation for Array.Empty<T>(); this is the only place we'll ever create this array
private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0];
#pragma warning restore CA1825
public static WorkStealingQueue[] Queues => _queues;
public static void Add(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = _queues;
Debug.Assert(Array.IndexOf(oldQueues, queue) == -1);
var newQueues = new WorkStealingQueue[oldQueues.Length + 1];
Array.Copy(oldQueues, 0, newQueues, 0, oldQueues.Length);
newQueues[^1] = queue;
if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
public static void Remove(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = _queues;
if (oldQueues.Length == 0)
{
return;
}
int pos = Array.IndexOf(oldQueues, queue);
if (pos == -1)
{
Debug.Fail("Should have found the queue");
return;
}
var newQueues = new WorkStealingQueue[oldQueues.Length - 1];
if (pos == 0)
{
Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length);
}
else if (pos == oldQueues.Length - 1)
{
Array.Copy(oldQueues, 0, newQueues, 0, newQueues.Length);
}
else
{
Array.Copy(oldQueues, 0, newQueues, 0, pos);
Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos);
}
if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
}
internal sealed class WorkStealingQueue
{
private const int INITIAL_SIZE = 32;
internal volatile object?[] m_array = new object[INITIAL_SIZE]; // SOS's ThreadPool command depends on this name
private volatile int m_mask = INITIAL_SIZE - 1;
#if DEBUG
// in debug builds, start at the end so we exercise the index reset logic.
private const int START_INDEX = int.MaxValue;
#else
private const int START_INDEX = 0;
#endif
private volatile int m_headIndex = START_INDEX;
private volatile int m_tailIndex = START_INDEX;
private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false);
public void LocalPush(object obj)
{
int tail = m_tailIndex;
// We're going to increment the tail; if we'll overflow, then we need to reset our counts
if (tail == int.MaxValue)
{
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_tailIndex == int.MaxValue)
{
//
// Rather than resetting to zero, we'll just mask off the bits we don't care about.
// This way we don't need to rearrange the items already in the queue; they'll be found
// correctly exactly where they are. One subtlety here is that we need to make sure that
// if head is currently < tail, it remains that way. This happens to just fall out from
// the bit-masking, because we only do this if tail == int.MaxValue, meaning that all
// bits are set, so all of the bits we're keeping will also be set. Thus it's impossible
// for the head to end up > than the tail, since you can't set any more bits than all of
// them.
//
m_headIndex &= m_mask;
m_tailIndex = tail = m_tailIndex & m_mask;
Debug.Assert(m_headIndex <= m_tailIndex);
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: true);
}
}
// When there are at least 2 elements' worth of space, we can take the fast path.
if (tail < m_headIndex + m_mask)
{
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
else
{
// We need to contend with foreign pops, so we lock.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
int head = m_headIndex;
int count = m_tailIndex - m_headIndex;
// If there is still space (one left), just add the element.
if (count >= m_mask)
{
// We're full; expand the queue by doubling its size.
var newArray = new object?[m_array.Length << 1];
for (int i = 0; i < m_array.Length; i++)
newArray[i] = m_array[(i + head) & m_mask];
// Reset the field values, incl. the mask.
m_array = newArray;
m_headIndex = 0;
m_tailIndex = tail = count;
m_mask = (m_mask << 1) | 1;
}
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
public bool LocalFindAndPop(object obj)
{
// Fast path: check the tail. If equal, we can skip the lock.
if (m_array[(m_tailIndex - 1) & m_mask] == obj)
{
object? unused = LocalPop();
Debug.Assert(unused == null || unused == obj);
return unused != null;
}
// Else, do an O(N) search for the work item. The theory of work stealing and our
// inlining logic is that most waits will happen on recently queued work. And
// since recently queued work will be close to the tail end (which is where we
// begin our search), we will likely find it quickly. In the worst case, we
// will traverse the whole local queue; this is typically not going to be a
// problem (although degenerate cases are clearly an issue) because local work
// queues tend to be somewhat shallow in length, and because if we fail to find
// the work item, we are about to block anyway (which is very expensive).
for (int i = m_tailIndex - 2; i >= m_headIndex; i--)
{
if (m_array[i & m_mask] == obj)
{
// If we found the element, block out steals to avoid interference.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
// If we encountered a race condition, bail.
if (m_array[i & m_mask] == null)
return false;
// Otherwise, null out the element.
Volatile.Write(ref m_array[i & m_mask], null);
// And then check to see if we can fix up the indexes (if we're at
// the edge). If we can't, we just leave nulls in the array and they'll
// get filtered out eventually (but may lead to superfluous resizing).
if (i == m_tailIndex)
m_tailIndex--;
else if (i == m_headIndex)
m_headIndex++;
return true;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
return false;
}
public object? LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null;
private object? LocalPopCore()
{
while (true)
{
int tail = m_tailIndex;
if (m_headIndex >= tail)
{
return null;
}
// Decrement the tail using a fence to ensure subsequent read doesn't come before.
tail--;
Interlocked.Exchange(ref m_tailIndex, tail);
// If there is no interaction with a take, we can head down the fast path.
if (m_headIndex <= tail)
{
int idx = tail & m_mask;
object? obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Interaction with takes: 0 or 1 elements left.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_headIndex <= tail)
{
// Element still available. Take it.
int idx = tail & m_mask;
object? obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// If we encountered a race condition and element was stolen, restore the tail.
m_tailIndex = tail + 1;
return null;
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
}
public bool CanSteal => m_headIndex < m_tailIndex;
public object? TrySteal(ref bool missedSteal)
{
while (true)
{
if (CanSteal)
{
bool taken = false;
try
{
m_foreignLock.TryEnter(ref taken);
if (taken)
{
// Increment head, and ensure read of tail doesn't move before it (fence).
int head = m_headIndex;
Interlocked.Exchange(ref m_headIndex, head + 1);
if (head < m_tailIndex)
{
int idx = head & m_mask;
object? obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Failed, restore head.
m_headIndex = head;
}
}
}
finally
{
if (taken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
missedSteal = true;
}
return null;
}
}
public int Count
{
get
{
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
return Math.Max(0, m_tailIndex - m_headIndex);
}
finally
{
if (lockTaken)
{
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
}
}
internal bool loggingEnabled;
internal readonly ConcurrentQueue<object> workItems = new ConcurrentQueue<object>(); // SOS's ThreadPool command depends on this name
private readonly Internal.PaddingFor32 pad1;
private volatile int numOutstandingThreadRequests = 0;
private readonly Internal.PaddingFor32 pad2;
public ThreadPoolWorkQueue()
{
loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
}
public ThreadPoolWorkQueueThreadLocals GetOrCreateThreadLocals() =>
ThreadPoolWorkQueueThreadLocals.threadLocals ?? CreateThreadLocals();
[MethodImpl(MethodImplOptions.NoInlining)]
private ThreadPoolWorkQueueThreadLocals CreateThreadLocals()
{
Debug.Assert(ThreadPoolWorkQueueThreadLocals.threadLocals == null);
return ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this);
}
internal void EnsureThreadRequested()
{
//
// If we have not yet requested #procs threads, then request a new thread.
//
// CoreCLR: Note that there is a separate count in the VM which has already been incremented
// by the VM by the time we reach this point.
//
int count = numOutstandingThreadRequests;
while (count < ThreadPoolGlobals.processorCount)
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count);
if (prev == count)
{
ThreadPool.RequestWorkerThread();
break;
}
count = prev;
}
}
internal void MarkThreadRequestSatisfied()
{
//
// One of our outstanding thread requests has been satisfied.
// Decrement the count so that future calls to EnsureThreadRequested will succeed.
//
// CoreCLR: Note that there is a separate count in the VM which has already been decremented
// by the VM by the time we reach this point.
//
int count = numOutstandingThreadRequests;
while (count > 0)
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count);
if (prev == count)
{
break;
}
count = prev;
}
}
public void Enqueue(object callback, bool forceGlobal)
{
Debug.Assert((callback is IThreadPoolWorkItem) ^ (callback is Task));
if (loggingEnabled)
System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(callback);
ThreadPoolWorkQueueThreadLocals? tl = null;
if (!forceGlobal)
tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
if (null != tl)
{
tl.workStealingQueue.LocalPush(callback);
}
else
{
workItems.Enqueue(callback);
}
EnsureThreadRequested();
}
internal bool LocalFindAndPop(object callback)
{
ThreadPoolWorkQueueThreadLocals? tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
return tl != null && tl.workStealingQueue.LocalFindAndPop(callback);
}
public object? Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal)
{
WorkStealingQueue localWsq = tl.workStealingQueue;
object? callback;
if ((callback = localWsq.LocalPop()) == null && // first try the local queue
!workItems.TryDequeue(out callback)) // then try the global queue
{
// finally try to steal from another thread's local queue
WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
int c = queues.Length;
Debug.Assert(c > 0, "There must at least be a queue for this thread.");
int maxIndex = c - 1;
int i = tl.random.Next(c);
while (c > 0)
{
i = (i < maxIndex) ? i + 1 : 0;
WorkStealingQueue otherQueue = queues[i];
if (otherQueue != localWsq && otherQueue.CanSteal)
{
callback = otherQueue.TrySteal(ref missedSteal);
if (callback != null)
{
break;
}
}
c--;
}
}
return callback;
}
public long LocalCount
{
get
{
long count = 0;
foreach (WorkStealingQueue workStealingQueue in WorkStealingQueueList.Queues)
{
count += workStealingQueue.Count;
}
return count;
}
}
public long GlobalCount => workItems.Count;
/// <summary>
/// Dispatches work items to this thread.
/// </summary>
/// <returns>
/// <c>true</c> if this thread did as much work as was available or its quantum expired.
/// <c>false</c> if this thread stopped working early.
/// </returns>
internal static bool Dispatch()
{
ThreadPoolWorkQueue outerWorkQueue = ThreadPoolGlobals.workQueue;
//
// Save the start time
//
int startTickCount = Environment.TickCount;
//
// Update our records to indicate that an outstanding request for a thread has now been fulfilled.
// From this point on, we are responsible for requesting another thread if we stop working for any
// reason, and we believe there might still be work in the queue.
//
// CoreCLR: Note that if this thread is aborted before we get a chance to request another one, the VM will
// record a thread request on our behalf. So we don't need to worry about getting aborted right here.
//
outerWorkQueue.MarkThreadRequestSatisfied();
// Has the desire for logging changed since the last time we entered?
outerWorkQueue.loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
//
// Assume that we're going to need another thread if this one returns to the VM. We'll set this to
// false later, but only if we're absolutely certain that the queue is empty.
//
bool needAnotherThread = true;
try
{
//
// Set up our thread-local data
//
// Use operate on workQueue local to try block so it can be enregistered
ThreadPoolWorkQueue workQueue = outerWorkQueue;
ThreadPoolWorkQueueThreadLocals tl = workQueue.GetOrCreateThreadLocals();
Thread currentThread = tl.currentThread;
// Start on clean ExecutionContext and SynchronizationContext
currentThread._executionContext = null;
currentThread._synchronizationContext = null;
//
// Loop until our quantum expires or there is no work.
//
while (ThreadPool.KeepDispatching(startTickCount))
{
bool missedSteal = false;
// Use operate on workItem local to try block so it can be enregistered
object? workItem = workQueue.Dequeue(tl, ref missedSteal);
if (workItem == null)
{
//
// No work.
// If we missed a steal, though, there may be more work in the queue.
// Instead of looping around and trying again, we'll just request another thread. Hopefully the thread
// that owns the contended work-stealing queue will pick up its own workitems in the meantime,
// which will be more efficient than this thread doing it anyway.
//
needAnotherThread = missedSteal;
// Tell the VM we're returning normally, not because Hill Climbing asked us to return.
return true;
}
if (workQueue.loggingEnabled)
System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolDequeueWorkObject(workItem);
//
// If we found work, there may be more work. Ask for another thread so that the other work can be processed
// in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue.
//
workQueue.EnsureThreadRequested();
//
// Execute the workitem outside of any finally blocks, so that it can be aborted if needed.
//
if (ThreadPoolGlobals.enableWorkerTracking)
{
bool reportedStatus = false;
try
{
ThreadPool.ReportThreadStatus(isWorking: true);
reportedStatus = true;
if (workItem is Task task)
{
task.ExecuteFromThreadPool(currentThread);
}
else
{
Debug.Assert(workItem is IThreadPoolWorkItem);
Unsafe.As<IThreadPoolWorkItem>(workItem).Execute();
}
}
finally
{
if (reportedStatus)
ThreadPool.ReportThreadStatus(isWorking: false);
}
}
else if (workItem is Task task)
{
// Check for Task first as it's currently faster to type check
// for Task and then Unsafe.As for the interface, rather than
// vice versa, in particular when the object implements a bunch
// of interfaces.
task.ExecuteFromThreadPool(currentThread);
}
else
{
Debug.Assert(workItem is IThreadPoolWorkItem);
Unsafe.As<IThreadPoolWorkItem>(workItem).Execute();
}
currentThread.ResetThreadPoolThread();
// Release refs
workItem = null;
// Return to clean ExecutionContext and SynchronizationContext
ExecutionContext.ResetThreadPoolThread(currentThread);
//
// Notify the VM that we executed this workitem. This is also our opportunity to ask whether Hill Climbing wants
// us to return the thread to the pool or not.
//
if (!ThreadPool.NotifyWorkItemComplete())
return false;
}
// If we get here, it's because our quantum expired. Tell the VM we're returning normally.
return true;
}
finally
{
//
// If we are exiting for any reason other than that the queue is definitely empty, ask for another
// thread to pick up where we left off.
//
if (needAnotherThread)
outerWorkQueue.EnsureThreadRequested();
}
}
}
// Simple random number generator. We don't need great randomness, we just need a little and for it to be fast.
internal struct FastRandom // xorshift prng
{
private uint _w, _x, _y, _z;
public FastRandom(int seed)
{
_x = (uint)seed;
_w = 88675123;
_y = 362436069;
_z = 521288629;
}
public int Next(int maxValue)
{
Debug.Assert(maxValue > 0);
uint t = _x ^ (_x << 11);
_x = _y; _y = _z; _z = _w;
_w = _w ^ (_w >> 19) ^ (t ^ (t >> 8));
return (int)(_w % (uint)maxValue);
}
}
// Holds a WorkStealingQueue, and removes it from the list when this object is no longer referenced.
internal sealed class ThreadPoolWorkQueueThreadLocals
{
[ThreadStatic]
public static ThreadPoolWorkQueueThreadLocals? threadLocals;
public readonly ThreadPoolWorkQueue workQueue;
public readonly ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue;
public readonly Thread currentThread;
public FastRandom random = new FastRandom(Thread.CurrentThread.ManagedThreadId); // mutable struct, do not copy or make readonly
public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq)
{
workQueue = tpq;
workStealingQueue = new ThreadPoolWorkQueue.WorkStealingQueue();
ThreadPoolWorkQueue.WorkStealingQueueList.Add(workStealingQueue);
currentThread = Thread.CurrentThread;
}
~ThreadPoolWorkQueueThreadLocals()
{
// Transfer any pending workitems into the global queue so that they will be executed by another thread
if (null != workStealingQueue)
{
if (null != workQueue)
{
object? cb;
while ((cb = workStealingQueue.LocalPop()) != null)
{
Debug.Assert(null != cb);
workQueue.Enqueue(cb, forceGlobal: true);
}
}
ThreadPoolWorkQueue.WorkStealingQueueList.Remove(workStealingQueue);
}
}
}
public delegate void WaitCallback(object? state);
public delegate void WaitOrTimerCallback(object? state, bool timedOut); // signaled or timed out
internal abstract class QueueUserWorkItemCallbackBase : IThreadPoolWorkItem
{
#if DEBUG
private int executed;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1821:RemoveEmptyFinalizers")]
~QueueUserWorkItemCallbackBase()
{
Interlocked.MemoryBarrier(); // ensure that an old cached value is not read below
Debug.Assert(
executed != 0, "A QueueUserWorkItemCallback was never called!");
}
#endif
public virtual void Execute()
{
#if DEBUG
GC.SuppressFinalize(this);
Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1),
"A QueueUserWorkItemCallback was called twice!");
#endif
}
}
internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase
{
private WaitCallback? _callback; // SOS's ThreadPool command depends on this name
private readonly object? _state;
private readonly ExecutionContext _context;
private static readonly Action<QueueUserWorkItemCallback> s_executionContextShim = quwi =>
{
Debug.Assert(quwi._callback != null);
WaitCallback callback = quwi._callback;
quwi._callback = null;
callback(quwi._state);
};
internal QueueUserWorkItemCallback(WaitCallback callback, object? state, ExecutionContext context)
{
Debug.Assert(context != null);
_callback = callback;
_state = state;
_context = context;
}
public override void Execute()
{
base.Execute();
ExecutionContext.RunForThreadPoolUnsafe(_context, s_executionContextShim, this);
}
}
internal sealed class QueueUserWorkItemCallback<TState> : QueueUserWorkItemCallbackBase
{
private Action<TState>? _callback; // SOS's ThreadPool command depends on this name
private readonly TState _state;
private readonly ExecutionContext _context;
internal QueueUserWorkItemCallback(Action<TState> callback, TState state, ExecutionContext context)
{
Debug.Assert(callback != null);
_callback = callback;
_state = state;
_context = context;
}
public override void Execute()
{
base.Execute();
Debug.Assert(_callback != null);
Action<TState> callback = _callback;
_callback = null;
ExecutionContext.RunForThreadPoolUnsafe(_context, callback, in _state);
}
}
internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUserWorkItemCallbackBase
{
private WaitCallback? _callback; // SOS's ThreadPool command depends on this name
private readonly object? _state;
internal QueueUserWorkItemCallbackDefaultContext(WaitCallback callback, object? state)
{
Debug.Assert(callback != null);
_callback = callback;
_state = state;
}
public override void Execute()
{
ExecutionContext.CheckThreadPoolAndContextsAreDefault();
base.Execute();
Debug.Assert(_callback != null);
WaitCallback callback = _callback;
_callback = null;
callback(_state);
// ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default
}
}
internal sealed class QueueUserWorkItemCallbackDefaultContext<TState> : QueueUserWorkItemCallbackBase
{
private Action<TState>? _callback; // SOS's ThreadPool command depends on this name
private readonly TState _state;
internal QueueUserWorkItemCallbackDefaultContext(Action<TState> callback, TState state)
{
Debug.Assert(callback != null);
_callback = callback;
_state = state;
}
public override void Execute()
{
ExecutionContext.CheckThreadPoolAndContextsAreDefault();
base.Execute();
Debug.Assert(_callback != null);
Action<TState> callback = _callback;
_callback = null;
callback(_state);
// ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default
}
}
internal sealed class _ThreadPoolWaitOrTimerCallback
{
private readonly WaitOrTimerCallback _waitOrTimerCallback;
private readonly ExecutionContext? _executionContext;
private readonly object? _state;
private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object? state, bool flowExecutionContext)
{
_waitOrTimerCallback = waitOrTimerCallback;
_state = state;
if (flowExecutionContext)
{
// capture the exection context
_executionContext = ExecutionContext.Capture();
}
}
private static void WaitOrTimerCallback_Context_t(object? state) =>
WaitOrTimerCallback_Context(state, timedOut: true);
private static void WaitOrTimerCallback_Context_f(object? state) =>
WaitOrTimerCallback_Context(state, timedOut: false);
private static void WaitOrTimerCallback_Context(object? state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state!;
helper._waitOrTimerCallback(helper._state, timedOut);
}
// call back helper
internal static void PerformWaitOrTimerCallback(_ThreadPoolWaitOrTimerCallback helper, bool timedOut)
{
Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
// call directly if it is an unsafe call OR EC flow is suppressed
ExecutionContext? context = helper._executionContext;
if (context == null)
{
WaitOrTimerCallback callback = helper._waitOrTimerCallback;
callback(helper._state, timedOut);
}
else
{
ExecutionContext.Run(context, timedOut ? _ccbt : _ccbf, helper);
}
}
}
public static partial class ThreadPool
{
[CLSCompliant(false)]
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, true);
}
[CLSCompliant(false)]
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
long millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (millisecondsTimeOutInterval > (uint)int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
long millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (millisecondsTimeOutInterval > (uint)int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
TimeSpan timeout,
bool executeOnlyOnce
)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (tm > (long)int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
TimeSpan timeout,
bool executeOnlyOnce
)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (tm > (long)int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, false);
}
public static bool QueueUserWorkItem(WaitCallback callBack) =>
QueueUserWorkItem(callBack, null);
public static bool QueueUserWorkItem(WaitCallback callBack, object? state)
{
if (callBack == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
EnsureInitialized();
ExecutionContext? context = ExecutionContext.Capture();
object tpcallBack = (context == null || context.IsDefault) ?
new QueueUserWorkItemCallbackDefaultContext(callBack!, state) :
(object)new QueueUserWorkItemCallback(callBack!, state, context);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
return true;
}
public static bool QueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal)
{
if (callBack == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
EnsureInitialized();
ExecutionContext? context = ExecutionContext.Capture();
object tpcallBack = (context == null || context.IsDefault) ?
new QueueUserWorkItemCallbackDefaultContext<TState>(callBack!, state) :
(object)new QueueUserWorkItemCallback<TState>(callBack!, state, context);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: !preferLocal);
return true;
}
public static bool UnsafeQueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal)
{
if (callBack == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
// If the callback is the runtime-provided invocation of an IAsyncStateMachineBox,
// then we can queue the Task state directly to the ThreadPool instead of
// wrapping it in a QueueUserWorkItemCallback.
//
// This occurs when user code queues its provided continuation to the ThreadPool;
// internally we call UnsafeQueueUserWorkItemInternal directly for Tasks.
if (ReferenceEquals(callBack, ThreadPoolGlobals.s_invokeAsyncStateMachineBox))
{
if (!(state is IAsyncStateMachineBox))
{
// The provided state must be the internal IAsyncStateMachineBox (Task) type
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state);
}
UnsafeQueueUserWorkItemInternal((object)state!, preferLocal);
return true;
}
EnsureInitialized();
ThreadPoolGlobals.workQueue.Enqueue(
new QueueUserWorkItemCallbackDefaultContext<TState>(callBack!, state), forceGlobal: !preferLocal);
return true;
}
public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object? state)
{
if (callBack == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
EnsureInitialized();
object tpcallBack = new QueueUserWorkItemCallbackDefaultContext(callBack!, state);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
return true;
}
public static bool UnsafeQueueUserWorkItem(IThreadPoolWorkItem callBack, bool preferLocal)
{
if (callBack == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
if (callBack is Task)
{
// Prevent code from queueing a derived Task that also implements the interface,
// as that would bypass Task.Start and its safety checks.
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.callBack);
}
UnsafeQueueUserWorkItemInternal(callBack!, preferLocal);
return true;
}
internal static void UnsafeQueueUserWorkItemInternal(object callBack, bool preferLocal)
{
Debug.Assert((callBack is IThreadPoolWorkItem) ^ (callBack is Task));
EnsureInitialized();
ThreadPoolGlobals.workQueue.Enqueue(callBack, forceGlobal: !preferLocal);
}
// This method tries to take the target callback out of the current thread's queue.
internal static bool TryPopCustomWorkItem(object workItem)
{
Debug.Assert(null != workItem);
return
ThreadPoolGlobals.threadPoolInitialized && // if not initialized, so there's no way this workitem was ever queued.
ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
}
// Get all workitems. Called by TaskScheduler in its debugger hooks.
internal static IEnumerable<object> GetQueuedWorkItems()
{
// Enumerate global queue
foreach (object workItem in ThreadPoolGlobals.workQueue.workItems)
{
yield return workItem;
}
// Enumerate each local queue
foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues)
{
if (wsq != null && wsq.m_array != null)
{
object?[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
object? item = items[i];
if (item != null)
{
yield return item;
}
}
}
}
}
internal static IEnumerable<object> GetLocallyQueuedWorkItems()
{
ThreadPoolWorkQueue.WorkStealingQueue? wsq = ThreadPoolWorkQueueThreadLocals.threadLocals?.workStealingQueue;
if (wsq != null && wsq.m_array != null)
{
object?[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
object? item = items[i];
if (item != null)
yield return item;
}
}
}
internal static IEnumerable<object> GetGloballyQueuedWorkItems() => ThreadPoolGlobals.workQueue.workItems;
private static object[] ToObjectArray(IEnumerable<object> workitems)
{
int i = 0;
foreach (object item in workitems)
{
i++;
}
object[] result = new object[i];
i = 0;
foreach (object item in workitems)
{
if (i < result.Length) // just in case someone calls us while the queues are in motion
result[i] = item;
i++;
}
return result;
}
// This is the method the debugger will actually call, if it ends up calling
// into ThreadPool directly. Tests can use this to simulate a debugger, as well.
internal static object[] GetQueuedWorkItemsForDebugger() =>
ToObjectArray(GetQueuedWorkItems());
internal static object[] GetGloballyQueuedWorkItemsForDebugger() =>
ToObjectArray(GetGloballyQueuedWorkItems());
internal static object[] GetLocallyQueuedWorkItemsForDebugger() =>
ToObjectArray(GetLocallyQueuedWorkItems());
/// <summary>
/// Gets the number of work items that are currently queued to be processed.
/// </summary>
/// <remarks>
/// For a thread pool implementation that may have different types of work items, the count includes all types that can
/// be tracked, which may only be the user work items including tasks. Some implementations may also include queued
/// timer and wait callbacks in the count. On Windows, the count is unlikely to include the number of pending IO
/// completions, as they get posted directly to an IO completion port.
/// </remarks>
public static long PendingWorkItemCount
{
get
{
ThreadPoolWorkQueue workQueue = ThreadPoolGlobals.workQueue;
return workQueue.LocalCount + workQueue.GlobalCount + PendingUnmanagedWorkItemCount;
}
}
}
}
| |
using System;
using NUnit.Framework;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Bluetooth.AttributeIds;
#if FX1_1
using NotImplementedException = System.NotSupportedException;
#endif
namespace InTheHand.Net.Tests.Sdp2
{
[TestFixture]
public class DumpCompleteThirdPartyRecords
{
internal static void DoTestSmart(String expected, byte[] recordBytes, params Type[] attributeIdEnumDefiningTypes)
{
ServiceRecordParser parser = new ServiceRecordParser();
parser.SkipUnhandledElementTypes = true;
ServiceRecord record = parser.Parse(recordBytes);
DoTestSmart(expected, record, attributeIdEnumDefiningTypes);
}
internal static void DoTestSmart(String expected, ServiceRecord record, params Type[] attributeIdEnumDefiningTypes)
{
string result = ServiceRecordUtilities.Dump(record, attributeIdEnumDefiningTypes);
Assert.AreEqual(expected, result);
}
internal static void DoTestSmart_NotSkip(String expected, byte[] recordBytes, params Type[] attributeIdEnumDefiningTypes)
{
ServiceRecordParser parser = new ServiceRecordParser();
parser.SkipUnhandledElementTypes = false;
ServiceRecord record = parser.Parse(recordBytes);
//
string result = ServiceRecordUtilities.Dump(record, attributeIdEnumDefiningTypes);
Assert.AreEqual(expected, result);
}
internal static void DoTestSmart_RecordStaticMethod(String expected, byte[] recordBytes, params Type[] attributeIdEnumDefiningTypes)
{
ServiceRecord record = ServiceRecord.CreateServiceRecordFromBytes(recordBytes);
//
string result = ServiceRecordUtilities.Dump(record, attributeIdEnumDefiningTypes);
Assert.AreEqual(expected, result);
}
internal static void DoTestRaw(String expected, byte[] recordBytes)
{
ServiceRecordParser parser = new ServiceRecordParser();
parser.SkipUnhandledElementTypes = true;
ServiceRecord record = parser.Parse(recordBytes);
//
string result = ServiceRecordUtilities.DumpRaw(record);
Assert.AreEqual(expected, result);
}
[Test]
public void UnsupportedCharacterEncoding()
{
DoTestSmart(Data_CompleteThirdPartyRecords.UnsupportedCharacterEncodingDump,
Data_CompleteThirdPartyRecords.UnsupportedCharacterEncoding,
typeof(ServiceDiscoveryServerAttributeId));
}
[Test]
public void Xp1()
{
DoTestSmart(Data_CompleteThirdPartyRecords.Xp1Dump, Data_CompleteThirdPartyRecords.Xp1Sdp,
typeof(ServiceDiscoveryServerAttributeId));
}
[Test]
public void Xp1WithNullForEnums()
{
DoTestSmart(Data_CompleteThirdPartyRecords.Xp1DumpWithNullForEnums,
Data_CompleteThirdPartyRecords.Xp1Sdp,
null);
}
[Test]
public void Xp1Raw()
{
DoTestRaw(Data_CompleteThirdPartyRecords.Xp1DumpRaw, Data_CompleteThirdPartyRecords.Xp1Sdp);
}
[Test]
public void XpFsquirtOpp()
{
DoTestSmart(Data_CompleteThirdPartyRecords.XpFsquirtOpp_Dump, Data_CompleteThirdPartyRecords.XpFsquirtOpp,
typeof(ServiceDiscoveryServerAttributeId));
}
[Test]
public void PalmOsOpp()
{
DoTestSmart_RecordStaticMethod(Data_CompleteThirdPartyRecords.PalmOsOppDump, Data_CompleteThirdPartyRecords.PalmOsOpp,
typeof(ServiceDiscoveryServerAttributeId));
}
[Test]
public void LogitechF0228A_Headset()
{
DoTestSmart(Data_CompleteThirdPartyRecords.LogitechF0228A_Headset_Dump, Data_CompleteThirdPartyRecords.LogitechF0228A_Headset);
}
[Test]
public void LogitechF0228A_Handsfree()
{
DoTestSmart_RecordStaticMethod(Data_CompleteThirdPartyRecords.LogitechF0228A_Handsfree_Dump, Data_CompleteThirdPartyRecords.LogitechF0228A_Handsfree);
}
[Test]
public void BluetoothListener_DefaultRecord_ChatSample()
{
DoTestSmart(Data_CompleteThirdPartyRecords.BluetoothListener_DefaultRecord_ChatSample_Dump, Data_CompleteThirdPartyRecords.BluetoothListener_DefaultRecord_ChatSample);
}
//[Test]
//public void GuidByteOrdering()
//{
// Guid aa = new Guid("{00102030-4050-6070-8090-a0b0c0d0e0f0}");
// Console.WriteLine("aa: " + aa);
// byte[] aaBytes = aa.ToByteArray();
// Console.WriteLine("aa byteArray: " + BitConverter.ToString(aaBytes));
// //--
// Guid bb = new Guid(aaBytes);
// Console.WriteLine("bb: " + bb);
// byte[] bbBytes = bb.ToByteArray();
// Console.WriteLine("bb byteArray: " + BitConverter.ToString(bbBytes));
// //--
// System.IO.BinaryReader rdr = new System.IO.BinaryReader(
// new System.IO.MemoryStream(aaBytes, false));
// Guid cc = new Guid(rdr.ReadInt32(), rdr.ReadInt16(), rdr.ReadInt16(), rdr.ReadByte(), rdr.ReadByte(),
// rdr.ReadByte(), rdr.ReadByte(), rdr.ReadByte(), rdr.ReadByte(), rdr.ReadByte(), rdr.ReadByte());
// Console.WriteLine("cc: " + cc);
// byte[] ccBytes = cc.ToByteArray();
// Console.WriteLine("cc byteArray: " + BitConverter.ToString(ccBytes));
//}
[Test]
public void XpB_0of2Sdp()
{
DoTestSmart(Data_CompleteThirdPartyRecords.XpB_0of2Sdp_Dump, Data_CompleteThirdPartyRecords.XpB_0of2Sdp,
typeof(ServiceDiscoveryServerAttributeId));
}
[Test]
public void XpB_1of2_1115()
{
DoTestSmart(Data_CompleteThirdPartyRecords.XpB_1of2_1115_Dump, Data_CompleteThirdPartyRecords.XpB_1of2_1115
/*typeof(ServiceDiscoveryServerAttributeId)*/);
}
[Test]
public void SonyEricsson_Hid_Record()
{
// This should the normal test of binary record to dump, but we don't have the binary...
ServiceRecord rcd = Data_CompleteThirdPartyRecords.SonyEricsson_Hid_Record;
String expectedDump = Data_CompleteThirdPartyRecords.SonyEricsson_Hid_Record_Dump;
String dump = ServiceRecordUtilities.Dump(rcd);
Assert.AreEqual(expectedDump, dump, "dump");
//DoTest(/*!!!SonyEricsson_Hid_Record*/InTheHand.Net.Tests.Sdp2.Data_CompleteThirdPartyRecords.BluetoothListener_DefaultRecord_ChatSample,
// Data_SdpCreator_CompleteRecords.SonyEricsson_Hid_Record);
}
[Test]
public void SonyEricssonMv100_Imaging_hasUint64()
{
DoTestSmart(Data_CompleteThirdPartyRecords.SonyEricssonMv100_Imaging_hasUint64_Dump, Data_CompleteThirdPartyRecords.SonyEricssonMv100_Imaging_hasUint64);
}
//--------------------------------------------------------------
//[Test]
//public void KingSt_d2_DumpRaw_all()
//{
// ServiceRecordParser parser = new ServiceRecordParser();
// parser.SkipUnhandledElementTypes = true;
// byte[][] input = {
// Data_CompleteThirdPartyRecords.KingSt_d2r1,
// Data_CompleteThirdPartyRecords.KingSt_d2r2,
// Data_CompleteThirdPartyRecords.KingSt_d2r3,
// Data_CompleteThirdPartyRecords.KingSt_d2r4,
// Data_CompleteThirdPartyRecords.KingSt_d2r5,
// Data_CompleteThirdPartyRecords.KingSt_d2r6,
// Data_CompleteThirdPartyRecords.KingSt_d2r1_withPdlUuid128s,
// Data_CompleteThirdPartyRecords.KingSt_d2r1_withPdlUuid128sNonBluetoothBase,
// };
// foreach (byte[] cur in input) {
// ServiceRecord record = parser.Parse(cur);
// String dumpR = ServiceRecordUtilities.DumpRaw(record);
// Console.WriteLine("----");
// Console.WriteLine(dumpR);
// }
//}
[Test]
public void KingSt_d2r1_hasPdlUuid32s_Dump()
{
DoTestSmart(Data_CompleteThirdPartyRecords.KingSt_d2r1_Dump, Data_CompleteThirdPartyRecords.KingSt_d2r1);
}
[Test]
public void KingSt_d2r1_withPdlUuid128s_Dump()
{
DoTestSmart(Data_CompleteThirdPartyRecords.KingSt_d2r1_withPdlUuid128s_Dump, Data_CompleteThirdPartyRecords.KingSt_d2r1_withPdlUuid128s);
}
//[Test]
//public void KingSt_d2_Dump_all()
//{
// ServiceRecordParser parser = new ServiceRecordParser();
// parser.SkipUnhandledElementTypes = true;
// byte[][] input = {
// Data_CompleteThirdPartyRecords.KingSt_d2r1,
// Data_CompleteThirdPartyRecords.KingSt_d2r2,
// Data_CompleteThirdPartyRecords.KingSt_d2r3,
// Data_CompleteThirdPartyRecords.KingSt_d2r4,
// Data_CompleteThirdPartyRecords.KingSt_d2r5,
// Data_CompleteThirdPartyRecords.KingSt_d2r6,
// Data_CompleteThirdPartyRecords.KingSt_d2r1_withPdlUuid128s,
// Data_CompleteThirdPartyRecords.KingSt_d2r1_withPdlUuid128sNonBluetoothBase,
// };
// foreach (byte[] cur in input) {
// ServiceRecord record = parser.Parse(cur);
// String dumpR = ServiceRecordUtilities.Dump(record);
// Console.WriteLine("----");
// Console.WriteLine(dumpR);
// }
//}
[Test]
public void SemcHla_Dump()
{
DoTestSmart(Data_CompleteThirdPartyRecords.SemcHla_Dump,
Data_CompleteThirdPartyRecords.SemcHla);
}
[Test]
public void BenqE72ImagingResponder_Dump()
{
DoTestSmart_NotSkip(Data_CompleteThirdPartyRecords.BenqE72ImagingResponder_Dump,
Data_CompleteThirdPartyRecords.BenqE72ImagingResponder);
}
[Test]
public void BppDirectPrinting_TheMajor()
{
DoTestSmart_NotSkip(Data_CompleteThirdPartyRecords.BppDirectPrinting_TheMajor_Dump,
Data_CompleteThirdPartyRecords.BppDirectPrinting_TheMajor);
}
}//class
[TestFixture]
public class DumpMiscRecords
{
public const string CrLf = "\r\n";
public static readonly byte[] OneNilBytes = {
0x35, 4,
0x09,0x12,0x34,
0x00,
};
public static readonly byte[] OneNilBytes_AttrIdTopBitSet = {
0x35, 4,
0x09,0x92,0x34,
0x00,
};
public static readonly byte[] OneUnknownTypeBytes = {
0x35, 6,
0x09,0x12,0x34,
0x91,0x01,0x02
};
public static readonly byte[] BadUtf8StringBytes = {
0x35, 9,
0x09,0x12,0x34,
0x25,4,
0xFF,0x61,0x62,0xFF,
};
public static readonly byte[] ProtocolDescriptorListAlternativesBytes = {
0x35, 39,
0x09,0x00,0x04, // ProtocolDescriptorList
0x3D, 34, //Alternative
0x35, 15,
0x35, 6,
0x19,0x01,0x00, 0x09,0x10,0x01, // uuid16 0x0100, uint16 0x1001
0x35, 5,
0x19,0x00,0x03, 0x08,0x10,
0x35, 15,
0x35, 6,
0x19,0x01,0x00, 0x09,0x10,0x02, // uuid16 0x0100, uint16 0x1002
0x35, 5,
0x19,0x90,0x03, 0x08,0x10,
};
public const string ProtocolDescriptorListAlternatives_Dump
= "AttrId: 0x0004 -- ProtocolDescriptorList" + CrLf
+ "ElementAlternative" + CrLf
+ " ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x100" + " -- L2CapProtocol" + CrLf
+ " UInt16: 0x1001" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x3" + " -- RFCommProtocol" + CrLf
+ " UInt8: 0x10" + CrLf
+ " ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x100" + " -- L2CapProtocol" + CrLf
+ " UInt16: 0x1002" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x9003" + CrLf
+ " UInt8: 0x10" + CrLf
+ " ( ( L2Cap, PSM=0x1001 ), ( Rfcomm, ChannelNumber=16 ) )" + CrLf
+ " ( ( L2Cap, PSM=0x1002 ), ( 0x9003, ... ) )" + CrLf;
public static readonly byte[] OneUuid32Bytes = {
0x35, 8,
0x09,0x12,0x34,
0x1a,0xFF,0x23,0x40,0x01
};
//----
public static readonly byte[] PdlUuid16AlsoTopBitSet_Bytes ={
0x35, 0x14,
0x09, 0x00, 0x04,
0x35, 0x0f,
0x35, 0x06,
0x19, 0x01, 0x00,
0x09, 0xf0, 0xf9,
0x35, 0x05,
0x19, 0xfe, 0xba,
0x8, 0x18
};
public static readonly byte[] PdlUuid32AlsoTopBitSet_Bytes ={
0x35, 0x1f,
0x09, 0x00, 0x04,
0x35, 0x1a,
0x35, 0x08,
0x1a, 0x00, 0x00, 0x01, 0x00,
0x09, 0xf0, 0xf9,
0x35, 0x07,
0x1a, 0x10, 0x00, 0xfe, 0xba,
0x8, 0x17,
0x35, 0x05,
0x1a, 0xfe, 0x00, 0x01, 0xba,
};
public static readonly byte[] PdlUuid128_Bytes ={
0x35, 0x43,
0x09, 0x00, 0x04,
0x35, 0x3e,
0x35, 0x14,
0x1c, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB,
0x09, 0xf0, 0xf9,
0x35, 0x13,
0x1c, 0x10, 0x00, 0xfe, 0xba,
0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB,
0x8, 0x17,
0x35, 0x11,
0x1c, 0xfe, 0x00, 0x01, 0xba,
0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB,
};
const string PdlUuid16AlsoTopBitSet_Dump
= "AttrId: 0x0004 -- ProtocolDescriptorList" + CrLf
+ "ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x100" + " -- L2CapProtocol" + CrLf
+ " UInt16: 0xF0F9" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0xFEBA" + CrLf
+ " UInt8: 0x18" + CrLf
+ "( ( L2Cap, PSM=0xF0F9 ), ( 0xFEBA, ... ) )" + CrLf;
const string PdlUuid32AlsoTopBitSet_Dump
= "AttrId: 0x0004 -- ProtocolDescriptorList" + CrLf
+ "ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid32: 0x100" + " -- L2CapProtocol" + CrLf
+ " UInt16: 0xF0F9" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid32: 0x1000FEBA" + CrLf
+ " UInt8: 0x17" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid32: 0xFE0001BA" + CrLf
+ "( ( L2Cap, PSM=0xF0F9 ), ( 1000feba-0000-1000-8000-00805f9b34fb, ... ),"
+ " ( fe0001ba-0000-1000-8000-00805f9b34fb ) )" + CrLf;
const string PdlUuid128_Dump
= "AttrId: 0x0004 -- ProtocolDescriptorList" + CrLf
+ "ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid128: 00000100-0000-1000-8000-00805f9b34fb" + " -- L2CapProtocol" + CrLf
+ " UInt16: 0xF0F9" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid128: 1000feba-0000-1000-8000-00805f9b34fb" + CrLf
+ " UInt8: 0x17" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid128: fe0001ba-0000-1000-8000-00805f9b34fb" + CrLf
+ "( ( L2Cap, PSM=0xF0F9 ), ( 1000feba-0000-1000-8000-00805f9b34fb, ... ),"
+ " ( fe0001ba-0000-1000-8000-00805f9b34fb ) )" + CrLf;
const string PdlUuid128_DumpRaw
= "AttrId: 0x0004" + CrLf
+ "ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid128: 00000100-0000-1000-8000-00805f9b34fb" + CrLf
+ " UInt16: 0xF0F9" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid128: 1000feba-0000-1000-8000-00805f9b34fb" + CrLf
+ " UInt8: 0x17" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid128: fe0001ba-0000-1000-8000-00805f9b34fb" + CrLf
;
const string PdlTcsBinCordless_Dump
= "AttrId: 0x0004 -- ProtocolDescriptorList" + CrLf
+ "ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x100" + " -- L2CapProtocol" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x5" + " -- TcsBinProtocol" + CrLf
+ "( ( L2Cap ), ( TcsBin ) )" + CrLf
;
const string PdlHid_Dump
= "AttrId: 0x0004 -- ProtocolDescriptorList" + CrLf
+ "ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x100" + " -- L2CapProtocol" + CrLf
+ " UInt16: 0x69" + "" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x11" + " -- HidpProtocol" + CrLf
+ "( ( L2Cap, PSM=0x69 ), ( Hidp ) )" + CrLf
;
const string PdlNonHackProtocolId_Dump
= "AttrId: 0x0004 -- ProtocolDescriptorList" + CrLf
+ "ElementSequence" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x100 -- L2CapProtocol" + CrLf
+ " UInt16: 0x17" + CrLf
+ " ElementSequence" + CrLf
+ " Uuid16: 0x17 -- AvctpProtocol" + CrLf
+ " UInt16: 0x103" + CrLf
+ "( ( L2Cap, PSM=0x17 ), ( Avctp, ... ) )" + CrLf
;
[Test]
public void PdlUuid16AlsoTopBitSet()
{
DumpCompleteThirdPartyRecords.DoTestSmart(PdlUuid16AlsoTopBitSet_Dump, PdlUuid16AlsoTopBitSet_Bytes);
}
[Test]
public void PdlUuid32AlsoTopBitSet()
{
DumpCompleteThirdPartyRecords.DoTestSmart(PdlUuid32AlsoTopBitSet_Dump, PdlUuid32AlsoTopBitSet_Bytes);
}
[Test]
public void PdlUuid128()
{
DumpCompleteThirdPartyRecords.DoTestSmart(PdlUuid128_Dump, PdlUuid128_Bytes);
}
[Test]
public void PdlUuid128_Raw()
{
DumpCompleteThirdPartyRecords.DoTestRaw(PdlUuid128_DumpRaw, PdlUuid128_Bytes);
}
[Test]
public void PdlUndefinedHackProtoId()
{
// Protocol Descriptor List
// Protocol #0 UUID L2CAP
// Protocol #1 UUID TCS-BIN-CORDLESS
const UInt16 SvcClass16ProtocolL2CAP = 0x000000100;
const UInt16 SvcClass16ProtocolTcsBinCordless = 0x00000005;
ServiceRecord record = new ServiceRecord(
new ServiceAttribute(UniversalAttributeId.ProtocolDescriptorList,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement(ElementType.Uuid16, SvcClass16ProtocolL2CAP)),
new ServiceElement(ElementType.ElementSequence,
new ServiceElement(ElementType.Uuid16, SvcClass16ProtocolTcsBinCordless)))
));
DumpCompleteThirdPartyRecords.DoTestSmart(PdlTcsBinCordless_Dump, record);
}
[Test]
public void PdlDefinedButUnhandledHackProtoId()
{
//Protocol Descriptor List 0x0004 M
//Protocol Descriptor #0 Data Element Sequence M
// Protocol ID L2CAP UUID L2CAP, Note 1 M
// Parameter #0 PSM Uint16 HID_Control M
//Protocol Descriptor #1 Data Element Sequence M
// ProtocolID HID UUID HID Protocol, Note 1 M
const UInt16 SvcClass16ProtocolL2CAP = 0x000000100;
const UInt16 SvcClass16ProtocolHid = 0x00000011; //BluetoothService.HidpProtocol
const UInt16 PsmHidp = 0x69;
ServiceRecord record = new ServiceRecord(
new ServiceAttribute(UniversalAttributeId.ProtocolDescriptorList,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement(ElementType.Uuid16, SvcClass16ProtocolL2CAP),
new ServiceElement(ElementType.UInt16, PsmHidp)),
new ServiceElement(ElementType.ElementSequence,
new ServiceElement(ElementType.Uuid16, SvcClass16ProtocolHid))
)));
DumpCompleteThirdPartyRecords.DoTestSmart(PdlHid_Dump, record);
}
[Test]
public void PdlNonHackProtocolId_Avctp()
{
//const UInt16 SvcClass16Avcrp = 0x110E;
const UInt16 SvcClass16AvcrpController_ = 0x110F;
Guid SvcClass128AvcrpController = BluetoothService.CreateBluetoothUuid(SvcClass16AvcrpController_);
//
const UInt16 SvcClass16ProtocolL2CAP = 0x0100;
//Debug_Assert_CorrectShortUuid(SvcClass16ProtocolL2CAP, BluetoothService.L2CapProtocol);
const UInt16 SvcClass16ProtocolAvctp = 0x0017;
//Debug_Assert_CorrectShortUuid(SvcClass16ProtocolAvctp, BluetoothService.AvctpProtocol);
//
const UInt16 PsmAvcrp = 0x0017;
//const UInt16 PsmAvcrpBrowsing = 0x001B;
//
const UInt16 Version = 0x0103; // 1.3.......
//
var layer0 = new ServiceElement(ElementType.ElementSequence,
new ServiceElement(ElementType.Uuid16, SvcClass16ProtocolL2CAP),
new ServiceElement(ElementType.UInt16, PsmAvcrp));
var layer1 = new ServiceElement(ElementType.ElementSequence,
new ServiceElement(ElementType.Uuid16, SvcClass16ProtocolAvctp),
new ServiceElement(ElementType.UInt16, Version));
ServiceElement pdl = new ServiceElement(ElementType.ElementSequence,
layer0, layer1);
ServiceRecord record = new ServiceRecord(
new ServiceAttribute(UniversalAttributeId.ProtocolDescriptorList, pdl));
DumpCompleteThirdPartyRecords.DoTestSmart(PdlNonHackProtocolId_Dump, record);
}
//--------
public static readonly byte[] DeepString_BadUtf8StringBytes = {
0x35, 9+2,
0x09,0x12,0x34,
0x35,6,
0x25,4,
0xFF,0x61,0x62,0xFF,
};
// 'a\u00F6b\u2020d'
public static readonly byte[] DeepString_GoodUtf8StringBytes = {
0x35, 15,
0x09,0x12,0x34,
0x35,10,
0x25,8,
0x61, 0xC3,0xB6, 0x62, 0xE2,0x80,0xA0, 0x64
};
public static readonly byte[] DeepString_GoodUtf16BEStringBytes = {
0x35, 17,
0x09,0x12,0x34,
0x35,12,
0x25,10,
0,0x61, 0,0xF6, 0,0x62, 0x20,0x20, 0,0x64
};
public static readonly byte[] DeepString_GoodUtf16LEStringBytes = {
0x35, 17,
0x09,0x12,0x34,
0x35,12,
0x25,10,
0x61,0, 0xF6,0, 0x62,0, 0x20,0x20, 0x64,0
};
// Without the 0xF6, so UTF-16 sees it as valid!!!: 'ab\u2020d'
public static readonly byte[] DeepString_GoodUtf16BEStringBytes2 = {
0x35, 15,
0x09,0x12,0x34,
0x35,10,
0x25,08,
0,0x61, 0,0x62, 0x20,0x20, 0,0x64
};
public static readonly byte[] DeepString_GoodUtf16LEStringBytes2 = {
0x35, 15,
0x09,0x12,0x34,
0x35,10,
0x25,8,
0x61,0, 0x62,0, 0x20,0x20, 0x64,0
};
//----
[Test]
public void OneNil()
{
byte[] recordBytes = OneNilBytes;
const string expectedDump
= "AttrId: 0x1234" + CrLf
+ "Nil:" + CrLf;
DumpCompleteThirdPartyRecords.DoTestSmart(expectedDump, recordBytes);
}
[Test]
public void OneNil_Raw()
{
byte[] recordBytes = OneNilBytes;
const string expectedDump
= "AttrId: 0x1234" + CrLf
+ "Nil:" + CrLf;
DumpCompleteThirdPartyRecords.DoTestRaw(expectedDump, recordBytes);
}
[Test]
public void AttrIdTopBitSet()
{
byte[] recordBytes = OneNilBytes_AttrIdTopBitSet;
const string expectedDump
= "AttrId: 0x9234" + CrLf
+ "Nil:" + CrLf;
DumpCompleteThirdPartyRecords.DoTestSmart(expectedDump, recordBytes);
}
[Test]
public void AttrIdTopBitSet_Raw()
{
byte[] recordBytes = OneNilBytes_AttrIdTopBitSet;
const string expectedDump
= "AttrId: 0x9234" + CrLf
+ "Nil:" + CrLf;
DumpCompleteThirdPartyRecords.DoTestRaw(expectedDump, recordBytes);
}
[Test]
public void OneUnknownType()
{
byte[] recordBytes = OneUnknownTypeBytes;
const string expectedDump
= "AttrId: 0x1234" + CrLf
+ "Unknown: unknown" + CrLf;
DumpCompleteThirdPartyRecords.DoTestSmart(expectedDump, recordBytes);
}
[Test]
[ExpectedException(typeof(NotImplementedException), ExpectedMessage = "Element type: 18, SizeIndex: LengthTwoBytes, at offset: 5.")]
public void OneUnknownType_Strict()
{
byte[] recordBytes = OneUnknownTypeBytes;
ServiceRecordParser parser = new ServiceRecordParser();
parser.SkipUnhandledElementTypes = false;
parser.Parse(recordBytes);
}
[Test]
public void BadUtf8String()
{
const string expectedDump
= "AttrId: 0x1234" + CrLf
+ "TextString (Unknown/bad encoding):" + CrLf
+ "Length: 4, >>FF-61-62-FF<<" + CrLf;
DumpCompleteThirdPartyRecords.DoTestSmart(expectedDump, BadUtf8StringBytes);
}
[Test]
public void ProtocolDescriptorListAlternatives()
{
DumpCompleteThirdPartyRecords.DoTestSmart(ProtocolDescriptorListAlternatives_Dump, ProtocolDescriptorListAlternativesBytes);
}
[Test]
public void OneUuid32()
{
byte[] recordBytes = OneUuid32Bytes;
const string expectedDump
= "AttrId: 0x1234" + CrLf
+ "Uuid32: 0xFF234001" + CrLf;
DumpCompleteThirdPartyRecords.DoTestSmart(expectedDump, recordBytes);
}
[Test]
public void OneUInt128()
{
byte[] recordBytes = Data_SimpleRecords.OneUInt128_F123_E987;
const string expectedDump
= "AttrId: 0xF123" + CrLf
+ "UInt128: E9-87-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F-10" + CrLf;
DumpCompleteThirdPartyRecords.DoTestSmart(expectedDump, recordBytes);
}
[Test]
public void OneInt128()
{
byte[] recordBytes = Data_SimpleRecords.OneInt128_F123_E987;
const string expectedDump
= "AttrId: 0xF123" + CrLf
+ "Int128: E9-87-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F-10" + CrLf;
DumpCompleteThirdPartyRecords.DoTestSmart(expectedDump, recordBytes);
}
[Test]
public void OneUInt128_Raw()
{
byte[] recordBytes = Data_SimpleRecords.OneUInt128_F123_E987;
const string expectedDump
= "AttrId: 0xF123" + CrLf
+ "UInt128: E9-87-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F-10" + CrLf;
DumpCompleteThirdPartyRecords.DoTestRaw(expectedDump, recordBytes);
}
[Test]
public void OneInt128_Raw()
{
byte[] recordBytes = Data_SimpleRecords.OneInt128_F123_E987;
const string expectedDump
= "AttrId: 0xF123" + CrLf
+ "Int128: E9-87-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F-10" + CrLf;
DumpCompleteThirdPartyRecords.DoTestRaw(expectedDump, recordBytes);
}
//--------
[Test]
public void DeepString_BadUtf8String()
{
const string expectedDump
= "AttrId: 0x1234" + CrLf
+ "ElementSequence" + CrLf
+ " TextString (Unknown/bad encoding):" + CrLf
+ " Length: 4, >>FF-61-62-FF<<" + CrLf;
DumpCompleteThirdPartyRecords.DoTestSmart(expectedDump, DeepString_BadUtf8StringBytes);
}
const string ExpectedDump_DeepString
= "AttrId: 0x1234" + CrLf
+ "ElementSequence" + CrLf
+ " TextString (guessing UTF-8): 'a\u00F6b\u2020d'" + CrLf;
const string ExpectedDump_DeepStringBE_SeenAsBadEncoding
= "AttrId: 0x1234" + CrLf
+ "ElementSequence" + CrLf
+ " TextString (Unknown/bad encoding):" + CrLf
+ " Length: 10, >>00-61-00-F6-00-62-20-20-00-64<<" + CrLf;
const string ExpectedDump_DeepStringLE_SeenAsBadEncoding
= "AttrId: 0x1234" + CrLf
+ "ElementSequence" + CrLf
+ " TextString (Unknown/bad encoding):" + CrLf
+ " Length: 10, >>61-00-F6-00-62-00-20-20-64-00<<" + CrLf;
const string ExpectedDump_DeepString2BE_SeenAsBadEncoding
= "AttrId: 0x1234" + CrLf
+ "ElementSequence" + CrLf
+ " TextString (Unknown/bad encoding):" + CrLf
+ " Length: 8, >>00-61-00-62-20-20-00-64<<" + CrLf;
const string ExpectedDump_DeepString2LE_SeenAsBadEncoding
= "AttrId: 0x1234" + CrLf
+ "ElementSequence" + CrLf
+ " TextString (Unknown/bad encoding):" + CrLf
+ " Length: 8, >>61-00-62-00-20-20-64-00<<" + CrLf;
// Do we *really* want to produce string containing nulls!!!
const string ExpectedDump_DeepString2_AsBE
= "AttrId: 0x1234" + CrLf
+ "ElementSequence" + CrLf
+ " TextString (guessing UTF-8): '\u0000a\u0000b \u0000d'" + CrLf;
const string ExpectedDump_DeepString2_AsLE
= "AttrId: 0x1234" + CrLf
+ "ElementSequence" + CrLf
+ " TextString (guessing UTF-8): 'a\u0000b\u0000 d\u0000'" + CrLf;
[Test]
public void DeepString_GoodUtf8String()
{
DumpCompleteThirdPartyRecords.DoTestSmart(ExpectedDump_DeepString, DeepString_GoodUtf8StringBytes);
}
[Test]
public void DeepString_GoodUtf16BEString()
{
DumpCompleteThirdPartyRecords.DoTestSmart(ExpectedDump_DeepStringBE_SeenAsBadEncoding, DeepString_GoodUtf16BEStringBytes);
}
[Test]
public void DeepString_GoodUtf16LEString()
{
DumpCompleteThirdPartyRecords.DoTestSmart(ExpectedDump_DeepStringLE_SeenAsBadEncoding, DeepString_GoodUtf16LEStringBytes);
}
[Test]
public void DeepString_GoodUtf16BEString2()
{
DumpCompleteThirdPartyRecords.DoTestSmart(ExpectedDump_DeepString2BE_SeenAsBadEncoding, DeepString_GoodUtf16BEStringBytes2);
}
[Test]
public void DeepString_GoodUtf16LEString2()
{
DumpCompleteThirdPartyRecords.DoTestSmart(ExpectedDump_DeepString2LE_SeenAsBadEncoding, DeepString_GoodUtf16LEStringBytes2);
}
//----
[Test] // Copied from ServiceRecordBuilderTests.
public void CustomTwoFromOneWithHighAttrIdAdded()
{
// Rfcomm/StdSvcClass/SvcName
ServiceRecordBuilder bldr = new ServiceRecordBuilder();
bldr.AddServiceClass(BluetoothService.SerialPort);
bldr.ServiceName = "Hello World!";
ServiceAttribute attr2 = new ServiceAttribute(
0x8000,
ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, 0x80));
bldr.AddCustomAttribute(attr2);
ServiceAttribute attr2b = new ServiceAttribute(
0xFFFF,
ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, 255));
bldr.AddCustomAttribute(attr2b);
ServiceAttribute attr = new ServiceAttribute(
UniversalAttributeId.ServiceAvailability,
ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, 8));
bldr.AddCustomAttribute(attr);
DumpCompleteThirdPartyRecords.DoTestSmart(ServiceRecordBuilderTests_Data.CustomTwoFromOneWithHighAttrIdAdded, bldr.ServiceRecord);
}
}//class
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Glipho.OAuth.Providers.WebApiSample.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Net.Tests
{
public class WebUtilityTests
{
// HtmlEncode + HtmlDecode
public static IEnumerable<object[]> HtmlDecode_TestData()
{
yield return new object[] { "Hello! '"<&>\u2665♥\u00E7çç", "Hello! '\"<&>\u2665\u2665\u00E7\u00E7\u00E7" };
yield return new object[] { "Hello, world! \"<>\u2665\u00E7", "Hello, world! \"<>\u2665\u00E7" }; // No special chars
yield return new object[] { null, null };
yield return new object[] { "𣎴", char.ConvertFromUtf32(144308) };
}
[Theory]
[MemberData(nameof(HtmlDecode_TestData))]
public static void HtmlDecode(string value, string expected)
{
Assert.Equal(expected, WebUtility.HtmlDecode(value));
}
public static IEnumerable<object[]> HtmlEncode_TestData()
{
// Single quotes need to be encoded as ' rather than ' since ' is valid both for
// HTML and XHTML, but ' is valid only for XHTML.
// For more info: http://fishbowl.pastiche.org/2003/07/01/the_curse_of_apos/
yield return new object[] { "'", "'" };
yield return new object[] { "Hello! '\"<&>\u2665\u00E7 World", "Hello! '"<&>\u2665ç World" };
yield return new object[] { null, null };
yield return new object[] { "Hello, world!", "Hello, world!" }; // No special chars
yield return new object[] { char.ConvertFromUtf32(144308), "𣎴" }; // Default strict settings
}
[Theory]
[MemberData(nameof(HtmlEncode_TestData))]
public static void HtmlEncode(string value, string expected)
{
Assert.Equal(expected, WebUtility.HtmlEncode(value));
}
// Shared test data for UrlEncode + Decode and their ToBytes counterparts
public static IEnumerable<Tuple<string, string>> UrlDecode_SharedTestData()
{
// Recent change brings function inline with RFC 3986 to return hex-encoded chars in uppercase
yield return Tuple.Create("%2F%5C%22%09Hello!+%E2%99%A5%3F%2F%5C%22%09World!+%E2%99%A5%3F%E2%99%A5", "/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665");
yield return Tuple.Create("Hello, world", "Hello, world"); // No special chars
yield return Tuple.Create("%F0%90%8F%BF", "\uD800\uDFFF"); // Surrogate pair
}
public static IEnumerable<Tuple<string, string>> UrlEncode_SharedTestData()
{
// Recent change brings function inline with RFC 3986 to return hex-encoded chars in uppercase
yield return Tuple.Create("/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665", "%2F%5C%22%09Hello!+%E2%99%A5%3F%2F%5C%22%09World!+%E2%99%A5%3F%E2%99%A5");
yield return Tuple.Create("'", "%27");
yield return Tuple.Create("\uD800\uDFFF", "%F0%90%8F%BF"); // Surrogate pairs should be encoded as 4 bytes together
// TODO: Uncomment this block out when dotnet/corefx#7166 is fixed.
/*
// Tests for stray surrogate chars (all should be encoded as U+FFFD)
// Relevant GitHub issue: dotnet/corefx#7036
yield return Tuple.Create("\uD800", "%EF%BF%BD"); // High surrogate
yield return Tuple.Create("\uDC00", "%EF%BF%BD"); // Low surrogate
yield return Tuple.Create("\uDC00\uD800", "%EF%BF%BD%EF%BF%BD"); // Low + high
yield return Tuple.Create("\uD900\uDA00", "%EF%BF%BD%EF%BF%BD"); // High + high
yield return Tuple.Create("\uDE00\uDF00", "%EF%BF%BD%EF%BF%BD"); // Low + low
yield return Tuple.Create("!\uDB00@", "!%EF%BF%BD%40"); // Non-surrogate + high + non-surrogate
yield return Tuple.Create("#\uDD00$", "%23%EF%BF%BD%24"); // Non-surrogate + low + non-surrogate
*/
}
public static IEnumerable<object[]> UrlEncodeDecode_Roundtrip_SharedTestData()
{
yield return new object[] { "'" };
yield return new object[] { "http://www.microsoft.com" };
yield return new object[] { "/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665" };
yield return new object[] { "\uD800\uDFFF" }; // Surrogate pairs
yield return new object[] { CharRange('\uE000', '\uF8FF') }; // BMP private use chars
yield return new object[] { CharRange('\uFDD0', '\uFDEF') }; // Low BMP non-chars
// TODO: Uncomment when dotnet/corefx#7166 is fixed.
// yield return new object[] { "\uFFFE\uFFFF" }; // High BMP non-chars
yield return new object[] { CharRange('\0', '\u001F') }; // C0 controls
yield return new object[] { CharRange('\u0080', '\u009F') }; // C1 controls
yield return new object[] { CharRange('\u202A', '\u202E') }; // BIDI embedding and override
yield return new object[] { CharRange('\u2066', '\u2069') }; // BIDI isolate
yield return new object[] { "\uFEFF" }; // BOM
// Astral plane private use chars
yield return new object[] { CharRange(0xF0000, 0xFFFFD) };
yield return new object[] { CharRange(0x100000, 0x10FFFD) };
// Astral plane non-chars
yield return new object[] { "\U0001FFFE" };
yield return new object[] { "\U0001FFFF" };
yield return new object[] { CharRange(0x2FFFE, 0x10FFFF) };
}
// UrlEncode + UrlDecode
public static IEnumerable<object[]> UrlDecode_TestData()
{
foreach (var tuple in UrlDecode_SharedTestData())
yield return new object[] { tuple.Item1, tuple.Item2 };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(UrlDecode_TestData))]
public static void UrlDecode(string encodedValue, string expected)
{
Assert.Equal(expected, WebUtility.UrlDecode(encodedValue));
}
public static IEnumerable<object[]> UrlEncode_TestData()
{
foreach (var tuple in UrlEncode_SharedTestData())
yield return new object[] { tuple.Item1, tuple.Item2 };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(UrlEncode_TestData))]
public static void UrlEncode(string value, string expected)
{
Assert.Equal(expected, WebUtility.UrlEncode(value));
}
[Theory]
[MemberData(nameof(UrlEncodeDecode_Roundtrip_SharedTestData))]
public static void UrlEncodeDecode_Roundtrip(string value)
{
string encoded = WebUtility.UrlEncode(value);
Assert.Equal(value, WebUtility.UrlDecode(encoded));
}
// UrlEncode + DecodeToBytes
public static IEnumerable<object[]> UrlDecodeToBytes_TestData()
{
foreach (var tuple in UrlDecode_SharedTestData())
{
byte[] input = Encoding.UTF8.GetBytes(tuple.Item1);
byte[] output = Encoding.UTF8.GetBytes(tuple.Item2);
yield return new object[] { input, 0, input.Length, output };
}
yield return new object[] { null, 0, 0, null };
}
[Theory]
[MemberData(nameof(UrlDecodeToBytes_TestData))]
public static void UrlDecodeToBytes(byte[] value, int offset, int count, byte[] expected)
{
byte[] actual = WebUtility.UrlDecodeToBytes(value, offset, count);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlDecodeToBytes_Invalid()
{
Assert.Throws<ArgumentNullException>("bytes", () => WebUtility.UrlDecodeToBytes(null, 0, 1)); // Bytes is null
Assert.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlDecodeToBytes(new byte[1], -1, 1)); // Offset < 0
Assert.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlDecodeToBytes(new byte[1], 2, 1)); // Offset > bytes.Length
Assert.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlDecodeToBytes(new byte[1], 0, -1)); // Count < 0
Assert.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlDecodeToBytes(new byte[1], 0, 3)); // Count > bytes.Length
}
[Theory]
[InlineData("a", 0, 1)]
[InlineData("a", 1, 0)]
[InlineData("abc", 0, 3)]
[InlineData("abc", 1, 2)]
[InlineData("abc", 1, 1)]
[InlineData("abcd", 1, 2)]
[InlineData("abcd", 2, 2)]
public static void UrlEncodeToBytes_NothingToExpand_OutputMatchesSubInput(string inputString, int offset, int count)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(inputString);
byte[] subInputBytes = new byte[count];
Buffer.BlockCopy(inputBytes, offset, subInputBytes, 0, count);
Assert.Equal(inputString.Length, inputBytes.Length);
byte[] outputBytes = WebUtility.UrlEncodeToBytes(inputBytes, offset, count);
Assert.NotSame(inputBytes, outputBytes);
Assert.Equal(count, outputBytes.Length);
Assert.Equal(subInputBytes, outputBytes);
}
public static IEnumerable<object[]> UrlEncodeToBytes_TestData()
{
foreach (var tuple in UrlEncode_SharedTestData())
{
byte[] input = Encoding.UTF8.GetBytes(tuple.Item1);
byte[] output = Encoding.UTF8.GetBytes(tuple.Item2);
yield return new object[] { input, 0, input.Length, output };
}
yield return new object[] { null, 0, 0, null };
}
[Theory]
[MemberData(nameof(UrlEncodeToBytes_TestData))]
public static void UrlEncodeToBytes(byte[] value, int offset, int count, byte[] expected)
{
byte[] actual = WebUtility.UrlEncodeToBytes(value, offset, count);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlEncodeToBytes_Invalid()
{
Assert.Throws<ArgumentNullException>("bytes", () => WebUtility.UrlEncodeToBytes(null, 0, 1)); // Bytes is null
Assert.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlEncodeToBytes(new byte[1], -1, 1)); // Offset < 0
Assert.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlEncodeToBytes(new byte[1], 2, 1)); // Offset > bytes.Length
Assert.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlEncodeToBytes(new byte[1], 0, -1)); // Count < 0
Assert.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlEncodeToBytes(new byte[1], 0, 3)); // Count > bytes.Length
}
[Theory]
[MemberData(nameof(UrlEncodeDecode_Roundtrip_SharedTestData))]
public static void UrlEncodeDecodeToBytes_Roundtrip(string url)
{
byte[] input = Encoding.UTF8.GetBytes(url);
byte[] encoded = WebUtility.UrlEncodeToBytes(input, 0, input.Length);
Assert.Equal(input, WebUtility.UrlDecodeToBytes(encoded, 0, encoded.Length));
}
[Theory]
[InlineData("FooBarQuux", 3, 7, "BarQuux")]
public static void UrlEncodeToBytes_ExcludeIrrelevantData(string value, int offset, int count, string expected)
{
byte[] input = Encoding.UTF8.GetBytes(value);
byte[] encoded = WebUtility.UrlEncodeToBytes(input, offset, count);
string actual = Encoding.UTF8.GetString(encoded);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("FooBarQuux", 3, 7, "BarQuux")]
public static void UrlDecodeToBytes_ExcludeIrrelevantData(string value, int offset, int count, string expected)
{
byte[] input = Encoding.UTF8.GetBytes(value);
byte[] decoded = WebUtility.UrlDecodeToBytes(input, offset, count);
string actual = Encoding.UTF8.GetString(decoded);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlEncodeToBytes_NewArray()
{
// If no encoding is needed, the current implementation simply
// returns the input array to a method which then clones it.
// We have to make sure it always returns a new array, to
// prevent problems where the input array is changed if
// the output one is modified.
byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Encoding");
byte[] output = WebUtility.UrlEncodeToBytes(input, 0, input.Length);
Assert.NotSame(input, output);
}
[Fact]
public static void UrlDecodeToBytes_NewArray()
{
byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Decoding");
byte[] output = WebUtility.UrlDecodeToBytes(input, 0, input.Length);
Assert.NotSame(input, output);
}
public static string CharRange(int start, int end)
{
Debug.Assert(start <= end);
int capacity = end - start + 1;
var builder = new StringBuilder(capacity);
for (int i = start; i <= end; i++)
{
// 0 -> \0, 65 -> A, 0x10FFFF -> \U0010FFFF
builder.Append(char.ConvertFromUtf32(i));
}
return builder.ToString();
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Windows.Input;
using Sketching.Tool;
using Xamarin.Forms;
using Sketching.Tool.Arrow;
using Sketching.Tool.Circle;
using Sketching.Tool.Mark;
using Sketching.Tool.Oval;
using Sketching.Tool.Rectangle;
using Sketching.Tool.Stroke;
using Sketching.Tool.Text;
using Sketching.Interfaces;
namespace Sketching.Views
{
public partial class SketchView : ContentView
{
~SketchView()
{
System.Diagnostics.Debug.WriteLine("~SketchView");
}
public Command<ITool> ActivateToolCommand { get; set; }
public ICommand UndoCommand { get; set; }
public ICommand UndoAllCommand { get; set; }
public static readonly BindableProperty ToolCollectionProperty = BindableProperty.Create(nameof(ToolCollection), typeof(IToolCollection), typeof(SketchView), null,
propertyChanged: ToolCollectionPropertyChanged);
public IToolCollection ToolCollection
{
get { return (IToolCollection)GetValue(ToolCollectionProperty); }
set { SetValue(ToolCollectionProperty, value); }
}
private static void ToolCollectionPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
}
public SketchArea SketchArea => sketchArea;
// ToolbarHeight
public static readonly BindableProperty ToolbarHeightProperty = BindableProperty.Create(nameof(ToolbarHeight), typeof(double), typeof(SketchView), 50.0, propertyChanged: ToolbarHeightPropertyChanged);
public double ToolbarHeight
{
get { return (double)GetValue(ToolbarHeightProperty); }
set { SetValue(ToolbarHeightProperty, value); }
}
public bool CanDrawOutsideImageBounds {
get { return sketchArea.CanDrawOutsideImageBounds; }
set { sketchArea.CanDrawOutsideImageBounds = value;}
}
public IImage BackgroundImage {
get { return sketchArea.BackgroundImage; }
set {
sketchArea.BackgroundImage = value;
}
}
public bool EnableGrid
{
get { return sketchArea.EnableGrid ; }
set { sketchArea.EnableGrid = value; }
}
private static void ToolbarHeightPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
SetToolbarHeight(((SketchView)bindable).toolbarStack, (double)newValue);
}
public SketchView()
{
InitializeComponent();
ToolCollection = new ToolCollection();
ActivateToolCommand = new Command<ITool>(ActivateTool);
UndoCommand = new Command(() => { ToolCollection.Undo(); });
UndoAllCommand = new Command(() => { ToolCollection.UndoAll(); });
SetToolbarHeight(toolbarStack, ToolbarHeight);
sketchArea.Delegates.Add(ToolCollection);
sketchArea.ToolCollection = ToolCollection;
}
public void AddDefaultToolbarItems()
{
var assembly = typeof(SketchView).GetTypeInfo().Assembly;
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Line.png",assembly), new LineTool(), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Curve.png", assembly), new CurveTool(), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Highlight.png", assembly), new HighlightTool(), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Circle.png", assembly), new CircleTool(), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Oval.png", assembly), new OvalTool(), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Rectangle.png", assembly), new RectangleTool(), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Arrow.png", assembly), new ArrowTool(), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Point.png", assembly), new MarkTool(), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Text.png", assembly), new TextTool(Navigation), ActivateToolCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Undo.png", assembly), null, UndoCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Trash.png", assembly), null, UndoAllCommand);
}
private void ActivateTool(ITool tool)
{
if (SelectedTool?.Name == tool?.Name)
{
OpenToolSettings(SelectedTool);
return;
}
ToolCollection.ActivateTool(tool);
// Unselect all items
foreach (var child in toolbarStack.Children.Where(n => n is SketchToolbarItem))
{
var toolBarItem = (SketchToolbarItem)child;
toolBarItem.IsSelected = toolBarItem?.Tool == tool;
}
}
private ITool SelectedTool
{
get
{
var selectedItem = toolbarStack.Children.FirstOrDefault(n => (n as SketchToolbarItem)?.IsSelected == true);
return ((SketchToolbarItem)selectedItem)?.Tool;
}
}
private void OpenToolSettings(ITool tool)
{
var orientation = Width > Height ? StackOrientation.Horizontal : StackOrientation.Vertical;
Navigation.PushAsync(new ToolSettingsView(tool, orientation));
}
public void AddToolbarItem(ImageSource imageSource, ITool tool, ICommand command)
{
if (tool != null && ToolCollection.Tools.Any(n => n.Name == tool.Name))
throw new VerificationException("Tool already exists");
var newSketchToolbarItem = new SketchToolbarItem(imageSource, tool, command ?? ActivateToolCommand)
{
VerticalOptions = LayoutOptions.FillAndExpand,
WidthRequest = ToolbarHeight,
IsSelected = toolbarStack.Children.Count == 0 // Select the first added tool
};
toolbarStack.Children.Add(newSketchToolbarItem);
if (tool != null)
{
ToolCollection.Tools.Add(tool);
if (newSketchToolbarItem.IsSelected)
{
ToolCollection.ActivateTool(tool);
}
}
}
public void AddAllToolbarItems()
{
RemoveAllToolbarItems();
AddDefaultToolbarItems();
}
public void AddUndoTools()
{
var assembly = typeof(SketchView).GetTypeInfo().Assembly;
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Undo.png",assembly), null, UndoCommand);
AddToolbarItem(ImageSource.FromResource("Sketching.Resources.Trash.png",assembly), null, UndoAllCommand);
}
public void RemoveAllToolbarItems()
{
while (toolbarStack.Children.Any())
{
RemoveToolbarItemByIndex(0);
}
}
public void RemoveToolbarItemByName(string name)
{
var toolsToRemove = new List<SketchToolbarItem>();
foreach (var child in toolbarStack.Children)
{
var toolbarItem = child as SketchToolbarItem;
if (toolbarItem?.Tool == null) continue;
if (!toolbarItem.Tool.Name.Equals(name)) continue;
toolsToRemove.Add(toolbarItem);
}
foreach (var toolbarItem in toolsToRemove)
{
if (ToolCollection.Tools.Contains(toolbarItem.Tool))
ToolCollection.Tools.Remove(toolbarItem.Tool);
if (toolbarStack.Children.Contains(toolbarItem))
toolbarStack.Children.Remove(toolbarItem);
}
}
public void RemoveToolbarItemByIndex(int index)
{
var toolbarItem = (SketchToolbarItem)toolbarStack.Children[index];
if (toolbarItem == null) return;
if (ToolCollection.Tools.Contains(toolbarItem.Tool))
{
ToolCollection.Tools.Remove(toolbarItem.Tool);
}
if (toolbarStack.Children.Contains(toolbarItem))
{
toolbarStack.Children.Remove(toolbarItem);
}
}
private static void SetToolbarHeight(StackLayout toolbarStack, double height)
{
toolbarStack.HeightRequest = height;
foreach (var sketchToolbarItem in toolbarStack.Children)
{
sketchToolbarItem.WidthRequest = height;
}
}
}
}
| |
// 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.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Reflection.Runtime.BindingFlagSupport
{
//=================================================================================================================
// This class encapsulates the minimum set of arcane desktop CLR policies needed to implement the Get*(BindingFlags) apis.
//
// In particular, it encapsulates behaviors such as what exactly determines the "visibility" of a property and event, and
// what determines whether and how they are overridden.
//=================================================================================================================
internal abstract class MemberPolicies<M> where M : MemberInfo
{
//=================================================================================================================
// Subclasses for specific MemberInfo types must override these:
//=================================================================================================================
//
// Returns all of the directly declared members on the given TypeInfo.
//
public abstract IEnumerable<M> GetDeclaredMembers(TypeInfo typeInfo);
//
// Policy to decide whether a member is considered "virtual", "virtual new" and what its member visibility is.
// (For "visibility", we reuse the MethodAttributes enum since Reflection lacks an element-agnostic enum for this.
// Only the MemberAccessMask bits are set.)
//
public abstract void GetMemberAttributes(M member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot);
//
// Policy to decide whether two virtual members are signature-compatible for the purpose of implicit overriding.
//
public abstract bool AreNamesAndSignatureEqual(M member1, M member2);
//
// Policy to decide how BindingFlags should be reinterpreted for a given member type.
// This is overridden for nested types which all match on any combination Instance | Static and are never inherited.
// It is also overridden for constructors which are never inherited.
//
public virtual BindingFlags ModifyBindingFlags(BindingFlags bindingFlags)
{
return bindingFlags;
}
//
// Policy to create a wrapper MemberInfo (if appropriate). This is due to the fact that MemberInfo's actually have their identity
// tied to the type they were queried off of and this unfortunate fact shows up in certain api behaviors.
//
public virtual M GetInheritedMemberInfo(M underlyingMemberInfo, Type reflectedType)
{
return underlyingMemberInfo;
}
//
// Helper method for determining whether two methods are signature-compatible for the purpose of implicit overriding.
//
protected static bool AreNamesAndSignaturesEqual(MethodInfo method1, MethodInfo method2)
{
if (method1.Name != method2.Name)
{
return false;
}
ParameterInfo[] p1 = method1.GetParameters();
ParameterInfo[] p2 = method2.GetParameters();
if (p1.Length != p2.Length)
{
return false;
}
for (int i = 0; i < p1.Length; i++)
{
Type parameterType1 = p1[i].ParameterType;
Type parameterType2 = p2[i].ParameterType;
if (!(parameterType1.Equals(parameterType2)))
{
return false;
}
}
return true;
}
//
// This is a singleton class one for each MemberInfo category: Return the appropriate one.
//
public static MemberPolicies<M> Default
{
get
{
if (_default == null)
{
Type t = typeof(M);
if (t.Equals(typeof(FieldInfo)))
{
_default = (MemberPolicies<M>)(Object)(new FieldPolicies());
}
else if (t.Equals(typeof(MethodInfo)))
{
_default = (MemberPolicies<M>)(Object)(new MethodPolicies());
}
else if (t.Equals(typeof(ConstructorInfo)))
{
_default = (MemberPolicies<M>)(Object)(new ConstructorPolicies());
}
else if (t.Equals(typeof(PropertyInfo)))
{
_default = (MemberPolicies<M>)(Object)(new PropertyPolicies());
}
else if (t.Equals(typeof(EventInfo)))
{
_default = (MemberPolicies<M>)(Object)(new EventPolicies());
}
else if (t.Equals(typeof(TypeInfo)))
{
_default = (MemberPolicies<M>)(Object)(new NestedTypePolicies());
}
else
{
Debug.Assert(false, "Unknown MemberInfo type.");
}
}
return _default;
}
}
private static volatile MemberPolicies<M> _default;
}
//==========================================================================================================================
// Policies for fields.
//==========================================================================================================================
internal sealed class FieldPolicies : MemberPolicies<FieldInfo>
{
public sealed override IEnumerable<FieldInfo> GetDeclaredMembers(TypeInfo typeInfo)
{
return typeInfo.DeclaredFields;
}
public sealed override void GetMemberAttributes(FieldInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot)
{
FieldAttributes fieldAttributes = member.Attributes;
visibility = (MethodAttributes)(fieldAttributes & FieldAttributes.FieldAccessMask);
isStatic = (0 != (fieldAttributes & FieldAttributes.Static));
isVirtual = false;
isNewSlot = false;
}
public sealed override bool AreNamesAndSignatureEqual(FieldInfo member1, FieldInfo member2)
{
Debug.Assert(false, "This code path should be unreachable as fields are never \"virtual\".");
throw new NotSupportedException();
}
}
//==========================================================================================================================
// Policies for constructors.
//==========================================================================================================================
internal sealed class ConstructorPolicies : MemberPolicies<ConstructorInfo>
{
public sealed override IEnumerable<ConstructorInfo> GetDeclaredMembers(TypeInfo typeInfo)
{
return typeInfo.DeclaredConstructors;
}
public sealed override BindingFlags ModifyBindingFlags(BindingFlags bindingFlags)
{
// Constructors are not inherited.
return bindingFlags | BindingFlags.DeclaredOnly;
}
public sealed override void GetMemberAttributes(ConstructorInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot)
{
MethodAttributes methodAttributes = member.Attributes;
visibility = methodAttributes & MethodAttributes.MemberAccessMask;
isStatic = (0 != (methodAttributes & MethodAttributes.Static));
isVirtual = false;
isNewSlot = false;
}
public sealed override bool AreNamesAndSignatureEqual(ConstructorInfo member1, ConstructorInfo member2)
{
Debug.Assert(false, "This code path should be unreachable as constructors are never \"virtual\".");
throw new NotSupportedException();
}
}
//==========================================================================================================================
// Policies for methods.
//==========================================================================================================================
internal sealed class MethodPolicies : MemberPolicies<MethodInfo>
{
public sealed override IEnumerable<MethodInfo> GetDeclaredMembers(TypeInfo typeInfo)
{
return typeInfo.DeclaredMethods;
}
public sealed override void GetMemberAttributes(MethodInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot)
{
MethodAttributes methodAttributes = member.Attributes;
visibility = methodAttributes & MethodAttributes.MemberAccessMask;
isStatic = (0 != (methodAttributes & MethodAttributes.Static));
isVirtual = (0 != (methodAttributes & MethodAttributes.Virtual));
isNewSlot = (0 != (methodAttributes & MethodAttributes.NewSlot));
}
public sealed override bool AreNamesAndSignatureEqual(MethodInfo member1, MethodInfo member2)
{
return AreNamesAndSignaturesEqual(member1, member2);
}
}
//==========================================================================================================================
// Policies for properties.
//==========================================================================================================================
internal sealed class PropertyPolicies : MemberPolicies<PropertyInfo>
{
public sealed override IEnumerable<PropertyInfo> GetDeclaredMembers(TypeInfo typeInfo)
{
return typeInfo.DeclaredProperties;
}
public sealed override void GetMemberAttributes(PropertyInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot)
{
MethodInfo accessorMethod = GetAccessorMethod(member);
MethodAttributes methodAttributes = accessorMethod.Attributes;
visibility = methodAttributes & MethodAttributes.MemberAccessMask;
isStatic = (0 != (methodAttributes & MethodAttributes.Static));
isVirtual = (0 != (methodAttributes & MethodAttributes.Virtual));
isNewSlot = (0 != (methodAttributes & MethodAttributes.NewSlot));
}
public sealed override bool AreNamesAndSignatureEqual(PropertyInfo member1, PropertyInfo member2)
{
return AreNamesAndSignaturesEqual(GetAccessorMethod(member1), GetAccessorMethod(member2));
}
public sealed override PropertyInfo GetInheritedMemberInfo(PropertyInfo underlyingMemberInfo, Type reflectedType)
{
return new InheritedPropertyInfo(underlyingMemberInfo, reflectedType);
}
private MethodInfo GetAccessorMethod(PropertyInfo property)
{
MethodInfo accessor = property.GetMethod;
if (accessor == null)
{
accessor = property.SetMethod;
}
return accessor;
}
}
//==========================================================================================================================
// Policies for events.
//==========================================================================================================================
internal sealed class EventPolicies : MemberPolicies<EventInfo>
{
public sealed override IEnumerable<EventInfo> GetDeclaredMembers(TypeInfo typeInfo)
{
return typeInfo.DeclaredEvents;
}
public sealed override void GetMemberAttributes(EventInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot)
{
MethodInfo accessorMethod = GetAccessorMethod(member);
MethodAttributes methodAttributes = accessorMethod.Attributes;
visibility = methodAttributes & MethodAttributes.MemberAccessMask;
isStatic = (0 != (methodAttributes & MethodAttributes.Static));
isVirtual = (0 != (methodAttributes & MethodAttributes.Virtual));
isNewSlot = (0 != (methodAttributes & MethodAttributes.NewSlot));
}
public sealed override bool AreNamesAndSignatureEqual(EventInfo member1, EventInfo member2)
{
return AreNamesAndSignaturesEqual(GetAccessorMethod(member1), GetAccessorMethod(member2));
}
private MethodInfo GetAccessorMethod(EventInfo e)
{
MethodInfo accessor = e.AddMethod;
return accessor;
}
}
//==========================================================================================================================
// Policies for nested types.
//
// Nested types enumerate a little differently than other members:
//
// Base classes are never searched, regardless of BindingFlags.DeclaredOnly value.
//
// Public|NonPublic|IgnoreCase are the only relevant BindingFlags. The apis ignore any other bits.
//
// There is no such thing as a "static" or "instanced" nested type. For enumeration purposes,
// we'll arbitrarily denote all nested types as "static."
//
//==========================================================================================================================
internal sealed class NestedTypePolicies : MemberPolicies<TypeInfo>
{
public sealed override IEnumerable<TypeInfo> GetDeclaredMembers(TypeInfo typeInfo)
{
return typeInfo.DeclaredNestedTypes;
}
public sealed override void GetMemberAttributes(TypeInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot)
{
isStatic = true;
isVirtual = false;
isNewSlot = false;
// Since we never search base types for nested types, we don't need to map every visibility value one to one.
// We just need to distinguish between "public" and "everything else."
visibility = member.IsNestedPublic ? MethodAttributes.Public : MethodAttributes.Private;
}
public sealed override bool AreNamesAndSignatureEqual(TypeInfo member1, TypeInfo member2)
{
Debug.Assert(false, "This code path should be unreachable as nested types are never \"virtual\".");
throw new NotSupportedException();
}
public sealed override BindingFlags ModifyBindingFlags(BindingFlags bindingFlags)
{
bindingFlags &= BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase;
bindingFlags |= BindingFlags.Static | BindingFlags.DeclaredOnly;
return bindingFlags;
}
}
}
| |
/*
* 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 Lucene.Net.Codecs.Pulsing
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Index;
using Store;
using Util;
/// <summary>
/// TODO: we now inline based on total TF of the term,
/// but it might be better to inline by "net bytes used"
/// so that a term that has only 1 posting but a huge
/// payload would not be inlined. Though this is
/// presumably rare in practice...
///
/// Writer for the pulsing format.
///
/// Wraps another postings implementation and decides
/// (based on total number of occurrences), whether a terms
/// postings should be inlined into the term dictionary,
/// or passed through to the wrapped writer.
///
/// @lucene.experimental
/// </summary>
public sealed class PulsingPostingsWriter : PostingsWriterBase
{
internal static readonly String CODEC = "PulsedPostingsWriter";
internal static readonly String SUMMARY_EXTENSION = "smy"; // recording field summary
// To add a new version, increment from the last one, and
// change VERSION_CURRENT to point to your new version:
internal static readonly int VERSION_START = 0;
internal static readonly int VERSION_META_ARRAY = 1;
internal static readonly int VERSION_CURRENT = VERSION_META_ARRAY;
private readonly SegmentWriteState _segmentState;
private IndexOutput _termsOut;
private readonly List<FieldMetaData> _fields;
private FieldInfo.IndexOptions? _indexOptions;
private bool _storePayloads;
// information for wrapped PF, in current field
private int _longsSize;
private long[] _longs;
private bool _absolute;
private class PulsingTermState : BlockTermState
{
internal byte[] BYTES;
internal BlockTermState WRAPPED_STATE;
public override String ToString()
{
if (BYTES != null)
{
return "inlined";
}
return "not inlined wrapped=" + WRAPPED_STATE;
}
}
// one entry per position
private readonly Position[] _pending;
private int _pendingCount = 0; // -1 once we've hit too many positions
private Position _currentDoc; // first Position entry of current doc
private sealed class Position
{
internal BytesRef payload;
internal int termFreq; // only incremented on first position for a given doc
internal int pos;
internal int docID;
internal int startOffset;
internal int endOffset;
}
private class FieldMetaData
{
public int FieldNumber { get; private set; }
public int LongsSize { get; private set; }
public FieldMetaData(int number, int size)
{
FieldNumber = number;
LongsSize = size;
}
}
// TODO: -- lazy init this? ie, if every single term
// was inlined (eg for a "primary key" field) then we
// never need to use this fallback? Fallback writer for
// non-inlined terms:
private readonly PostingsWriterBase _wrappedPostingsWriter;
/// <summary>
/// If the total number of positions (summed across all docs
/// for this term) is less than or equal maxPositions, then the postings are
/// inlined into terms dict
/// </summary>
public PulsingPostingsWriter(SegmentWriteState state, int maxPositions, PostingsWriterBase wrappedPostingsWriter)
{
_pending = new Position[maxPositions];
for (var i = 0; i < maxPositions; i++)
{
_pending[i] = new Position();
}
_fields = new List<FieldMetaData>();
// We simply wrap another postings writer, but only call
// on it when tot positions is >= the cutoff:
_wrappedPostingsWriter = wrappedPostingsWriter;
_segmentState = state;
}
public override void Init(IndexOutput termsOut)
{
_termsOut = termsOut;
CodecUtil.WriteHeader(termsOut, CODEC, VERSION_CURRENT);
termsOut.WriteVInt(_pending.Length); // encode maxPositions in header
_wrappedPostingsWriter.Init(termsOut);
}
public override BlockTermState NewTermState()
{
var state = new PulsingTermState {WRAPPED_STATE = _wrappedPostingsWriter.NewTermState()};
return state;
}
public override void StartTerm()
{
Debug.Assert(_pendingCount == 0);
}
/// <summary>
/// TODO: -- should we NOT reuse across fields? would
/// be cleaner
/// Currently, this instance is re-used across fields, so
/// our parent calls setField whenever the field changes
/// </summary>
/// <param name="fieldInfo"></param>
/// <returns></returns>
public override int SetField(FieldInfo fieldInfo)
{
_indexOptions = fieldInfo.FieldIndexOptions;
_storePayloads = fieldInfo.HasPayloads();
_absolute = false;
_longsSize = _wrappedPostingsWriter.SetField(fieldInfo);
_longs = new long[_longsSize];
_fields.Add(new FieldMetaData(fieldInfo.Number, _longsSize));
return 0;
}
public override void StartDoc(int docId, int termDocFreq)
{
Debug.Assert(docId >= 0, "Got DocID=" + docId);
if (_pendingCount == _pending.Length)
{
Push();
_wrappedPostingsWriter.FinishDoc();
}
if (_pendingCount != -1)
{
Debug.Assert(_pendingCount < _pending.Length);
_currentDoc = _pending[_pendingCount];
_currentDoc.docID = docId;
if (_indexOptions == FieldInfo.IndexOptions.DOCS_ONLY)
{
_pendingCount++;
}
else if (_indexOptions == FieldInfo.IndexOptions.DOCS_AND_FREQS)
{
_pendingCount++;
_currentDoc.termFreq = termDocFreq;
}
else
{
_currentDoc.termFreq = termDocFreq;
}
}
else
{
// We've already seen too many docs for this term --
// just forward to our fallback writer
_wrappedPostingsWriter.StartDoc(docId, termDocFreq);
}
}
public override void AddPosition(int position, BytesRef payload, int startOffset, int endOffset)
{
if (_pendingCount == _pending.Length)
{
Push();
}
if (_pendingCount == -1)
{
// We've already seen too many docs for this term --
// just forward to our fallback writer
_wrappedPostingsWriter.AddPosition(position, payload, startOffset, endOffset);
}
else
{
// buffer up
Position pos = _pending[_pendingCount++];
pos.pos = position;
pos.startOffset = startOffset;
pos.endOffset = endOffset;
pos.docID = _currentDoc.docID;
if (payload != null && payload.Length > 0)
{
if (pos.payload == null)
{
pos.payload = BytesRef.DeepCopyOf(payload);
}
else
{
pos.payload.CopyBytes(payload);
}
}
else if (pos.payload != null)
{
pos.payload.Length = 0;
}
}
}
public override void FinishDoc()
{
if (_pendingCount == -1)
{
_wrappedPostingsWriter.FinishDoc();
}
}
private readonly RAMOutputStream _buffer = new RAMOutputStream();
/// <summary>
/// Called when we are done adding docs to this term
/// </summary>
/// <param name="_state"></param>
public override void FinishTerm(BlockTermState _state)
{
var state = (PulsingTermState) _state;
Debug.Assert(_pendingCount > 0 || _pendingCount == -1);
if (_pendingCount == -1)
{
state.WRAPPED_STATE.DocFreq = state.DocFreq;
state.WRAPPED_STATE.TotalTermFreq = state.TotalTermFreq;
state.BYTES = null;
_wrappedPostingsWriter.FinishTerm(state.WRAPPED_STATE);
}
else
{
// There were few enough total occurrences for this
// term, so we fully inline our postings data into
// terms dict, now:
// TODO: it'd be better to share this encoding logic
// in some inner codec that knows how to write a
// single doc / single position, etc. This way if a
// given codec wants to store other interesting
// stuff, it could use this pulsing codec to do so
if (_indexOptions >= FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS)
{
var lastDocID = 0;
var pendingIDX = 0;
var lastPayloadLength = -1;
var lastOffsetLength = -1;
while (pendingIDX < _pendingCount)
{
var doc = _pending[pendingIDX];
var delta = doc.docID - lastDocID;
lastDocID = doc.docID;
// if (DEBUG) System.out.println(" write doc=" + doc.docID + " freq=" + doc.termFreq);
if (doc.termFreq == 1)
{
_buffer.WriteVInt((delta << 1) | 1);
}
else
{
_buffer.WriteVInt(delta << 1);
_buffer.WriteVInt(doc.termFreq);
}
var lastPos = 0;
var lastOffset = 0;
for (var posIDX = 0; posIDX < doc.termFreq; posIDX++)
{
var pos = _pending[pendingIDX++];
Debug.Assert(pos.docID == doc.docID);
var posDelta = pos.pos - lastPos;
lastPos = pos.pos;
var payloadLength = pos.payload == null ? 0 : pos.payload.Length;
if (_storePayloads)
{
if (payloadLength != lastPayloadLength)
{
_buffer.WriteVInt((posDelta << 1) | 1);
_buffer.WriteVInt(payloadLength);
lastPayloadLength = payloadLength;
}
else
{
_buffer.WriteVInt(posDelta << 1);
}
}
else
{
_buffer.WriteVInt(posDelta);
}
if (_indexOptions >= FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS)
{
//System.out.println("write=" + pos.startOffset + "," + pos.endOffset);
var offsetDelta = pos.startOffset - lastOffset;
var offsetLength = pos.endOffset - pos.startOffset;
if (offsetLength != lastOffsetLength)
{
_buffer.WriteVInt(offsetDelta << 1 | 1);
_buffer.WriteVInt(offsetLength);
}
else
{
_buffer.WriteVInt(offsetDelta << 1);
}
lastOffset = pos.startOffset;
lastOffsetLength = offsetLength;
}
if (payloadLength > 0)
{
Debug.Assert(_storePayloads);
_buffer.WriteBytes(pos.payload.Bytes, 0, pos.payload.Length);
}
}
}
}
else switch (_indexOptions)
{
case FieldInfo.IndexOptions.DOCS_AND_FREQS:
{
var lastDocId = 0;
for (var posIdx = 0; posIdx < _pendingCount; posIdx++)
{
var doc = _pending[posIdx];
var delta = doc.docID - lastDocId;
Debug.Assert(doc.termFreq != 0);
if (doc.termFreq == 1)
{
_buffer.WriteVInt((delta << 1) | 1);
}
else
{
_buffer.WriteVInt(delta << 1);
_buffer.WriteVInt(doc.termFreq);
}
lastDocId = doc.docID;
}
}
break;
case FieldInfo.IndexOptions.DOCS_ONLY:
{
var lastDocId = 0;
for (var posIdx = 0; posIdx < _pendingCount; posIdx++)
{
var doc = _pending[posIdx];
_buffer.WriteVInt(doc.docID - lastDocId);
lastDocId = doc.docID;
}
}
break;
}
state.BYTES = new byte[(int) _buffer.FilePointer];
_buffer.WriteTo(state.BYTES, 0);
_buffer.Reset();
}
_pendingCount = 0;
}
public override void EncodeTerm(long[] empty, DataOutput output, FieldInfo fieldInfo, BlockTermState state,
bool abs)
{
var _state = (PulsingTermState) state;
Debug.Assert(empty.Length == 0);
_absolute = _absolute || abs;
if (_state.BYTES == null)
{
_wrappedPostingsWriter.EncodeTerm(_longs, _buffer, fieldInfo, _state.WRAPPED_STATE, _absolute);
for (var i = 0; i < _longsSize; i++)
{
output.WriteVLong(_longs[i]);
}
_buffer.WriteTo(output);
_buffer.Reset();
_absolute = false;
}
else
{
output.WriteVInt(_state.BYTES.Length);
output.WriteBytes(_state.BYTES, 0, _state.BYTES.Length);
_absolute = _absolute || abs;
}
}
protected override void Dispose(bool disposing)
{
_wrappedPostingsWriter.Dispose();
if (_wrappedPostingsWriter is PulsingPostingsWriter ||
VERSION_CURRENT < VERSION_META_ARRAY)
{
return;
}
var summaryFileName = IndexFileNames.SegmentFileName(_segmentState.SegmentInfo.Name,
_segmentState.SegmentSuffix, SUMMARY_EXTENSION);
IndexOutput output = null;
try
{
output =
_segmentState.Directory.CreateOutput(summaryFileName, _segmentState.Context);
CodecUtil.WriteHeader(output, CODEC, VERSION_CURRENT);
output.WriteVInt(_fields.Count);
foreach (var field in _fields)
{
output.WriteVInt(field.FieldNumber);
output.WriteVInt(field.LongsSize);
}
output.Dispose();
}
finally
{
IOUtils.CloseWhileHandlingException(output);
}
}
// Pushes pending positions to the wrapped codec
private void Push()
{
Debug.Assert(_pendingCount == _pending.Length);
_wrappedPostingsWriter.StartTerm();
// Flush all buffered docs
if (_indexOptions >= FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS)
{
Position doc = null;
foreach(var pos in _pending)
{
if (doc == null)
{
doc = pos;
_wrappedPostingsWriter.StartDoc(doc.docID, doc.termFreq);
}
else if (doc.docID != pos.docID)
{
Debug.Assert(pos.docID > doc.docID);
_wrappedPostingsWriter.FinishDoc();
doc = pos;
_wrappedPostingsWriter.StartDoc(doc.docID, doc.termFreq);
}
_wrappedPostingsWriter.AddPosition(pos.pos, pos.payload, pos.startOffset, pos.endOffset);
}
//wrappedPostingsWriter.finishDoc();
}
else
{
foreach(var doc in _pending)
{
_wrappedPostingsWriter.StartDoc(doc.docID, _indexOptions == FieldInfo.IndexOptions.DOCS_ONLY ? 0 : doc.termFreq);
}
}
_pendingCount = -1;
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Codecs.Asserting
{
using System;
using AssertingAtomicReader = Lucene.Net.Index.AssertingAtomicReader;
using BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using IBits = Lucene.Net.Util.IBits;
using BytesRef = Lucene.Net.Util.BytesRef;
using DocValuesType = Lucene.Net.Index.DocValuesType;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using Int64BitSet = Lucene.Net.Util.Int64BitSet;
/*
* 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 Lucene45DocValuesFormat = Lucene.Net.Codecs.Lucene45.Lucene45DocValuesFormat;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using SegmentReadState = Lucene.Net.Index.SegmentReadState;
using SegmentWriteState = Lucene.Net.Index.SegmentWriteState;
using SortedDocValues = Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues;
/// <summary>
/// Just like <seealso cref="Lucene45DocValuesFormat"/> but with additional asserts.
/// </summary>
[DocValuesFormatName("Asserting")]
public class AssertingDocValuesFormat : DocValuesFormat
{
private readonly DocValuesFormat @in = new Lucene45DocValuesFormat();
public AssertingDocValuesFormat()
: base()
{
}
public override DocValuesConsumer FieldsConsumer(SegmentWriteState state)
{
DocValuesConsumer consumer = @in.FieldsConsumer(state);
Debug.Assert(consumer != null);
return new AssertingDocValuesConsumer(consumer, state.SegmentInfo.DocCount);
}
public override DocValuesProducer FieldsProducer(SegmentReadState state)
{
Debug.Assert(state.FieldInfos.HasDocValues);
DocValuesProducer producer = @in.FieldsProducer(state);
Debug.Assert(producer != null);
return new AssertingDocValuesProducer(producer, state.SegmentInfo.DocCount);
}
internal class AssertingDocValuesConsumer : DocValuesConsumer
{
internal readonly DocValuesConsumer @in;
internal readonly int MaxDoc;
internal AssertingDocValuesConsumer(DocValuesConsumer @in, int maxDoc)
{
this.@in = @in;
this.MaxDoc = maxDoc;
}
public override void AddNumericField(FieldInfo field, IEnumerable<long?> values)
{
int count = 0;
foreach (var v in values)
{
count++;
}
Debug.Assert(count == MaxDoc);
CheckIterator(values.GetEnumerator(), MaxDoc, true);
@in.AddNumericField(field, values);
}
public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values)
{
int count = 0;
foreach (BytesRef b in values)
{
Debug.Assert(b == null || b.IsValid());
count++;
}
Debug.Assert(count == MaxDoc);
CheckIterator(values.GetEnumerator(), MaxDoc, true);
@in.AddBinaryField(field, values);
}
public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
int valueCount = 0;
BytesRef lastValue = null;
foreach (BytesRef b in values)
{
Debug.Assert(b != null);
Debug.Assert(b.IsValid());
if (valueCount > 0)
{
Debug.Assert(b.CompareTo(lastValue) > 0);
}
lastValue = BytesRef.DeepCopyOf(b);
valueCount++;
}
Debug.Assert(valueCount <= MaxDoc);
FixedBitSet seenOrds = new FixedBitSet(valueCount);
int count = 0;
foreach (long? v in docToOrd)
{
Debug.Assert(v != null);
int ord = (int)v.Value;
Debug.Assert(ord >= -1 && ord < valueCount);
if (ord >= 0)
{
seenOrds.Set(ord);
}
count++;
}
Debug.Assert(count == MaxDoc);
Debug.Assert(seenOrds.Cardinality() == valueCount);
CheckIterator(values.GetEnumerator(), valueCount, false);
CheckIterator(docToOrd.GetEnumerator(), MaxDoc, false);
@in.AddSortedField(field, values, docToOrd);
}
public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
long valueCount = 0;
BytesRef lastValue = null;
foreach (BytesRef b in values)
{
Debug.Assert(b != null);
Debug.Assert(b.IsValid());
if (valueCount > 0)
{
Debug.Assert(b.CompareTo(lastValue) > 0);
}
lastValue = BytesRef.DeepCopyOf(b);
valueCount++;
}
int docCount = 0;
long ordCount = 0;
Int64BitSet seenOrds = new Int64BitSet(valueCount);
IEnumerator<long?> ordIterator = ords.GetEnumerator();
foreach (long? v in docToOrdCount)
{
Debug.Assert(v != null);
int count = (int)v.Value;
Debug.Assert(count >= 0);
docCount++;
ordCount += count;
long lastOrd = -1;
for (int i = 0; i < count; i++)
{
ordIterator.MoveNext();
long? o = ordIterator.Current;
Debug.Assert(o != null);
long ord = o.Value;
Debug.Assert(ord >= 0 && ord < valueCount);
Debug.Assert(ord > lastOrd, "ord=" + ord + ",lastOrd=" + lastOrd);
seenOrds.Set(ord);
lastOrd = ord;
}
}
Debug.Assert(ordIterator.MoveNext() == false);
Debug.Assert(docCount == MaxDoc);
Debug.Assert(seenOrds.Cardinality() == valueCount);
CheckIterator(values.GetEnumerator(), valueCount, false);
CheckIterator(docToOrdCount.GetEnumerator(), MaxDoc, false);
CheckIterator(ords.GetEnumerator(), ordCount, false);
@in.AddSortedSetField(field, values, docToOrdCount, ords);
}
protected override void Dispose(bool disposing)
{
if (disposing)
@in.Dispose();
}
}
internal class AssertingNormsConsumer : DocValuesConsumer
{
internal readonly DocValuesConsumer @in;
internal readonly int MaxDoc;
internal AssertingNormsConsumer(DocValuesConsumer @in, int maxDoc)
{
this.@in = @in;
this.MaxDoc = maxDoc;
}
public override void AddNumericField(FieldInfo field, IEnumerable<long?> values)
{
int count = 0;
foreach (long? v in values)
{
Debug.Assert(v != null);
count++;
}
Debug.Assert(count == MaxDoc);
CheckIterator(values.GetEnumerator(), MaxDoc, false);
@in.AddNumericField(field, values);
}
protected override void Dispose(bool disposing)
{
if (disposing)
@in.Dispose();
}
public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values)
{
throw new InvalidOperationException();
}
public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
throw new InvalidOperationException();
}
public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
throw new InvalidOperationException();
}
}
private static void CheckIterator<T>(IEnumerator<T> iterator, long expectedSize, bool allowNull)
{
for (long i = 0; i < expectedSize; i++)
{
bool hasNext = iterator.MoveNext();
Debug.Assert(hasNext);
T v = iterator.Current;
Debug.Assert(allowNull || v != null);
try
{
iterator.Reset();
throw new InvalidOperationException("broken iterator (supports remove): " + iterator);
}
catch (System.NotSupportedException)
{
// ok
}
}
Debug.Assert(!iterator.MoveNext());
/*try
{
//iterator.next();
throw new InvalidOperationException("broken iterator (allows next() when hasNext==false) " + iterator);
}
catch (Exception)
{
// ok
}*/
}
internal class AssertingDocValuesProducer : DocValuesProducer
{
internal readonly DocValuesProducer @in;
internal readonly int MaxDoc;
internal AssertingDocValuesProducer(DocValuesProducer @in, int maxDoc)
{
this.@in = @in;
this.MaxDoc = maxDoc;
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
Debug.Assert(field.DocValuesType == DocValuesType.NUMERIC || field.NormType == DocValuesType.NUMERIC);
NumericDocValues values = @in.GetNumeric(field);
Debug.Assert(values != null);
return new AssertingAtomicReader.AssertingNumericDocValues(values, MaxDoc);
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
Debug.Assert(field.DocValuesType == DocValuesType.BINARY);
BinaryDocValues values = @in.GetBinary(field);
Debug.Assert(values != null);
return new AssertingAtomicReader.AssertingBinaryDocValues(values, MaxDoc);
}
public override SortedDocValues GetSorted(FieldInfo field)
{
Debug.Assert(field.DocValuesType == DocValuesType.SORTED);
SortedDocValues values = @in.GetSorted(field);
Debug.Assert(values != null);
return new AssertingAtomicReader.AssertingSortedDocValues(values, MaxDoc);
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
Debug.Assert(field.DocValuesType == DocValuesType.SORTED_SET);
SortedSetDocValues values = @in.GetSortedSet(field);
Debug.Assert(values != null);
return new AssertingAtomicReader.AssertingSortedSetDocValues(values, MaxDoc);
}
public override IBits GetDocsWithField(FieldInfo field)
{
Debug.Assert(field.DocValuesType != DocValuesType.NONE);
IBits bits = @in.GetDocsWithField(field);
Debug.Assert(bits != null);
Debug.Assert(bits.Length == MaxDoc);
return new AssertingAtomicReader.AssertingBits(bits);
}
protected override void Dispose(bool disposing)
{
if (disposing)
@in.Dispose();
}
public override long RamBytesUsed()
{
return @in.RamBytesUsed();
}
public override void CheckIntegrity()
{
@in.CheckIntegrity();
}
}
}
}
| |
using System;
using System.Text;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace HETSAPI.Models
{
/// <summary>
/// Seniority Audit Database Model
/// </summary>
[MetaData (Description = "The history of all changes to the seniority of a piece of equipment. The current seniority information (underlying data elements and the calculation result) is in the equipment record. Every time that information changes, the old values are copied to here, with a start date, end date range. In the normal case, an annual update triggers the old values being copied here and the new values put into the equipment record. If a user manually changes the values, the existing values are copied into a record added here.")]
public sealed class SeniorityAudit : AuditableEntity, IEquatable<SeniorityAudit>
{
/// <summary>
/// Seniority Audit Database Model Constructor (required by entity framework)
/// </summary>
public SeniorityAudit()
{
Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="SeniorityAudit" /> class.
/// </summary>
/// <param name="id">A system-generated unique identifier for a SeniorityAudit (required).</param>
/// <param name="startDate">The effective date that the Seniority data in this record went into effect. (required).</param>
/// <param name="endDate">The effective date at which the Seniority data in this record ceased to be in effect. (required).</param>
/// <param name="localArea">A foreign key reference to the system-generated unique identifier for a Local Area (required).</param>
/// <param name="equipment">A foreign key reference to the system-generated unique identifier for an Equipment (required).</param>
/// <param name="blockNumber">The block number for the piece of equipment as calculated by the Seniority Algorthm for this equipment type in the local area. As currently defined by the business - 1, 2 or Open.</param>
/// <param name="owner">A foreign key reference to the system-generated unique identifier for an Owner.</param>
/// <param name="ownerOrganizationName">The name of the organization of the owner from the Owner Record, captured at the time this record was created..</param>
/// <param name="seniority">The seniority calculation result for this piece of equipment. The calculation is based on the &quot;numYears&quot; of service + average hours of service over the last three fiscal years - as stored in the related fields (serviceHoursLastYear, serviceHoursTwoYearsAgo serviceHoursThreeYearsAgo)..</param>
/// <param name="serviceHoursLastYear">Number of hours of service by this piece of equipment in the previous fiscal year.</param>
/// <param name="serviceHoursTwoYearsAgo">Number of hours of service by this piece of equipment in the fiscal year before the last one - e.g. if current year is FY2018 then hours in FY2016.</param>
/// <param name="serviceHoursThreeYearsAgo">Number of hours of service by this piece of equipment in the fiscal year three years ago - e.g. if current year is FY2018 then hours in FY2015.</param>
/// <param name="isSeniorityOverridden">True if the Seniority for the piece of equipment was manually overridden. Set if a user has gone in and explicitly updated the seniority base information. Indicates that underlying numbers were manually overridden..</param>
/// <param name="seniorityOverrideReason">A text reason for why the piece of equipments underlying data was overridden to change their seniority number..</param>
public SeniorityAudit(int id, DateTime startDate, DateTime endDate, LocalArea localArea, Equipment equipment,
int? blockNumber = null, Owner owner = null, string ownerOrganizationName = null, float? seniority = null,
float? serviceHoursLastYear = null, float? serviceHoursTwoYearsAgo = null, float? serviceHoursThreeYearsAgo = null,
bool? isSeniorityOverridden = null, string seniorityOverrideReason = null)
{
Id = id;
StartDate = startDate;
EndDate = endDate;
LocalArea = localArea;
Equipment = equipment;
BlockNumber = blockNumber;
Owner = owner;
OwnerOrganizationName = ownerOrganizationName;
Seniority = seniority;
ServiceHoursLastYear = serviceHoursLastYear;
ServiceHoursTwoYearsAgo = serviceHoursTwoYearsAgo;
ServiceHoursThreeYearsAgo = serviceHoursThreeYearsAgo;
IsSeniorityOverridden = isSeniorityOverridden;
SeniorityOverrideReason = seniorityOverrideReason;
}
/// <summary>
/// A system-generated unique identifier for a SeniorityAudit
/// </summary>
/// <value>A system-generated unique identifier for a SeniorityAudit</value>
[MetaData (Description = "A system-generated unique identifier for a SeniorityAudit")]
public int Id { get; set; }
/// <summary>
/// The effective date that the Seniority data in this record went into effect.
/// </summary>
/// <value>The effective date that the Seniority data in this record went into effect.</value>
[MetaData (Description = "The effective date that the Seniority data in this record went into effect.")]
public DateTime StartDate { get; set; }
/// <summary>
/// The effective date at which the Seniority data in this record ceased to be in effect.
/// </summary>
/// <value>The effective date at which the Seniority data in this record ceased to be in effect.</value>
[MetaData (Description = "The effective date at which the Seniority data in this record ceased to be in effect.")]
public DateTime EndDate { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for a Local Area
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for a Local Area</value>
[MetaData (Description = "A foreign key reference to the system-generated unique identifier for a Local Area")]
public LocalArea LocalArea { get; set; }
/// <summary>
/// Foreign key for LocalArea
/// </summary>
[ForeignKey("LocalArea")]
[JsonIgnore]
[MetaData (Description = "A foreign key reference to the system-generated unique identifier for a Local Area")]
public int? LocalAreaId { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for an Equipment
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for an Equipment</value>
[MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Equipment")]
public Equipment Equipment { get; set; }
/// <summary>
/// Foreign key for Equipment
/// </summary>
[ForeignKey("Equipment")]
[JsonIgnore]
[MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Equipment")]
public int? EquipmentId { get; set; }
/// <summary>
/// The block number for the piece of equipment as calculated by the Seniority Algorthm for this equipment type in the local area. As currently defined by the business - 1, 2 or Open
/// </summary>
/// <value>The block number for the piece of equipment as calculated by the Seniority Algorthm for this equipment type in the local area. As currently defined by the business - 1, 2 or Open</value>
[MetaData (Description = "The block number for the piece of equipment as calculated by the Seniority Algorthm for this equipment type in the local area. As currently defined by the business - 1, 2 or Open")]
public int? BlockNumber { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for an Owner
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for an Owner</value>
[MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Owner")]
public Owner Owner { get; set; }
/// <summary>
/// Foreign key for Owner
/// </summary>
[ForeignKey("Owner")]
[JsonIgnore]
[MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Owner")]
public int? OwnerId { get; set; }
/// <summary>
/// The name of the organization of the owner from the Owner Record, captured at the time this record was created.
/// </summary>
/// <value>The name of the organization of the owner from the Owner Record, captured at the time this record was created.</value>
[MetaData (Description = "The name of the organization of the owner from the Owner Record, captured at the time this record was created.")]
[MaxLength(150)]
public string OwnerOrganizationName { get; set; }
/// <summary>
/// The seniority calculation result for this piece of equipment. The calculation is based on the "numYears" of service + average hours of service over the last three fiscal years - as stored in the related fields (serviceHoursLastYear, serviceHoursTwoYearsAgo serviceHoursThreeYearsAgo).
/// </summary>
/// <value>The seniority calculation result for this piece of equipment. The calculation is based on the "numYears" of service + average hours of service over the last three fiscal years - as stored in the related fields (serviceHoursLastYear, serviceHoursTwoYearsAgo serviceHoursThreeYearsAgo).</value>
[MetaData (Description = "The seniority calculation result for this piece of equipment. The calculation is based on the "numYears" of service + average hours of service over the last three fiscal years - as stored in the related fields (serviceHoursLastYear, serviceHoursTwoYearsAgo serviceHoursThreeYearsAgo).")]
public float? Seniority { get; set; }
/// <summary>
/// Number of hours of service by this piece of equipment in the previous fiscal year
/// </summary>
/// <value>Number of hours of service by this piece of equipment in the previous fiscal year</value>
[MetaData (Description = "Number of hours of service by this piece of equipment in the previous fiscal year")]
public float? ServiceHoursLastYear { get; set; }
/// <summary>
/// Number of hours of service by this piece of equipment in the fiscal year before the last one - e.g. if current year is FY2018 then hours in FY2016
/// </summary>
/// <value>Number of hours of service by this piece of equipment in the fiscal year before the last one - e.g. if current year is FY2018 then hours in FY2016</value>
[MetaData (Description = "Number of hours of service by this piece of equipment in the fiscal year before the last one - e.g. if current year is FY2018 then hours in FY2016")]
public float? ServiceHoursTwoYearsAgo { get; set; }
/// <summary>
/// Number of hours of service by this piece of equipment in the fiscal year three years ago - e.g. if current year is FY2018 then hours in FY2015
/// </summary>
/// <value>Number of hours of service by this piece of equipment in the fiscal year three years ago - e.g. if current year is FY2018 then hours in FY2015</value>
[MetaData (Description = "Number of hours of service by this piece of equipment in the fiscal year three years ago - e.g. if current year is FY2018 then hours in FY2015")]
public float? ServiceHoursThreeYearsAgo { get; set; }
/// <summary>
/// True if the Seniority for the piece of equipment was manually overridden. Set if a user has gone in and explicitly updated the seniority base information. Indicates that underlying numbers were manually overridden.
/// </summary>
/// <value>True if the Seniority for the piece of equipment was manually overridden. Set if a user has gone in and explicitly updated the seniority base information. Indicates that underlying numbers were manually overridden.</value>
[MetaData (Description = "True if the Seniority for the piece of equipment was manually overridden. Set if a user has gone in and explicitly updated the seniority base information. Indicates that underlying numbers were manually overridden.")]
public bool? IsSeniorityOverridden { get; set; }
/// <summary>
/// A text reason for why the piece of equipments underlying data was overridden to change their seniority number.
/// </summary>
/// <value>A text reason for why the piece of equipments underlying data was overridden to change their seniority number.</value>
[MetaData (Description = "A text reason for why the piece of equipments underlying data was overridden to change their seniority number.")]
[MaxLength(2048)]
public string SeniorityOverrideReason { 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 SeniorityAudit {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" StartDate: ").Append(StartDate).Append("\n");
sb.Append(" EndDate: ").Append(EndDate).Append("\n");
sb.Append(" LocalArea: ").Append(LocalArea).Append("\n");
sb.Append(" Equipment: ").Append(Equipment).Append("\n");
sb.Append(" BlockNumber: ").Append(BlockNumber).Append("\n");
sb.Append(" Owner: ").Append(Owner).Append("\n");
sb.Append(" OwnerOrganizationName: ").Append(OwnerOrganizationName).Append("\n");
sb.Append(" Seniority: ").Append(Seniority).Append("\n");
sb.Append(" ServiceHoursLastYear: ").Append(ServiceHoursLastYear).Append("\n");
sb.Append(" ServiceHoursTwoYearsAgo: ").Append(ServiceHoursTwoYearsAgo).Append("\n");
sb.Append(" ServiceHoursThreeYearsAgo: ").Append(ServiceHoursThreeYearsAgo).Append("\n");
sb.Append(" IsSeniorityOverridden: ").Append(IsSeniorityOverridden).Append("\n");
sb.Append(" SeniorityOverrideReason: ").Append(SeniorityOverrideReason).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)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((SeniorityAudit)obj);
}
/// <summary>
/// Returns true if SeniorityAudit instances are equal
/// </summary>
/// <param name="other">Instance of SeniorityAudit to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SeniorityAudit other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
Id == other.Id ||
Id.Equals(other.Id)
) &&
(
StartDate == other.StartDate ||
StartDate.Equals(other.StartDate)
) &&
(
EndDate == other.EndDate ||
EndDate.Equals(other.EndDate)
) &&
(
LocalArea == other.LocalArea ||
LocalArea != null &&
LocalArea.Equals(other.LocalArea)
) &&
(
Equipment == other.Equipment ||
Equipment != null &&
Equipment.Equals(other.Equipment)
) &&
(
BlockNumber == other.BlockNumber ||
BlockNumber != null &&
BlockNumber.Equals(other.BlockNumber)
) &&
(
Owner == other.Owner ||
Owner != null &&
Owner.Equals(other.Owner)
) &&
(
OwnerOrganizationName == other.OwnerOrganizationName ||
OwnerOrganizationName != null &&
OwnerOrganizationName.Equals(other.OwnerOrganizationName)
) &&
(
Seniority == other.Seniority ||
Seniority != null &&
Seniority.Equals(other.Seniority)
) &&
(
ServiceHoursLastYear == other.ServiceHoursLastYear ||
ServiceHoursLastYear != null &&
ServiceHoursLastYear.Equals(other.ServiceHoursLastYear)
) &&
(
ServiceHoursTwoYearsAgo == other.ServiceHoursTwoYearsAgo ||
ServiceHoursTwoYearsAgo != null &&
ServiceHoursTwoYearsAgo.Equals(other.ServiceHoursTwoYearsAgo)
) &&
(
ServiceHoursThreeYearsAgo == other.ServiceHoursThreeYearsAgo ||
ServiceHoursThreeYearsAgo != null &&
ServiceHoursThreeYearsAgo.Equals(other.ServiceHoursThreeYearsAgo)
) &&
(
IsSeniorityOverridden == other.IsSeniorityOverridden ||
IsSeniorityOverridden != null &&
IsSeniorityOverridden.Equals(other.IsSeniorityOverridden)
) &&
(
SeniorityOverrideReason == other.SeniorityOverrideReason ||
SeniorityOverrideReason != null &&
SeniorityOverrideReason.Equals(other.SeniorityOverrideReason)
);
}
/// <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
hash = hash * 59 + Id.GetHashCode();
hash = hash * 59 + StartDate.GetHashCode();
hash = hash * 59 + EndDate.GetHashCode();
if (LocalArea != null)
{
hash = hash * 59 + LocalArea.GetHashCode();
}
if (Equipment != null)
{
hash = hash * 59 + Equipment.GetHashCode();
}
if (BlockNumber != null)
{
hash = hash * 59 + BlockNumber.GetHashCode();
}
if (Owner != null)
{
hash = hash * 59 + Owner.GetHashCode();
}
if (OwnerOrganizationName != null)
{
hash = hash * 59 + OwnerOrganizationName.GetHashCode();
}
if (Seniority != null)
{
hash = hash * 59 + Seniority.GetHashCode();
}
if (ServiceHoursLastYear != null)
{
hash = hash * 59 + ServiceHoursLastYear.GetHashCode();
}
if (ServiceHoursTwoYearsAgo != null)
{
hash = hash * 59 + ServiceHoursTwoYearsAgo.GetHashCode();
}
if (ServiceHoursThreeYearsAgo != null)
{
hash = hash * 59 + ServiceHoursThreeYearsAgo.GetHashCode();
}
if (IsSeniorityOverridden != null)
{
hash = hash * 59 + IsSeniorityOverridden.GetHashCode();
}
if (SeniorityOverrideReason != null)
{
hash = hash * 59 + SeniorityOverrideReason.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(SeniorityAudit left, SeniorityAudit right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(SeniorityAudit left, SeniorityAudit right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
/*
* $Id: IrcCommands.cs 288 2008-07-28 21:56:47Z meebey $
* $URL: svn://svn.qnetp.net/smartirc/SmartIrc4net/trunk/src/IrcCommands/IrcCommands.cs $
* $Rev: 288 $
* $Author: meebey $
* $Date: 2008-07-28 17:56:47 -0400 (Mon, 28 Jul 2008) $
*
* SmartIrc4net - the IRC library for .NET/C# <http://smartirc4net.sf.net>
*
* Copyright (c) 2003-2005 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net>
*
* Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Text;
namespace Meebey.SmartIrc4net
{
/// <summary>
///
/// </summary>
/// <threadsafety static="true" instance="true" />
public class IrcCommands: IrcConnection
{
private int _MaxModeChanges = 3;
protected int MaxModeChanges {
get {
return _MaxModeChanges;
}
set {
_MaxModeChanges = value;
}
}
#if LOG4NET
public IrcCommands()
{
Logger.Main.Debug("IrcCommands created");
}
#endif
#if LOG4NET
~IrcCommands()
{
Logger.Main.Debug("IrcCommands destroyed");
}
#endif
// API commands
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="destination"></param>
/// <param name="message"></param>
/// <param name="priority"></param>
public void SendMessage(SendType type, string destination, string message, Priority priority)
{
switch(type) {
case SendType.Message:
RfcPrivmsg(destination, message, priority);
break;
case SendType.Action:
RfcPrivmsg(destination, "\x1"+"ACTION "+message+"\x1", priority);
break;
case SendType.Notice:
RfcNotice(destination, message, priority);
break;
case SendType.CtcpRequest:
RfcPrivmsg(destination, "\x1"+message+"\x1", priority);
break;
case SendType.CtcpReply:
RfcNotice(destination, "\x1"+message+"\x1", priority);
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="destination"></param>
/// <param name="message"></param>
public void SendMessage(SendType type, string destination, string message)
{
SendMessage(type, destination, message, Priority.Medium);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="message"></param>
/// <param name="priority"></param>
public void SendReply(IrcMessageData data, string message, Priority priority)
{
switch (data.Type) {
case ReceiveType.ChannelMessage:
SendMessage(SendType.Message, data.Channel, message, priority);
break;
case ReceiveType.QueryMessage:
SendMessage(SendType.Message, data.Nick, message, priority);
break;
case ReceiveType.QueryNotice:
SendMessage(SendType.Notice, data.Nick, message, priority);
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="message"></param>
public void SendReply(IrcMessageData data, string message)
{
SendReply(data, message, Priority.Medium);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void Op(string channel, string nickname, Priority priority)
{
WriteLine(Rfc2812.Mode(channel, "+o "+nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/*
public void Op(string channel, string[] nicknames)
{
if (nicknames == null) {
throw new ArgumentNullException("nicknames");
}
string[] modes = new string[nicknames.Length];
for (int i = 0; i < nicknames.Length; i++) {
modes[i] = "+o";
}
WriteLine(Rfc2812.Mode(channel, modes, nicknames));
}
*/
public void Op(string channel, string nickname)
{
WriteLine(Rfc2812.Mode(channel, "+o "+nickname));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void Deop(string channel, string nickname, Priority priority)
{
WriteLine(Rfc2812.Mode(channel, "-o "+nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
public void Deop(string channel, string nickname)
{
WriteLine(Rfc2812.Mode(channel, "-o "+nickname));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void Voice(string channel, string nickname, Priority priority)
{
WriteLine(Rfc2812.Mode(channel, "+v "+nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
public void Voice(string channel, string nickname)
{
WriteLine(Rfc2812.Mode(channel, "+v "+nickname));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void Devoice(string channel, string nickname, Priority priority)
{
WriteLine(Rfc2812.Mode(channel, "-v "+nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
public void Devoice(string channel, string nickname)
{
WriteLine(Rfc2812.Mode(channel, "-v "+nickname));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="priority"></param>
public void Ban(string channel, Priority priority)
{
WriteLine(Rfc2812.Mode(channel, "+b"), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
public void Ban(string channel)
{
WriteLine(Rfc2812.Mode(channel, "+b"));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="hostmask"></param>
/// <param name="priority"></param>
public void Ban(string channel, string hostmask, Priority priority)
{
WriteLine(Rfc2812.Mode(channel, "+b "+hostmask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="hostmask"></param>
public void Ban(string channel, string hostmask)
{
WriteLine(Rfc2812.Mode(channel, "+b "+hostmask));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="hostmask"></param>
/// <param name="priority"></param>
public void Unban(string channel, string hostmask, Priority priority)
{
WriteLine(Rfc2812.Mode(channel, "-b "+hostmask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="hostmask"></param>
public void Unban(string channel, string hostmask)
{
WriteLine(Rfc2812.Mode(channel, "-b "+hostmask));
}
// non-RFC commands
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void Halfop(string channel, string nickname, Priority priority)
{
WriteLine(Rfc2812.Mode(channel, "+h "+nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
public void Dehalfop(string channel, string nickname)
{
WriteLine(Rfc2812.Mode(channel, "-h "+nickname));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/*
public void Mode(string target, string[] newModes, string[] newModeParameters)
{
int modeLines = (int) Math.Ceiling(newModes.Length / (double) _MaxModeChanges);
for (int i = 0; i < modeLines; i++) {
int chunkOffset = i * _MaxModeChanges;
string[] newModeChunks = new string[_MaxModeChanges];
string[] newModeParameterChunks = new string[_MaxModeChanges];
for (int j = 0; j < _MaxModeChanges; j++) {
newModeChunks[j] = newModes[chunkOffset + j];
newModeParameterChunks[j] = newModeParameterChunks[chunkOffset + j];
}
WriteLine(Rfc2812.Mode(target, newModeChunks, newModeParameterChunks));
}
}
*/
#region RFC commands
/// <summary>
///
/// </summary>
/// <param name="password"></param>
/// <param name="priority"></param>
public void RfcPass(string password, Priority priority)
{
WriteLine(Rfc2812.Pass(password), priority);
}
/// <summary>
///
/// </summary>
/// <param name="password"></param>
public void RfcPass(string password)
{
WriteLine(Rfc2812.Pass(password));
}
/// <summary>
///
/// </summary>
/// <param name="username"></param>
/// <param name="usermode"></param>
/// <param name="realname"></param>
/// <param name="priority"></param>
public void RfcUser(string username, int usermode, string realname, Priority priority)
{
WriteLine(Rfc2812.User(username, usermode, realname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="username"></param>
/// <param name="usermode"></param>
/// <param name="realname"></param>
public void RfcUser(string username, int usermode, string realname)
{
WriteLine(Rfc2812.User(username, usermode, realname));
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="password"></param>
/// <param name="priority"></param>
public void RfcOper(string name, string password, Priority priority)
{
WriteLine(Rfc2812.Oper(name, password), priority);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="password"></param>
public void RfcOper(string name, string password)
{
WriteLine(Rfc2812.Oper(name, password));
}
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="message"></param>
/// <param name="priority"></param>
public void RfcPrivmsg(string destination, string message, Priority priority)
{
WriteLine(Rfc2812.Privmsg(destination, message), priority);
}
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="message"></param>
public void RfcPrivmsg(string destination, string message)
{
WriteLine(Rfc2812.Privmsg(destination, message));
}
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="message"></param>
/// <param name="priority"></param>
public void RfcNotice(string destination, string message, Priority priority)
{
WriteLine(Rfc2812.Notice(destination, message), priority);
}
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="message"></param>
public void RfcNotice(string destination, string message)
{
WriteLine(Rfc2812.Notice(destination, message));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="priority"></param>
public void RfcJoin(string channel, Priority priority)
{
WriteLine(Rfc2812.Join(channel), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
public void RfcJoin(string channel)
{
WriteLine(Rfc2812.Join(channel));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="priority"></param>
public void RfcJoin(string[] channels, Priority priority)
{
WriteLine(Rfc2812.Join(channels), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
public void RfcJoin(string[] channels)
{
WriteLine(Rfc2812.Join(channels));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="key"></param>
/// <param name="priority"></param>
public void RfcJoin(string channel, string key, Priority priority)
{
WriteLine(Rfc2812.Join(channel, key), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="key"></param>
public void RfcJoin(string channel, string key)
{
WriteLine(Rfc2812.Join(channel, key));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="keys"></param>
/// <param name="priority"></param>
public void RfcJoin(string[] channels, string[] keys, Priority priority)
{
WriteLine(Rfc2812.Join(channels, keys), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="keys"></param>
public void RfcJoin(string[] channels, string[] keys)
{
WriteLine(Rfc2812.Join(channels, keys));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="priority"></param>
public void RfcPart(string channel, Priority priority)
{
WriteLine(Rfc2812.Part(channel), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
public void RfcPart(string channel)
{
WriteLine(Rfc2812.Part(channel));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="priority"></param>
public void RfcPart(string[] channels, Priority priority)
{
WriteLine(Rfc2812.Part(channels), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
public void RfcPart(string[] channels)
{
WriteLine(Rfc2812.Part(channels));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="partmessage"></param>
/// <param name="priority"></param>
public void RfcPart(string channel, string partmessage, Priority priority)
{
WriteLine(Rfc2812.Part(channel, partmessage), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="partmessage"></param>
public void RfcPart(string channel, string partmessage)
{
WriteLine(Rfc2812.Part(channel, partmessage));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="partmessage"></param>
/// <param name="priority"></param>
public void RfcPart(string[] channels, string partmessage, Priority priority)
{
WriteLine(Rfc2812.Part(channels, partmessage), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="partmessage"></param>
public void RfcPart(string[] channels, string partmessage)
{
WriteLine(Rfc2812.Part(channels, partmessage));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void RfcKick(string channel, string nickname, Priority priority)
{
WriteLine(Rfc2812.Kick(channel, nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
public void RfcKick(string channel, string nickname)
{
WriteLine(Rfc2812.Kick(channel, nickname));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void RfcKick(string[] channels, string nickname, Priority priority)
{
WriteLine(Rfc2812.Kick(channels, nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="nickname"></param>
public void RfcKick(string[] channels, string nickname)
{
WriteLine(Rfc2812.Kick(channels, nickname));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nicknames"></param>
/// <param name="priority"></param>
public void RfcKick(string channel, string[] nicknames, Priority priority)
{
WriteLine(Rfc2812.Kick(channel, nicknames), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nicknames"></param>
public void RfcKick(string channel, string[] nicknames)
{
WriteLine(Rfc2812.Kick(channel, nicknames));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="nicknames"></param>
/// <param name="priority"></param>
public void RfcKick(string[] channels, string[] nicknames, Priority priority)
{
WriteLine(Rfc2812.Kick(channels, nicknames), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="nicknames"></param>
public void RfcKick(string[] channels, string[] nicknames)
{
WriteLine(Rfc2812.Kick(channels, nicknames));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/// <param name="comment"></param>
/// <param name="priority"></param>
public void RfcKick(string channel, string nickname, string comment, Priority priority)
{
WriteLine(Rfc2812.Kick(channel, nickname, comment), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nickname"></param>
/// <param name="comment"></param>
public void RfcKick(string channel, string nickname, string comment)
{
WriteLine(Rfc2812.Kick(channel, nickname, comment));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="nickname"></param>
/// <param name="comment"></param>
/// <param name="priority"></param>
public void RfcKick(string[] channels, string nickname, string comment, Priority priority)
{
WriteLine(Rfc2812.Kick(channels, nickname, comment), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="nickname"></param>
/// <param name="comment"></param>
public void RfcKick(string[] channels, string nickname, string comment)
{
WriteLine(Rfc2812.Kick(channels, nickname, comment));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nicknames"></param>
/// <param name="comment"></param>
/// <param name="priority"></param>
public void RfcKick(string channel, string[] nicknames, string comment, Priority priority)
{
WriteLine(Rfc2812.Kick(channel, nicknames, comment), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="nicknames"></param>
/// <param name="comment"></param>
public void RfcKick(string channel, string[] nicknames, string comment)
{
WriteLine(Rfc2812.Kick(channel, nicknames, comment));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="nicknames"></param>
/// <param name="comment"></param>
/// <param name="priority"></param>
public void RfcKick(string[] channels, string[] nicknames, string comment, Priority priority)
{
WriteLine(Rfc2812.Kick(channels, nicknames, comment), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="nicknames"></param>
/// <param name="comment"></param>
public void RfcKick(string[] channels, string[] nicknames, string comment)
{
WriteLine(Rfc2812.Kick(channels, nicknames, comment));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcMotd(Priority priority)
{
WriteLine(Rfc2812.Motd(), priority);
}
/// <summary>
///
/// </summary>
public void RfcMotd()
{
WriteLine(Rfc2812.Motd());
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcMotd(string target, Priority priority)
{
WriteLine(Rfc2812.Motd(target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
public void RfcMotd(string target)
{
WriteLine(Rfc2812.Motd(target));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
[Obsolete("use RfcLusers(Priority) instead")]
public void RfcLuser(Priority priority)
{
RfcLusers(priority);
}
public void RfcLusers(Priority priority)
{
WriteLine(Rfc2812.Lusers(), priority);
}
/// <summary>
///
/// </summary>
[Obsolete("use RfcLusers() instead")]
public void RfcLuser()
{
RfcLusers();
}
public void RfcLusers()
{
WriteLine(Rfc2812.Lusers());
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="priority"></param>
[Obsolete("use RfcLusers(string, Priority) instead")]
public void RfcLuser(string mask, Priority priority)
{
RfcLusers(mask, priority);
}
public void RfcLusers(string mask, Priority priority)
{
WriteLine(Rfc2812.Lusers(mask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
[Obsolete("use RfcLusers(string) instead")]
public void RfcLuser(string mask)
{
RfcLusers(mask);
}
public void RfcLusers(string mask)
{
WriteLine(Rfc2812.Lusers(mask));
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
[Obsolete("use RfcLusers(string, string, Priority) instead")]
public void RfcLuser(string mask, string target, Priority priority)
{
RfcLusers(mask, target, priority);
}
public void RfcLusers(string mask, string target, Priority priority)
{
WriteLine(Rfc2812.Lusers(mask, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="target"></param>
[Obsolete("use RfcLusers(string, string) instead")]
public void RfcLuser(string mask, string target)
{
RfcLusers(mask, target);
}
public void RfcLusers(string mask, string target)
{
WriteLine(Rfc2812.Lusers(mask, target));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcVersion(Priority priority)
{
WriteLine(Rfc2812.Version(), priority);
}
/// <summary>
///
/// </summary>
public void RfcVersion()
{
WriteLine(Rfc2812.Version());
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcVersion(string target, Priority priority)
{
WriteLine(Rfc2812.Version(target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
public void RfcVersion(string target)
{
WriteLine(Rfc2812.Version(target));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcStats(Priority priority)
{
WriteLine(Rfc2812.Stats(), priority);
}
/// <summary>
///
/// </summary>
public void RfcStats()
{
WriteLine(Rfc2812.Stats());
}
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="priority"></param>
public void RfcStats(string query, Priority priority)
{
WriteLine(Rfc2812.Stats(query), priority);
}
/// <summary>
///
/// </summary>
/// <param name="query"></param>
public void RfcStats(string query)
{
WriteLine(Rfc2812.Stats(query));
}
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcStats(string query, string target, Priority priority)
{
WriteLine(Rfc2812.Stats(query, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="target"></param>
public void RfcStats(string query, string target)
{
WriteLine(Rfc2812.Stats(query, target));
}
/// <summary>
///
/// </summary>
public void RfcLinks()
{
WriteLine(Rfc2812.Links());
}
/// <summary>
///
/// </summary>
/// <param name="servermask"></param>
/// <param name="priority"></param>
public void RfcLinks(string servermask, Priority priority)
{
WriteLine(Rfc2812.Links(servermask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="servermask"></param>
public void RfcLinks(string servermask)
{
WriteLine(Rfc2812.Links(servermask));
}
/// <summary>
///
/// </summary>
/// <param name="remoteserver"></param>
/// <param name="servermask"></param>
/// <param name="priority"></param>
public void RfcLinks(string remoteserver, string servermask, Priority priority)
{
WriteLine(Rfc2812.Links(remoteserver, servermask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="remoteserver"></param>
/// <param name="servermask"></param>
public void RfcLinks(string remoteserver, string servermask)
{
WriteLine(Rfc2812.Links(remoteserver, servermask));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcTime(Priority priority)
{
WriteLine(Rfc2812.Time(), priority);
}
/// <summary>
///
/// </summary>
public void RfcTime()
{
WriteLine(Rfc2812.Time());
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcTime(string target, Priority priority)
{
WriteLine(Rfc2812.Time(target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
public void RfcTime(string target)
{
WriteLine(Rfc2812.Time(target));
}
/// <summary>
///
/// </summary>
/// <param name="targetserver"></param>
/// <param name="port"></param>
/// <param name="priority"></param>
public void RfcConnect(string targetserver, string port, Priority priority)
{
WriteLine(Rfc2812.Connect(targetserver, port), priority);
}
/// <summary>
///
/// </summary>
/// <param name="targetserver"></param>
/// <param name="port"></param>
public void RfcConnect(string targetserver, string port)
{
WriteLine(Rfc2812.Connect(targetserver, port));
}
/// <summary>
///
/// </summary>
/// <param name="targetserver"></param>
/// <param name="port"></param>
/// <param name="remoteserver"></param>
/// <param name="priority"></param>
public void RfcConnect(string targetserver, string port, string remoteserver, Priority priority)
{
WriteLine(Rfc2812.Connect(targetserver, port, remoteserver), priority);
}
/// <summary>
///
/// </summary>
/// <param name="targetserver"></param>
/// <param name="port"></param>
/// <param name="remoteserver"></param>
public void RfcConnect(string targetserver, string port, string remoteserver)
{
WriteLine(Rfc2812.Connect(targetserver, port, remoteserver));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcTrace(Priority priority)
{
WriteLine(Rfc2812.Trace(), priority);
}
/// <summary>
///
/// </summary>
public void RfcTrace()
{
WriteLine(Rfc2812.Trace());
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcTrace(string target, Priority priority)
{
WriteLine(Rfc2812.Trace(target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
public void RfcTrace(string target)
{
WriteLine(Rfc2812.Trace(target));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcAdmin(Priority priority)
{
WriteLine(Rfc2812.Admin(), priority);
}
/// <summary>
///
/// </summary>
public void RfcAdmin()
{
WriteLine(Rfc2812.Admin());
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcAdmin(string target, Priority priority)
{
WriteLine(Rfc2812.Admin(target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
public void RfcAdmin(string target)
{
WriteLine(Rfc2812.Admin(target));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcInfo(Priority priority)
{
WriteLine(Rfc2812.Info(), priority);
}
/// <summary>
///
/// </summary>
public void RfcInfo()
{
WriteLine(Rfc2812.Info());
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcInfo(string target, Priority priority)
{
WriteLine(Rfc2812.Info(target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
public void RfcInfo(string target)
{
WriteLine(Rfc2812.Info(target));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcServlist(Priority priority)
{
WriteLine(Rfc2812.Servlist(), priority);
}
/// <summary>
///
/// </summary>
public void RfcServlist()
{
WriteLine(Rfc2812.Servlist());
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="priority"></param>
public void RfcServlist(string mask, Priority priority)
{
WriteLine(Rfc2812.Servlist(mask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
public void RfcServlist(string mask)
{
WriteLine(Rfc2812.Servlist(mask));
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="type"></param>
/// <param name="priority"></param>
public void RfcServlist(string mask, string type, Priority priority)
{
WriteLine(Rfc2812.Servlist(mask, type), priority);
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="type"></param>
public void RfcServlist(string mask, string type)
{
WriteLine(Rfc2812.Servlist(mask, type));
}
/// <summary>
///
/// </summary>
/// <param name="servicename"></param>
/// <param name="servicetext"></param>
/// <param name="priority"></param>
public void RfcSquery(string servicename, string servicetext, Priority priority)
{
WriteLine(Rfc2812.Squery(servicename, servicetext), priority);
}
/// <summary>
///
/// </summary>
/// <param name="servicename"></param>
/// <param name="servicetext"></param>
public void RfcSquery(string servicename, string servicetext)
{
WriteLine(Rfc2812.Squery(servicename, servicetext));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="priority"></param>
public void RfcList(string channel, Priority priority)
{
WriteLine(Rfc2812.List(channel), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
public void RfcList(string channel)
{
WriteLine(Rfc2812.List(channel));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="priority"></param>
public void RfcList(string[] channels, Priority priority)
{
WriteLine(Rfc2812.List(channels), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
public void RfcList(string[] channels)
{
WriteLine(Rfc2812.List(channels));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcList(string channel, string target, Priority priority)
{
WriteLine(Rfc2812.List(channel, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="target"></param>
public void RfcList(string channel, string target)
{
WriteLine(Rfc2812.List(channel, target));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcList(string[] channels, string target, Priority priority)
{
WriteLine(Rfc2812.List(channels, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="target"></param>
public void RfcList(string[] channels, string target)
{
WriteLine(Rfc2812.List(channels, target));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="priority"></param>
public void RfcNames(string channel, Priority priority)
{
WriteLine(Rfc2812.Names(channel), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
public void RfcNames(string channel)
{
WriteLine(Rfc2812.Names(channel));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="priority"></param>
public void RfcNames(string[] channels, Priority priority)
{
WriteLine(Rfc2812.Names(channels), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
public void RfcNames(string[] channels)
{
WriteLine(Rfc2812.Names(channels));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcNames(string channel, string target, Priority priority)
{
WriteLine(Rfc2812.Names(channel, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="target"></param>
public void RfcNames(string channel, string target)
{
WriteLine(Rfc2812.Names(channel, target));
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcNames(string[] channels, string target, Priority priority)
{
WriteLine(Rfc2812.Names(channels, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channels"></param>
/// <param name="target"></param>
public void RfcNames(string[] channels, string target)
{
WriteLine(Rfc2812.Names(channels, target));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="priority"></param>
public void RfcTopic(string channel, Priority priority)
{
WriteLine(Rfc2812.Topic(channel), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
public void RfcTopic(string channel)
{
WriteLine(Rfc2812.Topic(channel));
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="newtopic"></param>
/// <param name="priority"></param>
public void RfcTopic(string channel, string newtopic, Priority priority)
{
WriteLine(Rfc2812.Topic(channel, newtopic), priority);
}
/// <summary>
///
/// </summary>
/// <param name="channel"></param>
/// <param name="newtopic"></param>
public void RfcTopic(string channel, string newtopic)
{
WriteLine(Rfc2812.Topic(channel, newtopic));
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcMode(string target, Priority priority)
{
WriteLine(Rfc2812.Mode(target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
public void RfcMode(string target)
{
WriteLine(Rfc2812.Mode(target));
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="newmode"></param>
/// <param name="priority"></param>
public void RfcMode(string target, string newmode, Priority priority)
{
WriteLine(Rfc2812.Mode(target, newmode), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="newmode"></param>
public void RfcMode(string target, string newmode)
{
WriteLine(Rfc2812.Mode(target, newmode));
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="distribution"></param>
/// <param name="info"></param>
/// <param name="priority"></param>
public void RfcService(string nickname, string distribution, string info, Priority priority)
{
WriteLine(Rfc2812.Service(nickname, distribution, info), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="distribution"></param>
/// <param name="info"></param>
public void RfcService(string nickname, string distribution, string info)
{
WriteLine(Rfc2812.Service(nickname, distribution, info));
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="channel"></param>
/// <param name="priority"></param>
public void RfcInvite(string nickname, string channel, Priority priority)
{
WriteLine(Rfc2812.Invite(nickname, channel), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="channel"></param>
public void RfcInvite(string nickname, string channel)
{
WriteLine(Rfc2812.Invite(nickname, channel));
}
/// <summary>
///
/// </summary>
/// <param name="newnickname"></param>
/// <param name="priority"></param>
public void RfcNick(string newnickname, Priority priority)
{
WriteLine(Rfc2812.Nick(newnickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="newnickname"></param>
public void RfcNick(string newnickname)
{
WriteLine(Rfc2812.Nick(newnickname));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcWho(Priority priority)
{
WriteLine(Rfc2812.Who(), priority);
}
/// <summary>
///
/// </summary>
public void RfcWho()
{
WriteLine(Rfc2812.Who());
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="priority"></param>
public void RfcWho(string mask, Priority priority)
{
WriteLine(Rfc2812.Who(mask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
public void RfcWho(string mask)
{
WriteLine(Rfc2812.Who(mask));
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="ircop"></param>
/// <param name="priority"></param>
public void RfcWho(string mask, bool ircop, Priority priority)
{
WriteLine(Rfc2812.Who(mask, ircop), priority);
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="ircop"></param>
public void RfcWho(string mask, bool ircop)
{
WriteLine(Rfc2812.Who(mask, ircop));
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
/// <param name="priority"></param>
public void RfcWhois(string mask, Priority priority)
{
WriteLine(Rfc2812.Whois(mask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="mask"></param>
public void RfcWhois(string mask)
{
WriteLine(Rfc2812.Whois(mask));
}
/// <summary>
///
/// </summary>
/// <param name="masks"></param>
/// <param name="priority"></param>
public void RfcWhois(string[] masks, Priority priority)
{
WriteLine(Rfc2812.Whois(masks), priority);
}
/// <summary>
///
/// </summary>
/// <param name="masks"></param>
public void RfcWhois(string[] masks)
{
WriteLine(Rfc2812.Whois(masks));
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="mask"></param>
/// <param name="priority"></param>
public void RfcWhois(string target, string mask, Priority priority)
{
WriteLine(Rfc2812.Whois(target, mask), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="mask"></param>
public void RfcWhois(string target, string mask)
{
WriteLine(Rfc2812.Whois(target, mask));
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="masks"></param>
/// <param name="priority"></param>
public void RfcWhois(string target, string[] masks, Priority priority)
{
WriteLine(Rfc2812.Whois(target ,masks), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="masks"></param>
public void RfcWhois(string target, string[] masks)
{
WriteLine(Rfc2812.Whois(target, masks));
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void RfcWhowas(string nickname, Priority priority)
{
WriteLine(Rfc2812.Whowas(nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
public void RfcWhowas(string nickname)
{
WriteLine(Rfc2812.Whowas(nickname));
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
/// <param name="priority"></param>
public void RfcWhowas(string[] nicknames, Priority priority)
{
WriteLine(Rfc2812.Whowas(nicknames), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
public void RfcWhowas(string[] nicknames)
{
WriteLine(Rfc2812.Whowas(nicknames));
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="count"></param>
/// <param name="priority"></param>
public void RfcWhowas(string nickname, string count, Priority priority)
{
WriteLine(Rfc2812.Whowas(nickname, count), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="count"></param>
public void RfcWhowas(string nickname, string count)
{
WriteLine(Rfc2812.Whowas(nickname, count));
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
/// <param name="count"></param>
/// <param name="priority"></param>
public void RfcWhowas(string[] nicknames, string count, Priority priority)
{
WriteLine(Rfc2812.Whowas(nicknames, count), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
/// <param name="count"></param>
public void RfcWhowas(string[] nicknames, string count)
{
WriteLine(Rfc2812.Whowas(nicknames, count));
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="count"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcWhowas(string nickname, string count, string target, Priority priority)
{
WriteLine(Rfc2812.Whowas(nickname, count, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="count"></param>
/// <param name="target"></param>
public void RfcWhowas(string nickname, string count, string target)
{
WriteLine(Rfc2812.Whowas(nickname, count, target));
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
/// <param name="count"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcWhowas(string[] nicknames, string count, string target, Priority priority)
{
WriteLine(Rfc2812.Whowas(nicknames, count, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
/// <param name="count"></param>
/// <param name="target"></param>
public void RfcWhowas(string[] nicknames, string count, string target)
{
WriteLine(Rfc2812.Whowas(nicknames, count, target));
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="comment"></param>
/// <param name="priority"></param>
public void RfcKill(string nickname, string comment, Priority priority)
{
WriteLine(Rfc2812.Kill(nickname, comment), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="comment"></param>
public void RfcKill(string nickname, string comment)
{
WriteLine(Rfc2812.Kill(nickname, comment));
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="priority"></param>
public void RfcPing(string server, Priority priority)
{
WriteLine(Rfc2812.Ping(server), priority);
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
public void RfcPing(string server)
{
WriteLine(Rfc2812.Ping(server));
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="server2"></param>
/// <param name="priority"></param>
public void RfcPing(string server, string server2, Priority priority)
{
WriteLine(Rfc2812.Ping(server, server2), priority);
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="server2"></param>
public void RfcPing(string server, string server2)
{
WriteLine(Rfc2812.Ping(server, server2));
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="priority"></param>
public void RfcPong(string server, Priority priority)
{
WriteLine(Rfc2812.Pong(server), priority);
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
public void RfcPong(string server)
{
WriteLine(Rfc2812.Pong(server));
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="server2"></param>
/// <param name="priority"></param>
public void RfcPong(string server, string server2, Priority priority)
{
WriteLine(Rfc2812.Pong(server, server2), priority);
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="server2"></param>
public void RfcPong(string server, string server2)
{
WriteLine(Rfc2812.Pong(server, server2));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcAway(Priority priority)
{
WriteLine(Rfc2812.Away(), priority);
}
/// <summary>
///
/// </summary>
public void RfcAway()
{
WriteLine(Rfc2812.Away());
}
/// <summary>
///
/// </summary>
/// <param name="awaytext"></param>
/// <param name="priority"></param>
public void RfcAway(string awaytext, Priority priority)
{
WriteLine(Rfc2812.Away(awaytext), priority);
}
/// <summary>
///
/// </summary>
/// <param name="awaytext"></param>
public void RfcAway(string awaytext)
{
WriteLine(Rfc2812.Away(awaytext));
}
/// <summary>
///
/// </summary>
public void RfcRehash()
{
WriteLine(Rfc2812.Rehash());
}
/// <summary>
///
/// </summary>
public void RfcDie()
{
WriteLine(Rfc2812.Die());
}
/// <summary>
///
/// </summary>
public void RfcRestart()
{
WriteLine(Rfc2812.Restart());
}
/// <summary>
///
/// </summary>
/// <param name="user"></param>
/// <param name="priority"></param>
public void RfcSummon(string user, Priority priority)
{
WriteLine(Rfc2812.Summon(user), priority);
}
/// <summary>
///
/// </summary>
/// <param name="user"></param>
public void RfcSummon(string user)
{
WriteLine(Rfc2812.Summon(user));
}
/// <summary>
///
/// </summary>
/// <param name="user"></param>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcSummon(string user, string target, Priority priority)
{
WriteLine(Rfc2812.Summon(user, target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="user"></param>
/// <param name="target"></param>
public void RfcSummon(string user, string target)
{
WriteLine(Rfc2812.Summon(user, target));
}
/// <summary>
///
/// </summary>
/// <param name="user"></param>
/// <param name="target"></param>
/// <param name="channel"></param>
/// <param name="priority"></param>
public void RfcSummon(string user, string target, string channel, Priority priority)
{
WriteLine(Rfc2812.Summon(user, target, channel), priority);
}
/// <summary>
///
/// </summary>
/// <param name="user"></param>
/// <param name="target"></param>
/// <param name="channel"></param>
public void RfcSummon(string user, string target, string channel)
{
WriteLine(Rfc2812.Summon(user, target, channel));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcUsers(Priority priority)
{
WriteLine(Rfc2812.Users(), priority);
}
/// <summary>
///
/// </summary>
public void RfcUsers()
{
WriteLine(Rfc2812.Users());
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="priority"></param>
public void RfcUsers(string target, Priority priority)
{
WriteLine(Rfc2812.Users(target), priority);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
public void RfcUsers(string target)
{
WriteLine(Rfc2812.Users(target));
}
/// <summary>
///
/// </summary>
/// <param name="wallopstext"></param>
/// <param name="priority"></param>
public void RfcWallops(string wallopstext, Priority priority)
{
WriteLine(Rfc2812.Wallops(wallopstext), priority);
}
/// <summary>
///
/// </summary>
/// <param name="wallopstext"></param>
public void RfcWallops(string wallopstext)
{
WriteLine(Rfc2812.Wallops(wallopstext));
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void RfcUserhost(string nickname, Priority priority)
{
WriteLine(Rfc2812.Userhost(nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
public void RfcUserhost(string nickname)
{
WriteLine(Rfc2812.Userhost(nickname));
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
/// <param name="priority"></param>
public void RfcUserhost(string[] nicknames, Priority priority)
{
WriteLine(Rfc2812.Userhost(nicknames), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
public void RfcUserhost(string[] nicknames)
{
WriteLine(Rfc2812.Userhost(nicknames));
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
/// <param name="priority"></param>
public void RfcIson(string nickname, Priority priority)
{
WriteLine(Rfc2812.Ison(nickname), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nickname"></param>
public void RfcIson(string nickname)
{
WriteLine(Rfc2812.Ison(nickname));
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
/// <param name="priority"></param>
public void RfcIson(string[] nicknames, Priority priority)
{
WriteLine(Rfc2812.Ison(nicknames), priority);
}
/// <summary>
///
/// </summary>
/// <param name="nicknames"></param>
public void RfcIson(string[] nicknames)
{
WriteLine(Rfc2812.Ison(nicknames));
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
public void RfcQuit(Priority priority)
{
WriteLine(Rfc2812.Quit(), priority);
}
/// <summary>
///
/// </summary>
public void RfcQuit()
{
WriteLine(Rfc2812.Quit());
}
public void RfcQuit(string quitmessage, Priority priority)
{
WriteLine(Rfc2812.Quit(quitmessage), priority);
}
/// <summary>
///
/// </summary>
/// <param name="quitmessage"></param>
public void RfcQuit(string quitmessage)
{
WriteLine(Rfc2812.Quit(quitmessage));
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="comment"></param>
/// <param name="priority"></param>
public void RfcSquit(string server, string comment, Priority priority)
{
WriteLine(Rfc2812.Squit(server, comment), priority);
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="comment"></param>
public void RfcSquit(string server, string comment)
{
WriteLine(Rfc2812.Squit(server, comment));
}
#endregion
}
}
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.Framework;
using NakedFramework.Architecture.Interactions;
using NakedFramework.Architecture.Reflect;
using NakedFramework.Architecture.Spec;
using NakedFramework.Architecture.SpecImmutable;
using NakedFramework.Core.Error;
using NakedFramework.Core.Interactions;
using NakedFramework.Core.Reflect;
using NakedFramework.Core.Util;
namespace NakedFramework.Core.Spec;
public abstract class ActionParameterSpec : IActionParameterSpec {
private readonly IActionParameterSpecImmutable actionParameterSpecImmutable;
private readonly IActionSpec parentAction;
// cache
private bool checkedForElementSpec;
private (string, IObjectSpec)[] choicesParameters;
private string description;
private IObjectSpec elementSpec;
private bool? isAutoCompleteEnabled;
private bool? isChoicesEnabled;
private bool? isInjected;
private bool? isMandatory;
private bool? isMultipleChoicesEnabled;
private bool? isNullable;
private string name;
private IObjectSpec spec;
protected internal ActionParameterSpec(int number, IActionSpec actionSpec, IActionParameterSpecImmutable actionParameterSpecImmutable, INakedFramework framework) {
Number = number;
Framework = framework;
parentAction = actionSpec ?? throw new InitialisationException($"{nameof(actionSpec)} is null");
this.actionParameterSpecImmutable = actionParameterSpecImmutable ?? throw new InitialisationException($"{nameof(actionParameterSpecImmutable)} is null");
}
public virtual IObjectSpec ElementSpec {
get {
if (!checkedForElementSpec) {
var facet = GetFacet<IElementTypeFacet>();
var es = facet?.ValueSpec;
elementSpec = es == null ? null : Framework.MetamodelManager.GetSpecification(es);
checkedForElementSpec = true;
}
return elementSpec;
}
}
public (INakedObjectAdapter value, TypeOfDefaultValue type) GetDefaultValueAndType(INakedObjectAdapter nakedObjectAdapter) {
if (parentAction.IsContributedMethod && nakedObjectAdapter != null) {
var matchingParms = parentAction.Parameters.Where(p => nakedObjectAdapter.Spec.IsOfType(p.Spec)).ToArray();
if (matchingParms.Any() && matchingParms.First() == this) {
return (nakedObjectAdapter, TypeOfDefaultValue.Explicit);
}
}
var facet = this.GetOpFacet<IActionDefaultsFacet>() ?? Spec.GetOpFacet<IDefaultedFacet>();
var (domainObject, typeOfDefaultValue) = facet switch {
IActionDefaultsFacet adf => adf.GetDefault(parentAction.RealTarget(nakedObjectAdapter), Framework),
IDefaultedFacet df => (df.Default, TypeOfDefaultValue.Implicit),
_ when nakedObjectAdapter == null => (null, TypeOfDefaultValue.Implicit),
_ when nakedObjectAdapter.Object.GetType().IsValueType => (0, TypeOfDefaultValue.Implicit),
_ => (null, TypeOfDefaultValue.Implicit)
};
return (Framework.NakedObjectManager.CreateAdapter(domainObject, null, null), typeOfDefaultValue);
}
private static IConsent GetConsent(string message) => message is null ? Allow.Default : new Veto(message);
#region IActionParameterSpec Members
public bool IsAutoCompleteEnabled {
get {
isAutoCompleteEnabled ??= ContainsFacet<IAutoCompleteFacet>();
return isAutoCompleteEnabled.Value;
}
}
public bool IsChoicesEnabled(INakedObjectAdapter adapter) {
isChoicesEnabled ??= !IsMultipleChoicesEnabled && actionParameterSpecImmutable.IsChoicesEnabled(adapter, Framework);
return isChoicesEnabled.Value;
}
public bool IsMultipleChoicesEnabled {
get {
isMultipleChoicesEnabled ??= Spec.IsCollectionOfBoundedSet(ElementSpec) ||
Spec.IsCollectionOfEnum(ElementSpec) ||
actionParameterSpecImmutable.IsMultipleChoicesEnabled;
return isMultipleChoicesEnabled.Value;
}
}
public virtual int Number { get; }
protected INakedFramework Framework { get; }
public virtual IActionSpec Action => parentAction;
public virtual IObjectSpec Spec => spec ??= Framework.MetamodelManager.GetSpecification(actionParameterSpecImmutable.Specification);
public string Name(INakedObjectAdapter nakedObjectAdapter) => name ??= GetFacet<IMemberNamedFacet>().FriendlyName(nakedObjectAdapter, Framework);
public virtual string Description(INakedObjectAdapter nakedObjectAdapter) => description ??= GetFacet<IDescribedAsFacet>().Description(nakedObjectAdapter, Framework) ?? "";
public virtual bool IsMandatory {
get {
isMandatory ??= GetFacet<IMandatoryFacet>().IsMandatory;
return isMandatory.Value;
}
}
public virtual bool IsInjected {
get {
isInjected ??= GetFacet<IInjectedFacet>() is not null;
return isInjected.Value;
}
}
public virtual Type[] FacetTypes => actionParameterSpecImmutable.FacetTypes;
public virtual IIdentifier Identifier => parentAction.Identifier;
public virtual bool ContainsFacet(Type facetType) => actionParameterSpecImmutable.ContainsFacet(facetType);
public virtual bool ContainsFacet<T>() where T : IFacet => actionParameterSpecImmutable.ContainsFacet<T>();
public virtual IFacet GetFacet(Type type) => actionParameterSpecImmutable.GetFacet(type);
public virtual T GetFacet<T>() where T : IFacet => actionParameterSpecImmutable.GetFacet<T>();
public virtual IEnumerable<IFacet> GetFacets() => actionParameterSpecImmutable.GetFacets();
public IConsent IsValid(INakedObjectAdapter nakedObjectAdapter, INakedObjectAdapter proposedValue) {
if (proposedValue is not null && !proposedValue.Spec.IsOfType(Spec)) {
var msg = string.Format(NakedObjects.Resources.NakedObjects.TypeMismatchError, Spec.SingularName);
return GetConsent(msg);
}
var buf = new InteractionBuffer();
IInteractionContext ic = InteractionContext.ModifyingPropParam(Framework, false, parentAction.RealTarget(nakedObjectAdapter), Identifier, proposedValue);
InteractionUtils.IsValid(this, ic, buf);
return InteractionUtils.IsValid(buf);
}
private string GetDisabledMessage() => GetFacet<IDisabledFacet>() is { } df ? df.DisabledReason(null) : null;
public virtual IConsent IsUsable(INakedObjectAdapter target) => GetConsent(GetDisabledMessage());
public bool IsNullable {
get {
isNullable ??= ContainsFacet(typeof(INullableFacet));
return isNullable.Value;
}
}
public (string, IObjectSpec)[] GetChoicesParameters() {
if (choicesParameters is null) {
var choicesFacet = GetFacet<IActionChoicesFacet>();
choicesParameters = choicesFacet is null
? Array.Empty<(string, IObjectSpec)>()
: choicesFacet.ParameterNamesAndTypes.Select(t => {
var (pName, pSpec) = t;
return (pName, Framework.MetamodelManager.GetSpecification(pSpec));
}).ToArray();
}
return choicesParameters;
}
public INakedObjectAdapter[] GetChoices(INakedObjectAdapter nakedObjectAdapter, IDictionary<string, INakedObjectAdapter> parameterNameValues) {
var choicesFacet = GetFacet<IActionChoicesFacet>();
var enumFacet = GetFacet<IEnumFacet>();
var manager = Framework.NakedObjectManager;
var persistor = Framework.Persistor;
if (choicesFacet is not null) {
var options = choicesFacet.GetChoices(parentAction.RealTarget(nakedObjectAdapter), parameterNameValues, Framework);
if (enumFacet is not null) {
options = enumFacet.GetChoices(parentAction.RealTarget(nakedObjectAdapter), options);
}
return manager.GetCollectionOfAdaptedObjects(options).ToArray();
}
if (enumFacet is not null) {
return manager.GetCollectionOfAdaptedObjects(enumFacet.GetChoices(parentAction.RealTarget(nakedObjectAdapter))).ToArray();
}
if (Spec.IsBoundedSet()) {
return manager.GetCollectionOfAdaptedObjects(persistor.Instances(Spec)).ToArray();
}
if (Spec.IsCollectionOfBoundedSet(ElementSpec) || Spec.IsCollectionOfEnum(ElementSpec)) {
var elementEnumFacet = ElementSpec.GetFacet<IEnumFacet>();
var domainObjects = elementEnumFacet != null ? (IEnumerable)elementEnumFacet.GetChoices(parentAction.RealTarget(nakedObjectAdapter)) : persistor.Instances(ElementSpec);
return manager.GetCollectionOfAdaptedObjects(domainObjects).ToArray();
}
return null;
}
public INakedObjectAdapter[] GetCompletions(INakedObjectAdapter nakedObjectAdapter, string autoCompleteParm) {
var autoCompleteFacet = GetFacet<IAutoCompleteFacet>();
return autoCompleteFacet is null ? null : Framework.NakedObjectManager.GetCollectionOfAdaptedObjects(autoCompleteFacet.GetCompletions(parentAction.RealTarget(nakedObjectAdapter), autoCompleteParm, Framework)).ToArray();
}
public INakedObjectAdapter GetDefault(INakedObjectAdapter nakedObjectAdapter) => GetDefaultValueAndType(nakedObjectAdapter).value;
public TypeOfDefaultValue GetDefaultType(INakedObjectAdapter nakedObjectAdapter) => GetDefaultValueAndType(nakedObjectAdapter).type;
public string Id => Identifier.MemberParameterNames[Number];
#endregion
}
| |
// <copyright file="UserLUTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization
{
/// <summary>
/// LU factorization tests for a user matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class UserLUTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorLU = matrixI.LU();
// Check lower triangular part.
var matrixL = factorLU.L;
Assert.AreEqual(matrixI.RowCount, matrixL.RowCount);
Assert.AreEqual(matrixI.ColumnCount, matrixL.ColumnCount);
for (var i = 0; i < matrixL.RowCount; i++)
{
for (var j = 0; j < matrixL.ColumnCount; j++)
{
Assert.AreEqual(i == j ? 1.0 : 0.0, matrixL[i, j]);
}
}
// Check upper triangular part.
var matrixU = factorLU.U;
Assert.AreEqual(matrixI.RowCount, matrixU.RowCount);
Assert.AreEqual(matrixI.ColumnCount, matrixU.ColumnCount);
for (var i = 0; i < matrixU.RowCount; i++)
{
for (var j = 0; j < matrixU.ColumnCount; j++)
{
Assert.AreEqual(i == j ? 1.0 : 0.0, matrixU[i, j]);
}
}
}
/// <summary>
/// LU factorization fails with a non-square matrix.
/// </summary>
[Test]
public void LUFailsWithNonSquareMatrix()
{
var matrix = new UserDefinedMatrix(3, 2);
Assert.That(() => matrix.LU(), Throws.ArgumentException);
}
/// <summary>
/// Identity determinant is one.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void IdentityDeterminantIsOne(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var lu = matrixI.LU();
Assert.AreEqual(1.0, lu.Determinant);
}
/// <summary>
/// Can factorize a random square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanFactorizeRandomMatrix(int order)
{
var matrixX = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var factorLU = matrixX.LU();
var matrixL = factorLU.L;
var matrixU = factorLU.U;
// Make sure the factors have the right dimensions.
Assert.AreEqual(order, matrixL.RowCount);
Assert.AreEqual(order, matrixL.ColumnCount);
Assert.AreEqual(order, matrixU.RowCount);
Assert.AreEqual(order, matrixU.ColumnCount);
// Make sure the L factor is lower triangular.
for (var i = 0; i < matrixL.RowCount; i++)
{
Assert.AreEqual(1.0, matrixL[i, i]);
for (var j = i + 1; j < matrixL.ColumnCount; j++)
{
Assert.AreEqual(0.0, matrixL[i, j]);
}
}
// Make sure the U factor is upper triangular.
for (var i = 0; i < matrixL.RowCount; i++)
{
for (var j = 0; j < i; j++)
{
Assert.AreEqual(0.0, matrixU[i, j]);
}
}
// Make sure the LU factor times it's transpose is the original matrix.
var matrixXfromLU = matrixL * matrixU;
var permutationInverse = factorLU.P.Inverse();
matrixXfromLU.PermuteRows(permutationInverse);
for (var i = 0; i < matrixXfromLU.RowCount; i++)
{
for (var j = 0; j < matrixXfromLU.ColumnCount; j++)
{
Assert.AreEqual(matrixX[i, j], matrixXfromLU[i, j], 1e-4);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVector(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var vectorb = new UserDefinedVector(Vector<float>.Build.Random(order, 1).ToArray());
var resultx = factorLU.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var matrixX = factorLU.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var vectorb = new UserDefinedVector(Vector<float>.Build.Random(order, 1).ToArray());
var vectorbCopy = vectorb.Clone();
var resultx = new UserDefinedVector(order);
factorLU.Solve(vectorb, resultx);
Assert.AreEqual(vectorb.Count, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="order">Matrix row number.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var matrixBCopy = matrixB.Clone();
var matrixX = new UserDefinedMatrix(order, order);
factorLU.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
/// <summary>
/// Can inverse a matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanInverse(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixAInverse = factorLU.Inverse();
// The inverse dimension is equal A
Assert.AreEqual(matrixAInverse.RowCount, matrixAInverse.RowCount);
Assert.AreEqual(matrixAInverse.ColumnCount, matrixAInverse.ColumnCount);
var matrixIdentity = matrixA * matrixAInverse;
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Check if multiplication of A and AI produced identity matrix.
for (var i = 0; i < matrixIdentity.RowCount; i++)
{
Assert.AreEqual(matrixIdentity[i, i], 1.0, 1e-4);
}
}
}
}
| |
/*
* 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 OpenSim.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Connection
{
/// <summary>
/// Object representing the whole of an avatar connection. This object
/// encapsulates the CAPS as well as UDP communication object that makes
/// up an avatar's connection to the simulator
/// </summary>
public class AvatarConnection
{
/// <summary>
/// This is the circuit data we get passed from an initial contact from another
/// simulator or the login service
/// </summary>
private AgentCircuitData _circuitData;
/// <summary>
/// Our control over user caps.
/// </summary>
private ICapsControl _capsControl;
/// <summary>
/// The state of this connection
/// </summary>
private AvatarConnectionState _state;
/// <summary>
/// Why this connection is established
/// </summary>
private EstablishedBy _establishedReason;
/// <summary>
/// Our UDP circuit. May be null if not yet set up
/// </summary>
private IClientAPI _udpCircuit;
/// <summary>
/// Whether or not this connection is currently terminating
/// </summary>
private bool _terminating = false;
/// <summary>
/// Delegate called for connection terminations
/// </summary>
/// <param name="conn">The connection that was terminated</param>
public delegate void ConnectionTerminated(AvatarConnection conn);
/// <summary>
/// Event called when a connection is terminated
/// </summary>
public event ConnectionTerminated OnConnectionTerminated;
/// <summary>
/// This is the circuit data we get passed from an initial contact from another
/// simulator or the login service
/// </summary>
public AgentCircuitData CircuitData
{
get
{
return _circuitData;
}
}
/// <summary>
/// The state of this connection
/// </summary>
public AvatarConnectionState State
{
get
{
return _state;
}
}
/// <summary>
/// The udp cicuit attached to this connection
/// </summary>
public IClientAPI UdpCircuit
{
get
{
return _udpCircuit;
}
}
/// <summary>
/// The SP we're connected with
/// </summary>
public Scenes.ScenePresence ScenePresence { get; set; }
public AvatarConnection(AgentCircuitData circuitData, EstablishedBy reason)
{
_circuitData = circuitData;
_state = AvatarConnectionState.UDPCircuitWait;
_establishedReason = reason;
}
/// <summary>
/// Attempts to attach a UDP circuit to this connection.
/// </summary>
/// <param name="udpCircuit">The circuit to attach</param>
/// <exception cref=""
public void AttachUdpCircuit(IClientAPI udpCircuit)
{
if (_udpCircuit != null)
{
var ex = new AttachUdpCircuitException(String.Format("UDP circuit already exists for {0}. New code: {1}, Existing code: {2}",
_circuitData.AgentID, _udpCircuit.CircuitCode, udpCircuit.CircuitCode));
ex.CircuitAlreadyExisted = true;
if (udpCircuit.CircuitCode == _circuitData.CircuitCode &&
udpCircuit.SessionId == _circuitData.SessionID)
{
ex.ExistingCircuitMatched = true;
}
throw ex;
}
if (udpCircuit.CircuitCode != _circuitData.CircuitCode)
{
throw new AttachUdpCircuitException(String.Format("UDP circuit code doesnt match expected code for {0}. Expected: {1}, Actual {2}",
_circuitData.AgentID, _circuitData.CircuitCode, udpCircuit.CircuitCode));
}
if (udpCircuit.SessionId != _circuitData.SessionID)
{
throw new AttachUdpCircuitException(String.Format("UDP session ID doesnt match expected ID for {0}. Expected: {1}, Actual {2}",
_circuitData.AgentID, _circuitData.SessionID, udpCircuit.SessionId));
}
_udpCircuit = udpCircuit;
_udpCircuit.OnConnectionClosed += _udpCircuit_OnConnectionClosed;
_udpCircuit.OnSetThrottles += _udpCircuit_OnSetThrottles;
_state = AvatarConnectionState.Established;
}
void _udpCircuit_OnSetThrottles(int bwMax)
{
//fire this off on a secondary thread. it is not order critical and if
//aperture is hung this can hang
Util.FireAndForget((obj) => { this.SetRootBandwidth(bwMax); });
}
void _udpCircuit_OnConnectionClosed(IClientAPI obj)
{
this.Terminate(false);
}
/// <summary>
/// Called by the transit manager when this avatar has entered a new transit stage
/// </summary>
/// <param name="stage"></param>
public async Task TransitStateChange(AvatarTransit.TransitStage stage, IEnumerable<uint> rideOnPrimIds)
{
if (stage == AvatarTransit.TransitStage.SendBegin)
{
var pa = ScenePresence.PhysicsActor;
if (pa != null)
{
pa.Suspend();
}
if (_capsControl != null) _capsControl.PauseTraffic();
await _udpCircuit.PauseUpdatesAndFlush();
}
else if (stage == AvatarTransit.TransitStage.SendCompletedSuccess || stage == AvatarTransit.TransitStage.SendError)
{
if (_capsControl != null) _capsControl.ResumeTraffic();
if (stage == AvatarTransit.TransitStage.SendCompletedSuccess)
_udpCircuit.ResumeUpdates(rideOnPrimIds);
else
_udpCircuit.ResumeUpdates(null); // don't kill object update if not leaving region
if (stage == AvatarTransit.TransitStage.SendError)
{
var pa = ScenePresence.PhysicsActor;
if (pa != null)
{
pa.Resume(false, null);
}
}
}
}
/// <summary>
/// Assigns a caps control to this connection
/// </summary>
/// <param name="capsControl"></param>
internal void SetCapsControl(ICapsControl capsControl)
{
_capsControl = capsControl;
}
/// <summary>
/// Terminates this user connection. Terminates UDP and tears down caps handlers and waits for the
/// teardown to complete
/// </summary>
public void Terminate(bool waitForClose)
{
if (!_terminating)
{
_terminating = true;
if (_udpCircuit != null) _udpCircuit.Close();
if (_capsControl != null) _capsControl.Teardown();
if (_udpCircuit != null && waitForClose)
{
_udpCircuit.WaitForClose();
}
var terminatedHandler = OnConnectionTerminated;
if (terminatedHandler != null)
{
terminatedHandler(this);
}
}
else
{
if (_udpCircuit != null && waitForClose)
{
_udpCircuit.WaitForClose();
}
}
}
/// <summary>
/// Sets the bandwidth available. We will assign this number to our caps
/// </summary>
/// <param name="bytesPerSecond"></param>
internal void SetRootBandwidth(int bytesPerSecond)
{
if (_capsControl != null) _capsControl.SetMaxBandwidth(bytesPerSecond);
}
}
}
| |
#region license
// Sqloogle
// Copyright 2013-2017 Dale Newman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Text;
using Sqloogle.Libs.DBDiff.Schema.Model;
namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model
{
public class Index : SQLServerSchemaBase
{
public enum IndexTypeEnum
{
Heap = 0,
Clustered = 1,
Nonclustered = 2,
XML = 3,
GEO = 4
}
public Index(ISchemaBase parent)
: base(parent, Enums.ObjectType.Index)
{
FilterDefintion = "";
Columns = new IndexColumns(parent);
}
public override ISchemaBase Clone(ISchemaBase parent)
{
Index index = new Index(parent)
{
AllowPageLocks = this.AllowPageLocks,
AllowRowLocks = this.AllowRowLocks,
Columns = this.Columns.Clone(),
FillFactor = this.FillFactor,
FileGroup = this.FileGroup,
Id = this.Id,
IgnoreDupKey = this.IgnoreDupKey,
IsAutoStatistics = this.IsAutoStatistics,
IsDisabled = this.IsDisabled,
IsPadded = this.IsPadded,
IsPrimaryKey = this.IsPrimaryKey,
IsUniqueKey = this.IsUniqueKey,
Name = this.Name,
SortInTempDb = this.SortInTempDb,
Status = this.Status,
Type = this.Type,
Owner = this.Owner,
FilterDefintion = this.FilterDefintion
};
ExtendedProperties.ForEach(item => index.ExtendedProperties.Add(item));
return index;
}
public string FileGroup { get; set; }
public Boolean SortInTempDb { get; set; }
public string FilterDefintion { get; set; }
public IndexColumns Columns { get; set; }
public Boolean IsAutoStatistics { get; set; }
public Boolean IsUniqueKey { get; set; }
public Boolean IsPrimaryKey { get; set; }
public IndexTypeEnum Type { get; set; }
public short FillFactor { get; set; }
public Boolean IsDisabled { get; set; }
public Boolean IsPadded { get; set; }
public Boolean IgnoreDupKey { get; set; }
public Boolean AllowPageLocks { get; set; }
public Boolean AllowRowLocks { get; set; }
public override string FullName
{
get
{
return Parent.FullName + ".[" + Name + "]";
}
}
/// <summary>
/// Compara dos indices y devuelve true si son iguales, caso contrario, devuelve false.
/// </summary>
public static Boolean Compare(Index origen, Index destino)
{
if (destino == null) throw new ArgumentNullException("destino");
if (origen == null) throw new ArgumentNullException("origen");
if (origen.AllowPageLocks != destino.AllowPageLocks) return false;
if (origen.AllowRowLocks != destino.AllowRowLocks) return false;
if (origen.FillFactor != destino.FillFactor) return false;
if (origen.IgnoreDupKey != destino.IgnoreDupKey) return false;
if (origen.IsAutoStatistics != destino.IsAutoStatistics) return false;
if (origen.IsDisabled != destino.IsDisabled) return false;
if (origen.IsPadded != destino.IsPadded) return false;
if (origen.IsPrimaryKey != destino.IsPrimaryKey) return false;
if (origen.IsUniqueKey != destino.IsUniqueKey) return false;
if (origen.Type != destino.Type) return false;
if (origen.SortInTempDb != destino.SortInTempDb) return false;
if (!origen.FilterDefintion.Equals(destino.FilterDefintion)) return false;
if (!IndexColumns.Compare(origen.Columns, destino.Columns)) return false;
return CompareFileGroup(origen,destino);
}
public static Boolean CompareExceptIsDisabled(Index origen, Index destino)
{
if (destino == null) throw new ArgumentNullException("destino");
if (origen == null) throw new ArgumentNullException("origen");
if (origen.AllowPageLocks != destino.AllowPageLocks) return false;
if (origen.AllowRowLocks != destino.AllowRowLocks) return false;
if (origen.FillFactor != destino.FillFactor) return false;
if (origen.IgnoreDupKey != destino.IgnoreDupKey) return false;
if (origen.IsAutoStatistics != destino.IsAutoStatistics) return false;
if (origen.IsPadded != destino.IsPadded) return false;
if (origen.IsPrimaryKey != destino.IsPrimaryKey) return false;
if (origen.IsUniqueKey != destino.IsUniqueKey) return false;
if (origen.Type != destino.Type) return false;
if (origen.SortInTempDb != destino.SortInTempDb) return false;
if (!origen.FilterDefintion.Equals(destino.FilterDefintion)) return false;
if (!IndexColumns.Compare(origen.Columns, destino.Columns)) return false;
//return true;
return CompareFileGroup(origen, destino);
}
private static Boolean CompareFileGroup(Index origen, Index destino)
{
if (destino == null) throw new ArgumentNullException("destino");
if (origen == null) throw new ArgumentNullException("origen");
if (origen.FileGroup != null)
{
if (!origen.FileGroup.Equals(destino.FileGroup)) return false;
}
return true;
}
public override string ToSql()
{
Database database = null;
ISchemaBase current = this;
while (database == null && current.Parent != null )
{
database = current.Parent as Database;
current = current.Parent;
}
var isAzure10 = database.Info.Version == DatabaseInfo.VersionTypeEnum.SQLServerAzure10;
var sql = new StringBuilder();
string includes = "";
if ((Type == IndexTypeEnum.Clustered) && (IsUniqueKey)) sql.Append("CREATE UNIQUE CLUSTERED ");
if ((Type == IndexTypeEnum.Clustered) && (!IsUniqueKey)) sql.Append("CREATE CLUSTERED ");
if ((Type == IndexTypeEnum.Nonclustered) && (IsUniqueKey)) sql.Append("CREATE UNIQUE NONCLUSTERED ");
if ((Type == IndexTypeEnum.Nonclustered) && (!IsUniqueKey)) sql.Append("CREATE NONCLUSTERED ");
if (Type == IndexTypeEnum.XML) sql.Append("CREATE PRIMARY XML ");
sql.Append("INDEX [" + Name + "] ON " + Parent.FullName + "\r\n(\r\n");
/*Ordena la coleccion de campos del Indice en funcion de la propieda IsIncluded*/
Columns.Sort();
for (int j = 0; j < Columns.Count; j++)
{
if (!Columns[j].IsIncluded)
{
sql.Append("\t[" + Columns[j].Name + "]");
if (Type != IndexTypeEnum.XML)
{
if (Columns[j].Order) sql.Append(" DESC"); else sql.Append(" ASC");
}
if (j < Columns.Count - 1) sql.Append(",");
sql.Append("\r\n");
}
else
{
if (String.IsNullOrEmpty(includes)) includes = ") INCLUDE (";
includes += "[" + Columns[j].Name + "],";
}
}
if (!String.IsNullOrEmpty(includes)) includes = includes.Substring(0, includes.Length - 1);
sql.Append(includes);
sql.Append(")");
if (!String.IsNullOrEmpty(FilterDefintion)) sql.Append("\r\n WHERE " + FilterDefintion + "\r\n");
sql.Append(" WITH (");
if (Parent.ObjectType == Enums.ObjectType.TableType)
{
if ((IgnoreDupKey) && (IsUniqueKey)) sql.Append("IGNORE_DUP_KEY = ON "); else sql.Append("IGNORE_DUP_KEY = OFF ");
}
else
{
if (!isAzure10){
if (IsPadded) sql.Append("PAD_INDEX = ON, "); else sql.Append("PAD_INDEX = OFF, ");}
if (IsAutoStatistics) sql.Append("STATISTICS_NORECOMPUTE = ON"); else sql.Append("STATISTICS_NORECOMPUTE = OFF");
if (Type != IndexTypeEnum.XML)
if ((IgnoreDupKey) && (IsUniqueKey)) sql.Append("IGNORE_DUP_KEY = ON, "); else sql.Append(", IGNORE_DUP_KEY = OFF");
if (!isAzure10)
{
if (AllowRowLocks) sql.Append(", ALLOW_ROW_LOCKS = ON"); else sql.Append(", ALLOW_ROW_LOCKS = OFF");
if (AllowPageLocks) sql.Append(", ALLOW_PAGE_LOCKS = ON"); else sql.Append(", ALLOW_PAGE_LOCKS = OFF");
if (FillFactor != 0) sql.Append(", FILLFACTOR = " + FillFactor.ToString());
}
}
sql.Append(")");
if (!isAzure10)
{
if (!String.IsNullOrEmpty(FileGroup)) sql.Append(" ON [" + FileGroup + "]");
}
sql.Append("\r\nGO\r\n");
if (IsDisabled)
sql.Append("ALTER INDEX [" + Name + "] ON " + ((Table)Parent).FullName + " DISABLE\r\nGO\r\n");
sql.Append(ExtendedProperties.ToSql());
return sql.ToString();
}
public override string ToSqlAdd()
{
return ToSql();
}
public override string ToSqlDrop()
{
return ToSqlDrop(null);
}
private string ToSqlDrop(string FileGroupName)
{
string sql = "DROP INDEX [" + Name + "] ON " + Parent.FullName;
if (!String.IsNullOrEmpty(FileGroupName)) sql += " WITH (MOVE TO [" + FileGroupName + "])";
sql += "\r\nGO\r\n";
return sql;
}
public override SQLScript Create()
{
Enums.ScripActionType action = Enums.ScripActionType.AddIndex;
if (!GetWasInsertInDiffList(action))
{
SetWasInsertInDiffList(action);
return new SQLScript(ToSqlAdd(), Parent.DependenciesCount, action);
}
return null;
}
public override SQLScript Drop()
{
Enums.ScripActionType action = Enums.ScripActionType.DropIndex;
if (!GetWasInsertInDiffList(action))
{
SetWasInsertInDiffList(action);
return new SQLScript(ToSqlDrop(), Parent.DependenciesCount, action);
}
return null;
}
private string ToSqlEnabled()
{
if (IsDisabled)
return "ALTER INDEX [" + Name + "] ON " + Parent.FullName + " DISABLE\r\nGO\r\n";
return "ALTER INDEX [" + Name + "] ON " + Parent.FullName + " REBUILD\r\nGO\r\n";
}
public override SQLScriptList ToSqlDiff()
{
SQLScriptList list = new SQLScriptList();
if (Status != Enums.ObjectStatusType.OriginalStatus)
RootParent.ActionMessage[Parent.FullName].Add(this);
if (HasState(Enums.ObjectStatusType.DropStatus))
list.Add(Drop());
if (HasState(Enums.ObjectStatusType.CreateStatus))
list.Add(Create());
if (HasState(Enums.ObjectStatusType.AlterStatus))
{
list.Add(Drop());
list.Add(Create());
}
if (Status == Enums.ObjectStatusType.DisabledStatus)
{
list.Add(ToSqlEnabled(), Parent.DependenciesCount, Enums.ScripActionType.AlterIndex);
}
/*if (this.Status == StatusEnum.ObjectStatusType.ChangeFileGroup)
{
listDiff.Add(this.ToSQLDrop(this.FileGroup), ((Table)Parent).DependenciesCount, StatusEnum.ScripActionType.DropIndex);
listDiff.Add(this.ToSQLAdd(), ((Table)Parent).DependenciesCount, StatusEnum.ScripActionType.AddIndex);
}*/
list.AddRange(ExtendedProperties.ToSqlDiff());
return list;
}
}
}
| |
// file: Supervised\NeuralNetwork\Network.cs
//
// summary: Implements the network class
using System;
using System.Linq;
using System.Collections.Generic;
using numl.Data;
using numl.Math.LinearAlgebra;
using numl.Math.Functions;
using numl.Model;
using numl.Math.Functions.Loss;
using numl.Supervised.NeuralNetwork.Optimization;
namespace numl.Supervised.NeuralNetwork
{
/// <summary>A network.</summary>
public partial class Network : Data.Graph
{
/// <summary>Gets or sets the in.</summary>
/// <value>The in.</value>
public Neuron[] In { get; set; }
/// <summary>Gets or sets the out.</summary>
/// <value>The out.</value>
public Neuron[] Out { get; set; }
/// <summary>
/// Gets or sets the output function (optional).
/// </summary>
public IFunction OutputFunction { get; set; }
/// <summary>
/// Gets or sets the network loss function.
/// </summary>
public ILossFunction LossFunction { get; set; } = new L2Loss();
/// <summary>
/// Gets or sets the current loss of the network.
/// </summary>
public double Cost { get; set; } = 0d;
/// <summary>
/// Returns the number of layers in the network.
/// </summary>
public int Layers
{
get
{
return this.GetVertices().OfType<Neuron>()
.Select(s => s.LayerId).Distinct().Count();
}
}
/// <summary>
/// Returns a new Network instance.
/// </summary>
public static Network New()
{
return new Network();
}
/// <summary>Gets a label.</summary>
/// <param name="n">The Node to process.</param>
/// <param name="d">The Descriptor to process.</param>
/// <returns>The label.</returns>
internal static string GetLabel(int n, Descriptor d)
{
var label = "";
try { label = Enum.GetName(d.Label.Type, n); }
// TODO: fix cheesy way of getting around IsEnum
catch
{
if (d.Label is StringProperty && ((StringProperty)d.Label).AsEnum)
label = ((StringProperty)d.Label).Dictionary[n];
else label = d.Label.Name;
}
return label;
}
#region Computation
/// <summary>Forwards the given x coordinate.</summary>
/// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception>
/// <param name="x">The Vector to process.</param>
public void Forward(Vector x)
{
if (In.Length != x.Length + 1)
throw new InvalidOperationException("Input nodes not aligned to input vector");
// this should forward the input through the network
// from the input nodes through the layers to the output layer
// set input (with bias inputs)
for (int i = 0; i < In.Length; i++)
In[i].Input = (i == 0 ? 1.0 : x[i - 1]);
// evaluate
for (int i = 0; i < Out.Length; i++)
Out[i].Evaluate();
}
/// <summary>Backpropagates the errors through the network given the supplied label.</summary>
/// <param name="y">Label to process.</param>
/// <param name="properties">Network training properties for use in learning.</param>
/// <param name="networkTrainer">Network training method.</param>
public void Back(double y, NetworkTrainingProperties properties, INetworkTrainer networkTrainer)
{
this.Back(Vector.Create(this.Out.Length, () => y), properties, networkTrainer);
}
/// <summary>Backpropagates the errors through the network given the supplied sequence label.</summary>
/// <param name="y">Output vector to process.</param>
/// <param name="properties">Network training properties for use in learning.</param>
/// <param name="networkTrainer">Network training method.</param>
/// <param name="update">Indicates whether to update the weights after computing the errors.</param>
public void Back(Vector y, NetworkTrainingProperties properties, INetworkTrainer networkTrainer, bool update = true)
{
this.Cost = this.LossFunction.Compute(this.Output(), y);
// CK
// propagate error gradients
for (int i = 0; i < Out.Length; i++)
Out[i].Error(y[i], properties);
if (update)
{
// reset weights
for (int i = 0; i < Out.Length; i++)
Out[i].Update(properties, networkTrainer);
}
}
/// <summary>
/// Returns the predicted output sequence from the Network after forwarding.
/// </summary>
/// <param name="network">Current network.</param>
/// <returns>Vector.</returns>
public Vector Output()
{
Vector output = this.Out.Select(n => n.Output).ToVector();
output = (this.OutputFunction != null ? this.OutputFunction.Compute(output) : output);
return output;
}
/// <summary>
/// Resets the neurons in the entire graph (see <see cref="Neuron.Reset(NetworkTrainingProperties)"/>).
/// </summary>
/// <param name="properties">Network training properties object.</param>
public void ResetStates(NetworkTrainingProperties properties)
{
foreach (var node in this.GetVertices().OfType<Neuron>())
{
node.Reset(properties);
}
}
#endregion
#region Graph
/// <summary>
/// Adds the Neuron to the underlying graph.
/// </summary>
/// <param name="node">Neuron to add.</param>
/// <returns></returns>
public Neuron AddNode(Neuron node)
{
base.AddVertex(node);
return node;
}
/// <summary>
/// Removes the specified node from the network, including any connections.
/// </summary>
/// <param name="node">Neuron to remove from the network.</param>
public void RemoveNode(Neuron node)
{
// remove this node from parent edges
for (int i = 0; i < node.In.Count; i++)
{
Neuron inode = node.In.ElementAt(i).Source;
for (int j = inode.Out.Count - 1; j >= 0; j--)
{
if (inode.Out.ElementAt(j).Target == node)
{
inode.Out.RemoveAt(j);
}
}
}
// remove this node from child edges
for (int j = 0; j < node.Out.Count; j++)
{
Neuron onode = node.Out.ElementAt(j).Target;
for (int i = onode.In.Count - 1; i >= 0; i--)
{
if (onode.In.ElementAt(i).Source == node)
{
onode.In.RemoveAt(i);
}
}
}
node.In?.Clear();
node.Out?.Clear();
base.RemoveVertex(node);
}
/// <summary>
/// Adds the Edge to the underlying graph.
/// </summary>
/// <param name="edge">Edge to add.</param>
/// <returns></returns>
public Edge AddEdge(Edge edge)
{
base.AddEdge(edge);
return edge;
}
#endregion
/// <summary>
/// Returns the Nodes from the specified layer, where 0 is the Input layer.
/// </summary>
/// <param name="layer">The layer index to retrieve Nodes from.</param>
/// <returns></returns>
public IEnumerable<Neuron> GetNodes(int layer)
{
return GetVertices().OfType<Neuron>().Where(n => n.LayerId == layer).ToArray();
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// .Net client wrapper for the REST API for Azure ApiManagement Service
/// </summary>
public static partial class ApisOperationsExtensions
{
/// <summary>
/// Creates new or updates existing specific API of the Api Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='parameters'>
/// Required. Create or update parameters.
/// </param>
/// <param name='etag'>
/// Optional. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateOrUpdate(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, ApiCreateOrUpdateParameters parameters, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).CreateOrUpdateAsync(resourceGroupName, serviceName, aid, parameters, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates new or updates existing specific API of the Api Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='parameters'>
/// Required. Create or update parameters.
/// </param>
/// <param name='etag'>
/// Optional. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateOrUpdateAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, ApiCreateOrUpdateParameters parameters, string etag)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, aid, parameters, etag, CancellationToken.None);
}
/// <summary>
/// Deletes specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).DeleteAsync(resourceGroupName, serviceName, aid, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string etag)
{
return operations.DeleteAsync(resourceGroupName, serviceName, aid, etag, CancellationToken.None);
}
/// <summary>
/// Exports API to one of the supported formats.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='accept'>
/// Required. Type of exporting content. Equivalent to Accept HTTP
/// header.
/// </param>
/// <returns>
/// The response model for the export API output operation.
/// </returns>
public static ApiExportResponse Export(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string accept)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).ExportAsync(resourceGroupName, serviceName, aid, accept);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Exports API to one of the supported formats.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='accept'>
/// Required. Type of exporting content. Equivalent to Accept HTTP
/// header.
/// </param>
/// <returns>
/// The response model for the export API output operation.
/// </returns>
public static Task<ApiExportResponse> ExportAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string accept)
{
return operations.ExportAsync(resourceGroupName, serviceName, aid, accept, CancellationToken.None);
}
/// <summary>
/// Gets specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <returns>
/// Get Api operation response details.
/// </returns>
public static ApiGetResponse Get(this IApisOperations operations, string resourceGroupName, string serviceName, string aid)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).GetAsync(resourceGroupName, serviceName, aid);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <returns>
/// Get Api operation response details.
/// </returns>
public static Task<ApiGetResponse> GetAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid)
{
return operations.GetAsync(resourceGroupName, serviceName, aid, CancellationToken.None);
}
/// <summary>
/// Imports API from one of the supported formats.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='contentType'>
/// Required. Type of importing content.
/// </param>
/// <param name='content'>
/// Required. Importing content.
/// </param>
/// <param name='path'>
/// Optional. Path in case importing document does not support path.
/// </param>
/// <param name='wsdlServiceName'>
/// Optional. Local name of WSDL Service to be imported.
/// </param>
/// <param name='wsdlEndpointName'>
/// Optional. Local name of WSDL Endpoint (port) to be imported.
/// </param>
/// <param name='apiType'>
/// Optional. Type of Api getting imported (Soap/Http).
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Import(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string contentType, Stream content, string path, string wsdlServiceName, string wsdlEndpointName, string apiType)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).ImportAsync(resourceGroupName, serviceName, aid, contentType, content, path, wsdlServiceName, wsdlEndpointName, apiType);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Imports API from one of the supported formats.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='contentType'>
/// Required. Type of importing content.
/// </param>
/// <param name='content'>
/// Required. Importing content.
/// </param>
/// <param name='path'>
/// Optional. Path in case importing document does not support path.
/// </param>
/// <param name='wsdlServiceName'>
/// Optional. Local name of WSDL Service to be imported.
/// </param>
/// <param name='wsdlEndpointName'>
/// Optional. Local name of WSDL Endpoint (port) to be imported.
/// </param>
/// <param name='apiType'>
/// Optional. Type of Api getting imported (Soap/Http).
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> ImportAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string contentType, Stream content, string path, string wsdlServiceName, string wsdlEndpointName, string apiType)
{
return operations.ImportAsync(resourceGroupName, serviceName, aid, contentType, content, path, wsdlServiceName, wsdlEndpointName, apiType, CancellationToken.None);
}
/// <summary>
/// List all APIs of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static ApiListResponse List(this IApisOperations operations, string resourceGroupName, string serviceName, QueryParameters query)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).ListAsync(resourceGroupName, serviceName, query);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all APIs of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static Task<ApiListResponse> ListAsync(this IApisOperations operations, string resourceGroupName, string serviceName, QueryParameters query)
{
return operations.ListAsync(resourceGroupName, serviceName, query, CancellationToken.None);
}
/// <summary>
/// List all APIs of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static ApiListResponse ListNext(this IApisOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all APIs of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static Task<ApiListResponse> ListNextAsync(this IApisOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Patches specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='parameters'>
/// Required. Patch parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Patch(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, PatchParameters parameters, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).PatchAsync(resourceGroupName, serviceName, aid, parameters, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patches specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='parameters'>
/// Required. Patch parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> PatchAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, PatchParameters parameters, string etag)
{
return operations.PatchAsync(resourceGroupName, serviceName, aid, parameters, etag, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedFile.CreateFromFile.
/// </summary>
public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase
{
/// <summary>
/// Tests invalid arguments to the CreateFromFile path parameter.
/// </summary>
[Fact]
public void InvalidArguments_Path()
{
// null is an invalid path
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName()));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile fileStream parameter.
/// </summary>
[Fact]
public void InvalidArguments_FileStream()
{
// null is an invalid stream
AssertExtensions.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mode parameter.
/// </summary>
[Fact]
public void InvalidArguments_Mode()
{
// FileMode out of range
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.Append never allowed
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate));
// FileMode.Truncate can't be used with default capacity, as resulting file will be empty
using (TempFile file = new TempFile(GetTestFilePath()))
{
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate));
}
}
[Fact]
public void InvalidArguments_Mode_Truncate()
{
// FileMode.Truncate never allowed
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile access parameter.
/// </summary>
[Fact]
public void InvalidArguments_Access()
{
// Out of range access values with a path
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42)));
// Write-only access is not allowed on maps (only on views)
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write));
// Test the same things, but with a FileStream instead of a path
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Out of range values with a stream
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true));
// Write-only access is not allowed
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream. The combinations should all be valid.
/// </summary>
[Theory]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, Capacity, mmfAccess);
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // On Windows, permission errors come from CreateFromFile
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, permission errors come from CreateView*
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Unix we don't actually create the OS map until the view is created; this results in the permissions
// error being thrown from CreateView* instead of from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor());
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mapName parameter.
/// </summary>
[Fact]
public void InvalidArguments_MapName()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Empty string is an invalid map name
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Test to verify that map names are left unsupported on Unix.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // Check map names are unsupported on Unix
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void MapNamesNotSupported_Unix(string mapName)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile capacity parameter.
/// </summary>
[Fact]
public void InvalidArguments_Capacity()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read));
// Positive capacity required when creating a map from an empty file
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read));
// With Read, the capacity can't be larger than the backing file's size.
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
// Now with a FileStream...
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// The subsequent tests are only valid we if we start with an empty FileStream, which we should have.
// This also verifies the previous failed tests didn't change the length of the file.
Assert.Equal(0, fs.Length);
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Default (0) capacity with an empty file
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Larger capacity than the underlying file, but read-only such that we can't expand the file
fs.SetLength(4096);
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Capacity can't be less than the file size (for such cases a view can be created with the smaller size)
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
// Capacity can't be less than the file size
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile inheritability parameter.
/// </summary>
[Theory]
[InlineData((HandleInheritability)(-1))]
[InlineData((HandleInheritability)(42))]
public void InvalidArguments_Inheritability(HandleInheritability inheritability)
{
// Out of range values for inheritability
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true));
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.Open, FileMode.OpenOrCreate },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// Test each of the four path-based CreateFromFile overloads
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
// Finally, re-test the last overload, this time with an empty file to start
using (TempFile file = new TempFile(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.CreateNew },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModeCreateNew(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads
// that take a capacity, since the default capacity doesn't work with an empty file.
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access))
{
ValidateMemoryMappedFile(mmf, capacity, access);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Create mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidNameCapacityCombinationsWithPath),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 })]
public void ValidArgumentCombinationsWithPath_ModeCreate(string mapName, long capacity)
{
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity, MemoryMappedFileAccess.ReadWrite))
{
ValidateMemoryMappedFile(mmf, capacity, MemoryMappedFileAccess.ReadWrite);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="modes">The modes to yield.</param>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath(
FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses)
{
foreach (object[] namesCaps in MemberData_ValidNameCapacityCombinationsWithPath(mapNames, capacities))
{
foreach (FileMode mode in modes)
{
foreach (MemoryMappedFileAccess access in accesses)
{
if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) &&
!IsWritable(access))
{
continue;
}
yield return new object[] { mode, namesCaps[0], namesCaps[1], access };
}
}
}
}
public static IEnumerable<object[]> MemberData_ValidNameCapacityCombinationsWithPath(
string[] mapNames, long[] capacities)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity;
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, };
}
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile that accepts a FileStream.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite },
new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable },
new bool[] { false, true })]
public void ValidArgumentCombinationsWithStream(
string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen)
{
// Create a file of the right size, then create the map for it.
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
// Start with an empty file and let the map grow it to the right size. This requires write access.
if (IsWritable(access))
{
using (FileStream fs = File.Create(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
/// <param name="inheritabilities">The inheritabilities to yield.</param>
/// <param name="inheritabilities">The leaveOpen values to yield.</param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream(
string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ?
s_pageSize.Value :
tmpCapacity;
foreach (MemoryMappedFileAccess access in accesses)
{
foreach (HandleInheritability inheritability in inheritabilities)
{
foreach (bool leaveOpen in leaveOpens)
{
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, access, inheritability, leaveOpen };
}
}
}
}
}
}
/// <summary>
/// Test that a map using the default capacity (0) grows to the size of the underlying file.
/// </summary>
[Fact]
public void DefaultCapacityIsFileLength()
{
const int DesiredCapacity = 8192;
const int DefaultCapacity = 0;
// With path
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
// With stream
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode
/// that requires the file to exist.
/// </summary>
[Fact]
public void FileDoesNotExist_OpenFileMode()
{
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath()));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with an existing file and a mode
/// that requires the file to not exist.
/// </summary>
[Fact]
public void FileAlreadyExists()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// FileMode.CreateNew invalid when the file already exists
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName()));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a read-write file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap()
{
// Already opened with another read-write map
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test to validate we can create multiple concurrent read-only maps from the same file path.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_SucceedsWithReadOnly()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
{
Assert.Equal(acc1.Capacity, acc2.Capacity);
}
}
/// <summary>
/// Test the exceptional behavior of *Execute access levels.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Unix model for executable differs from Windows
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute)]
public void FileNotOpenedForExecute(MemoryMappedFileAccess access)
{
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
{
// The FileStream created by the map doesn't have GENERIC_EXECUTE set
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access));
// The FileStream opened explicitly doesn't have GENERIC_EXECUTE set
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true));
}
}
}
/// <summary>
/// On Unix, modifying a file that is ReadOnly will fail under normal permissions.
/// If the test is being run under the superuser, however, modification of a ReadOnly
/// file is allowed.
/// </summary>
private void WriteToReadOnlyFile(MemoryMappedFileAccess access, bool succeeds)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
FileAttributes original = File.GetAttributes(file.Path);
File.SetAttributes(file.Path, FileAttributes.ReadOnly);
try
{
if (succeeds)
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access))
ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read);
else
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access));
}
finally
{
File.SetAttributes(file.Path, original);
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
public void WriteToReadOnlyFile_ReadWrite(MemoryMappedFileAccess access)
{
WriteToReadOnlyFile(access, access == MemoryMappedFileAccess.Read ||
(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0));
}
[Fact]
public void WriteToReadOnlyFile_CopyOnWrite()
{
WriteToReadOnlyFile(MemoryMappedFileAccess.CopyOnWrite, (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0));
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_Basic(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create and close the map
MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose();
// The handle should now be open iff leaveOpen
Assert.NotEqual(leaveOpen, handle.IsClosed);
}
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_OutstandingViews(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create the map, create each of the views, then close the map
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity))
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity))
{
// Explicitly close the map. The handle should now be open iff leaveOpen.
mmf.Dispose();
Assert.NotEqual(leaveOpen, handle.IsClosed);
// But the views should still be usable.
ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite);
ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite);
}
}
}
/// <summary>
/// Test to validate we can create multiple maps from the same FileStream.
/// </summary>
[Fact]
public void MultipleMapsForTheSameFileStream()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor())
{
// The capacity of the two maps should be equal
Assert.Equal(acc1.Capacity, acc2.Capacity);
var rand = new Random();
for (int i = 1; i <= 10; i++)
{
// Write a value to one map, then read it from the other,
// ping-ponging between the two.
int pos = rand.Next((int)acc1.Capacity - 1);
MemoryMappedViewAccessor reader = acc1, writer = acc2;
if (i % 2 == 0)
{
reader = acc2;
writer = acc1;
}
writer.Write(pos, (byte)i);
writer.Flush();
Assert.Equal(i, reader.ReadByte(pos));
}
}
}
/// <summary>
/// Test to verify that the map's size increases the underlying file size if the map's capacity is larger.
/// </summary>
[Fact]
public void FileSizeExpandsToCapacity()
{
const int InitialCapacity = 256;
using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity))
{
// Create a map with a larger capacity, and verify the file has expanded.
MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose();
using (FileStream fs = File.OpenRead(file.Path))
{
Assert.Equal(InitialCapacity * 2, fs.Length);
}
// Do the same thing again but with a FileStream.
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(InitialCapacity * 4, fs.Length);
}
}
}
/// <summary>
/// Test the exceptional behavior when attempting to create a map so large it's not supported.
/// </summary>
[PlatformSpecific(~TestPlatforms.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately)
[Fact]
public void TooLargeCapacity()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew))
{
try
{
long length = long.MaxValue;
MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested.
}
catch (IOException)
{
// Expected exception for too large a capacity
}
}
}
/// <summary>
/// Test to verify map names are handled appropriately, causing a conflict when they're active but
/// reusable in a sequential manner.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Tests reusability of map names on Windows
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void ReusingNames_Windows(string name)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity));
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
namespace OpenSim.Region.CoreModules.SampleMoneyModule
{
/// <summary>
/// This is only the functionality required to make the functionality associated with money work
/// (such as land transfers). There is no money code here! Use FORGE as an example for money code.
/// Demo Economy/Money Module. This is a purposely crippled module!
/// // To land transfer you need to add:
/// -helperuri http://serveraddress:port/
/// to the command line parameters you use to start up your client
/// This commonly looks like -helperuri http://127.0.0.1:9000/
///
/// </summary>
public enum TransactionType : int
{
SystemGenerated = 0,
RegionMoneyRequest = 1,
Gift = 2,
Purchase = 3
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SampleMoneyModule")]
public class SampleMoneyModule : IMoneyModule, ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Where Stipends come from and Fees go to.
/// </summary>
// private UUID EconomyBaseAccount = UUID.Zero;
private float EnergyEfficiency = 0f;
// private ObjectPaid handerOnObjectPaid;
private bool m_enabled = true;
private IConfigSource m_gConfig;
/// <summary>
/// Scenes by Region Handle
/// </summary>
private Dictionary<ulong, Scene> m_scenel = new Dictionary<ulong, Scene>();
private bool m_sellEnabled = false;
/// <summary>
/// Region UUIDS indexed by AgentID
/// </summary>
// private int m_stipend = 1000;
private int ObjectCount = 0;
private int PriceEnergyUnit = 0;
private int PriceGroupCreate = 0;
private int PriceObjectClaim = 0;
private float PriceObjectRent = 0f;
private float PriceObjectScaleFactor = 0f;
private int PriceParcelClaim = 0;
private float PriceParcelClaimFactor = 0f;
private int PriceParcelRent = 0;
private int PricePublicObjectDecay = 0;
private int PricePublicObjectDelete = 0;
private int PriceRentLight = 0;
private int PriceUpload = 0;
private int TeleportMinPrice = 0;
private float TeleportPriceExponent = 0f;
#region IMoneyModule Members
#pragma warning disable 0067
public event ObjectPaid OnObjectPaid;
#pragma warning restore 0067
public int GroupCreationCharge
{
get { return 0; }
}
public string Name
{
get { return "BetaGridLikeMoneyModule"; }
}
public Type ReplaceableInterface
{
get { return typeof(IMoneyModule); }
}
public int UploadCharge
{
get { return 0; }
}
public void AddRegion(Scene scene)
{
if (m_enabled)
{
scene.RegisterModuleInterface<IMoneyModule>(this);
IHttpServer httpServer = MainServer.Instance;
lock (m_scenel)
{
if (m_scenel.Count == 0)
{
// XMLRPCHandler = scene;
// To use the following you need to add:
// -helperuri <ADDRESS TO HERE OR grid MONEY SERVER>
// to the command line parameters you use to start up your client
// This commonly looks like -helperuri http://127.0.0.1:9000/
// Local Server.. enables functionality only.
httpServer.AddXmlRPCHandler("getCurrencyQuote", quote_func);
httpServer.AddXmlRPCHandler("buyCurrency", buy_func);
httpServer.AddXmlRPCHandler("preflightBuyLandPrep", preflightBuyLandPrep_func);
httpServer.AddXmlRPCHandler("buyLandPrep", landBuy_func);
}
if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle))
{
m_scenel[scene.RegionInfo.RegionHandle] = scene;
}
else
{
m_scenel.Add(scene.RegionInfo.RegionHandle, scene);
}
}
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnMoneyTransfer += MoneyTransferAction;
scene.EventManager.OnClientClosed += ClientClosed;
scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
scene.EventManager.OnMakeChildAgent += MakeChildAgent;
scene.EventManager.OnClientClosed += ClientLoggedOut;
scene.EventManager.OnValidateLandBuy += ValidateLandBuy;
scene.EventManager.OnLandBuy += processLandBuy;
}
}
// Please do not refactor these to be just one method
// Existing implementations need the distinction
//
public void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type, string extraData)
{
}
public void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type)
{
}
public void ApplyUploadCharge(UUID agentID, int amount, string text)
{
}
public void Close()
{
}
/// <summary>
/// Called on startup so the module can be configured.
/// </summary>
/// <param name="config">Configuration source.</param>
public void Initialise(IConfigSource config)
{
m_gConfig = config;
IConfig startupConfig = m_gConfig.Configs["Startup"];
IConfig economyConfig = m_gConfig.Configs["Economy"];
ReadConfigAndPopulate(startupConfig, "Startup");
ReadConfigAndPopulate(economyConfig, "Economy");
}
public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, int amount)
{
string description = String.Format("Object {0} pays {1}", resolveObjectName(objectID), resolveAgentName(toID));
bool give_result = doMoneyTransfer(fromID, toID, amount, 2, description);
BalanceUpdate(fromID, toID, give_result, description);
return give_result;
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
#endregion IMoneyModule Members
public bool AmountCovered(UUID agentID, int amount)
{
return true;
}
public XmlRpcResponse buy_func(XmlRpcRequest request, IPEndPoint remoteClient)
{
// Hashtable requestData = (Hashtable) request.Params[0];
// UUID agentId = UUID.Zero;
// int amount = 0;
XmlRpcResponse returnval = new XmlRpcResponse();
Hashtable returnresp = new Hashtable();
returnresp.Add("success", true);
returnval.Value = returnresp;
return returnval;
}
/// <summary>
/// When the client closes the connection we remove their accounting
/// info from memory to free up resources.
/// </summary>
/// <param name="AgentID">UUID of agent</param>
/// <param name="scene">Scene the agent was connected to.</param>
/// <see cref="OpenSim.Region.Framework.Scenes.EventManager.ClientClosed"/>
public void ClientClosed(UUID AgentID, Scene scene)
{
}
/// <summary>
/// Call this when the client disconnects.
/// </summary>
/// <param name="client"></param>
public void ClientClosed(IClientAPI client)
{
ClientClosed(client.AgentId, null);
}
/// <summary>
/// Event called Economy Data Request handler.
/// </summary>
/// <param name="agentId"></param>
public void EconomyDataRequestHandler(IClientAPI user)
{
Scene s = (Scene)user.Scene;
user.SendEconomyData(EnergyEfficiency, s.RegionInfo.ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate,
PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor,
PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload,
TeleportMinPrice, TeleportPriceExponent);
}
public int GetBalance(UUID agentID)
{
return 0;
}
/// <summary>
/// Utility function Gets a Random scene in the instance. For when which scene exactly you're doing something with doesn't matter
/// </summary>
/// <returns></returns>
public Scene GetRandomScene()
{
lock (m_scenel)
{
foreach (Scene rs in m_scenel.Values)
return rs;
}
return null;
}
/// <summary>
/// Utility function to get a Scene by RegionID in a module
/// </summary>
/// <param name="RegionID"></param>
/// <returns></returns>
public Scene GetSceneByUUID(UUID RegionID)
{
lock (m_scenel)
{
foreach (Scene rs in m_scenel.Values)
{
if (rs.RegionInfo.originRegionID == RegionID)
{
return rs;
}
}
}
return null;
}
public XmlRpcResponse landBuy_func(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
// Hashtable requestData = (Hashtable) request.Params[0];
// UUID agentId = UUID.Zero;
// int amount = 0;
retparam.Add("success", true);
ret.Value = retparam;
return ret;
}
public void ObjectBuy(IClientAPI remoteClient, UUID agentID,
UUID sessionID, UUID groupID, UUID categoryID,
uint localID, byte saleType, int salePrice)
{
if (!m_sellEnabled)
{
remoteClient.SendBlueBoxMessage(UUID.Zero, "", "Buying is not implemented in this version");
return;
}
if (salePrice != 0)
{
remoteClient.SendBlueBoxMessage(UUID.Zero, "", "Buying anything for a price other than zero is not implemented");
return;
}
Scene s = LocateSceneClientIn(remoteClient.AgentId);
// Implmenting base sale data checking here so the default OpenSimulator implementation isn't useless
// combined with other implementations. We're actually validating that the client is sending the data
// that it should. In theory, the client should already know what to send here because it'll see it when it
// gets the object data. If the data sent by the client doesn't match the object, the viewer probably has an
// old idea of what the object properties are. Viewer developer Hazim informed us that the base module
// didn't check the client sent data against the object do any. Since the base modules are the
// 'crowning glory' examples of good practice..
// Validate that the object exists in the scene the user is in
SceneObjectPart part = s.GetSceneObjectPart(localID);
if (part == null)
{
remoteClient.SendAgentAlertMessage("Unable to buy now. The object was not found.", false);
return;
}
// Validate that the client sent the price that the object is being sold for
if (part.SalePrice != salePrice)
{
remoteClient.SendAgentAlertMessage("Cannot buy at this price. Buy Failed. If you continue to get this relog.", false);
return;
}
// Validate that the client sent the proper sale type the object has set
if (part.ObjectSaleType != saleType)
{
remoteClient.SendAgentAlertMessage("Cannot buy this way. Buy Failed. If you continue to get this relog.", false);
return;
}
IBuySellModule module = s.RequestModuleInterface<IBuySellModule>();
if (module != null)
module.BuyObject(remoteClient, categoryID, localID, saleType, salePrice);
}
public XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
Hashtable membershiplevels = new Hashtable();
ArrayList levels = new ArrayList();
Hashtable level = new Hashtable();
level.Add("id", "00000000-0000-0000-0000-000000000000");
level.Add("description", "some level");
levels.Add(level);
//membershiplevels.Add("levels",levels);
Hashtable landuse = new Hashtable();
landuse.Add("upgrade", false);
landuse.Add("action", "http://invaliddomaininvalid.com/");
Hashtable currency = new Hashtable();
currency.Add("estimatedCost", 0);
Hashtable membership = new Hashtable();
membershiplevels.Add("upgrade", false);
membershiplevels.Add("action", "http://invaliddomaininvalid.com/");
membershiplevels.Add("levels", membershiplevels);
retparam.Add("success", true);
retparam.Add("currency", currency);
retparam.Add("membership", membership);
retparam.Add("landuse", landuse);
retparam.Add("confirm", "asdfajsdkfjasdkfjalsdfjasdf");
ret.Value = retparam;
return ret;
}
public XmlRpcResponse quote_func(XmlRpcRequest request, IPEndPoint remoteClient)
{
// Hashtable requestData = (Hashtable) request.Params[0];
// UUID agentId = UUID.Zero;
int amount = 0;
Hashtable quoteResponse = new Hashtable();
XmlRpcResponse returnval = new XmlRpcResponse();
Hashtable currencyResponse = new Hashtable();
currencyResponse.Add("estimatedCost", 0);
currencyResponse.Add("currencyBuy", amount);
quoteResponse.Add("success", true);
quoteResponse.Add("currency", currencyResponse);
quoteResponse.Add("confirm", "asdfad9fj39ma9fj");
returnval.Value = quoteResponse;
return returnval;
}
public void requestPayPrice(IClientAPI client, UUID objectID)
{
Scene scene = LocateSceneClientIn(client.AgentId);
if (scene == null)
return;
SceneObjectPart task = scene.GetSceneObjectPart(objectID);
if (task == null)
return;
SceneObjectGroup group = task.ParentGroup;
SceneObjectPart root = group.RootPart;
client.SendPayPrice(objectID, root.PayPrice);
}
/// <summary>
/// Sends the the stored money balance to the client
/// </summary>
/// <param name="client"></param>
/// <param name="agentID"></param>
/// <param name="SessionID"></param>
/// <param name="TransactionID"></param>
public void SendMoneyBalance(IClientAPI client, UUID agentID, UUID SessionID, UUID TransactionID)
{
if (client.AgentId == agentID && client.SessionId == SessionID)
{
int returnfunds = 0;
try
{
returnfunds = GetFundsForAgentID(agentID);
}
catch (Exception e)
{
client.SendAlertMessage(e.Message + " ");
}
client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds, 0, UUID.Zero, false, UUID.Zero, false, 0, String.Empty);
}
else
{
client.SendAlertMessage("Unable to send your money balance to you!");
}
}
// Please do not refactor these to be just one method
// Existing implementations need the distinction
//
public bool UploadCovered(UUID agentID, int amount)
{
return true;
}
/// <summary>
/// XMLRPC handler to send alert message and sound to client
/// </summary>
public XmlRpcResponse UserAlert(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
UUID agentId;
UUID soundId;
UUID regionId;
UUID.TryParse((string)requestData["agentId"], out agentId);
UUID.TryParse((string)requestData["soundId"], out soundId);
UUID.TryParse((string)requestData["regionId"], out regionId);
string text = (string)requestData["text"];
string secret = (string)requestData["secret"];
Scene userScene = GetSceneByUUID(regionId);
if (userScene != null)
{
if (userScene.RegionInfo.regionSecret == secret)
{
IClientAPI client = LocateClientObject(agentId);
if (client != null)
{
if (soundId != UUID.Zero)
client.SendPlayAttachedSound(soundId, UUID.Zero, UUID.Zero, 1.0f, 0);
client.SendBlueBoxMessage(UUID.Zero, "", text);
retparam.Add("success", true);
}
else
{
retparam.Add("success", false);
}
}
else
{
retparam.Add("success", false);
}
}
ret.Value = retparam;
return ret;
}
/// <summary>
/// Event Handler for when an Avatar enters one of the parcels in the simulator.
/// </summary>
/// <param name="avatar"></param>
/// <param name="localLandID"></param>
/// <param name="regionID"></param>
private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
{
//m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString());
}
private void BalanceUpdate(UUID senderID, UUID receiverID, bool transactionresult, string description)
{
IClientAPI sender = LocateClientObject(senderID);
IClientAPI receiver = LocateClientObject(receiverID);
if (senderID != receiverID)
{
if (sender != null)
{
sender.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(description), GetFundsForAgentID(senderID), 0, UUID.Zero, false, UUID.Zero, false, 0, String.Empty);
}
if (receiver != null)
{
receiver.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(description), GetFundsForAgentID(receiverID), 0, UUID.Zero, false, UUID.Zero, false, 0, String.Empty);
}
}
}
/// <summary>
/// Ensures that the agent accounting data is set up in this instance.
/// </summary>
/// <param name="agentID"></param>
private void CheckExistAndRefreshFunds(UUID agentID)
{
}
/// <summary>
/// Event Handler for when the client logs out.
/// </summary>
/// <param name="AgentId"></param>
private void ClientLoggedOut(UUID AgentId, Scene scene)
{
}
/// <summary>
/// Transfer money
/// </summary>
/// <param name="Sender"></param>
/// <param name="Receiver"></param>
/// <param name="amount"></param>
/// <returns></returns>
private bool doMoneyTransfer(UUID Sender, UUID Receiver, int amount, int transactiontype, string description)
{
bool result = true;
return result;
}
private SceneObjectPart findPrim(UUID objectID)
{
lock (m_scenel)
{
foreach (Scene s in m_scenel.Values)
{
SceneObjectPart part = s.GetSceneObjectPart(objectID);
if (part != null)
{
return part;
}
}
}
return null;
}
private void GetClientFunds(IClientAPI client)
{
CheckExistAndRefreshFunds(client.AgentId);
}
/// <summary>
/// Gets the amount of Funds for an agent
/// </summary>
/// <param name="AgentID"></param>
/// <returns></returns>
private int GetFundsForAgentID(UUID AgentID)
{
int returnfunds = 0;
return returnfunds;
}
/// <summary>
/// Locates a IClientAPI for the client specified
/// </summary>
/// <param name="AgentID"></param>
/// <returns></returns>
private IClientAPI LocateClientObject(UUID AgentID)
{
ScenePresence tPresence = null;
IClientAPI rclient = null;
lock (m_scenel)
{
foreach (Scene _scene in m_scenel.Values)
{
tPresence = _scene.GetScenePresence(AgentID);
if (tPresence != null)
{
if (!tPresence.IsChildAgent)
{
rclient = tPresence.ControllingClient;
}
}
if (rclient != null)
{
return rclient;
}
}
}
return null;
}
private Scene LocateSceneClientIn(UUID AgentId)
{
lock (m_scenel)
{
foreach (Scene _scene in m_scenel.Values)
{
ScenePresence tPresence = _scene.GetScenePresence(AgentId);
if (tPresence != null)
{
if (!tPresence.IsChildAgent)
{
return _scene;
}
}
}
}
return null;
}
/// <summary>
/// Event Handler for when a root agent becomes a child agent
/// </summary>
/// <param name="avatar"></param>
private void MakeChildAgent(ScenePresence avatar)
{
}
/// <summary>
/// THis method gets called when someone pays someone else as a gift.
/// </summary>
/// <param name="osender"></param>
/// <param name="e"></param>
private void MoneyTransferAction(Object osender, EventManager.MoneyTransferArgs e)
{
}
/// <summary>
/// New Client Event Handler
/// </summary>
/// <param name="client"></param>
private void OnNewClient(IClientAPI client)
{
GetClientFunds(client);
// Subscribe to Money messages
client.OnEconomyDataRequest += EconomyDataRequestHandler;
client.OnMoneyBalanceRequest += SendMoneyBalance;
client.OnRequestPayPrice += requestPayPrice;
client.OnObjectBuy += ObjectBuy;
client.OnLogout += ClientClosed;
}
private void processLandBuy(Object osender, EventManager.LandBuyArgs e)
{
}
/// <summary>
/// Parse Configuration
/// </summary>
/// <param name="scene"></param>
/// <param name="startupConfig"></param>
/// <param name="config"></param>
private void ReadConfigAndPopulate(IConfig startupConfig, string config)
{
if (config == "Startup" && startupConfig != null)
{
m_enabled = (startupConfig.GetString("economymodule", "BetaGridLikeMoneyModule") == "BetaGridLikeMoneyModule");
}
if (config == "Economy" && startupConfig != null)
{
PriceEnergyUnit = startupConfig.GetInt("PriceEnergyUnit", 100);
PriceObjectClaim = startupConfig.GetInt("PriceObjectClaim", 10);
PricePublicObjectDecay = startupConfig.GetInt("PricePublicObjectDecay", 4);
PricePublicObjectDelete = startupConfig.GetInt("PricePublicObjectDelete", 4);
PriceParcelClaim = startupConfig.GetInt("PriceParcelClaim", 1);
PriceParcelClaimFactor = startupConfig.GetFloat("PriceParcelClaimFactor", 1f);
PriceUpload = startupConfig.GetInt("PriceUpload", 0);
PriceRentLight = startupConfig.GetInt("PriceRentLight", 5);
TeleportMinPrice = startupConfig.GetInt("TeleportMinPrice", 2);
TeleportPriceExponent = startupConfig.GetFloat("TeleportPriceExponent", 2f);
EnergyEfficiency = startupConfig.GetFloat("EnergyEfficiency", 1);
PriceObjectRent = startupConfig.GetFloat("PriceObjectRent", 1);
PriceObjectScaleFactor = startupConfig.GetFloat("PriceObjectScaleFactor", 10);
PriceParcelRent = startupConfig.GetInt("PriceParcelRent", 1);
PriceGroupCreate = startupConfig.GetInt("PriceGroupCreate", -1);
m_sellEnabled = startupConfig.GetBoolean("SellEnabled", false);
}
}
private string resolveAgentName(UUID agentID)
{
// try avatar username surname
Scene scene = GetRandomScene();
UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, agentID);
if (account != null)
{
string avatarname = account.FirstName + " " + account.LastName;
return avatarname;
}
else
{
m_log.ErrorFormat(
"[MONEY]: Could not resolve user {0}",
agentID);
}
return String.Empty;
}
private string resolveObjectName(UUID objectID)
{
SceneObjectPart part = findPrim(objectID);
if (part != null)
{
return part.Name;
}
return String.Empty;
}
# region Standalone box enablers only
#endregion
#region local Fund Management
// private void SetLocalFundsForAgentID(UUID AgentID, int amount)
// {
// }
#endregion
#region Utility Helpers
#endregion
#region event Handlers
private void ValidateLandBuy(Object osender, EventManager.LandBuyArgs e)
{
lock (e)
{
e.economyValidated = true;
}
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Vevo;
using Vevo.DataAccessLib;
using Vevo.DataAccessLib.Cart;
using Vevo.Domain;
using Vevo.Shared.DataAccess;
using Vevo.WebAppLib;
using Vevo.Domain.Configurations;
using Vevo.WebUI;
public partial class AdminAdvanced_MainControls_SiteConfig : AdminAdvancedBaseUserControl
{
private const string _pathUpload = "Images/Configuration/";
protected class ConfigList
{
private string _configName;
private string _displayName;
public string ConfigName { get { return _configName; } set { _configName = value; } }
public string DisplayName { get { return _displayName; } set { _displayName = value; } }
public ConfigList( string configNameParam, string displayNameParam )
{
ConfigName = configNameParam;
DisplayName = displayNameParam;
}
}
private ConfigList[] _layoutConfigList = new ConfigList[]
{
new ConfigList( "Test", "Testtest" ),
new ConfigList( "Test", "Testtest2" ),
new ConfigList( "Test", "Testtest3" )
};
private void PopulateStoreConfig()
{
}
private void PopulateWebServiceConfig()
{
uxWebServiceAdminUserText.Text = DataAccessContext.Configurations.GetValue( "WebServiceAdminUser" );
}
private void PopulateCustomTimeZone()
{
uxUseTimeZoneDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "UseCustomTimeZone" );
uxCustomTimeZoneDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "CustomTimeZone" );
}
private void PopulateControls()
{
uxTaxConfig.PopulateControls();
uxProductImageSizeConfig.PopulateControls();
uxDisplay.PopulateControls();
uxRatingReview.PopulateControls();
uxGiftCertificate.PopulateControls();
uxWholesale.PopulateControls();
uxEmailNotification.PopulateControls();
uxUploadConfig.PopulateControls();
uxSeo.PopulateControls();
uxSystemConfig.PopulateControls();
uxAffiliateConfig.PopulateControls();
uxShippingTracking.PopulateControls();
uxDownloadCount.PopulateControls();
/*-------- Original Code -------------*/
PopulateStoreConfig();
PopulateCustomTimeZone();
PopulateWebServiceConfig();
if (!KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
{
uxAffiliateTab.Visible = false;
uxeBayConfigTab.Visible = false;
uxWebServiceSettingLabel.Visible = false;
uxWebServiceSettingTR.Visible = false;
}
}
private void SetUpUrlCultureID()
{
DataAccessHelper.UrlCultureID = CultureUtilities.UrlCultureID;
}
private void PopulateSymbolDropdown()
{
CurrencyUtilities.BaseCurrencyCode = DataAccessContext.Configurations.GetValue( "BaseWebsiteCurrency" );
uxSymbolDrop.DataSource = DataAccessContext.CurrencyRepository.GetByEnabled( BoolFilter.ShowTrue );
uxSymbolDrop.DataBind();
uxSymbolDrop.SelectedValue = CurrencyUtilities.BaseCurrencyCode;
}
private void PopulateDropdownControl()
{
uxMerchantCountryList.CurrentSelected = DataAccessContext.Configurations.GetValue( "ShippingMerchantCountry" );
PopulateSymbolDropdown();
uxShippingIncludeDiscountDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "ShippingIncludeDiscount" );
}
private void SetDefaultCurrency()
{
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["BaseWebsiteCurrency"],
uxSymbolDrop.SelectedValue );
CurrencyUtilities.BaseCurrencyCode = DataAccessContext.Configurations.GetValue( "BaseWebsiteCurrency" );
Currency currency = DataAccessContext.CurrencyRepository.GetOne( uxSymbolDrop.SelectedValue );
currency.ConversionRate = 1;
DataAccessContext.CurrencyRepository.Save( currency, uxSymbolDrop.SelectedValue );
}
private void RegisterSubmitButton()
{
WebUtilities.TieButton( this.Page, uxSearchText, uxSearchButton );
}
private string FindSearchText()
{
return uxSearchText.Text;
}
protected void Page_Load( object sender, EventArgs e )
{
RegisterSubmitButton();
if (!MainContext.IsPostBack)
PopulateDropdownControl();
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxDeleteConfirmButton.TargetControlID = "uxDeleteFileTempButton";
uxConfirmModalPopup.TargetControlID = "uxDeleteFileTempButton";
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyDeleteFileTempButton";
uxConfirmModalPopup.TargetControlID = "uxDummyDeleteFileTempButton";
}
if (!IsAdminModifiable())
{
uxSiteMaintenancePanel.Visible = false;
}
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (!MainContext.IsPostBack)
{
PopulateControls();
uxSearchText.Text = "";
uxDownloadExpirePeriodText.Text = DataAccessContext.Configurations.GetValue( "DownloadExpirePeriod" );
uxAllowAnonymousCheckoutDropDown.SelectedValue = DataAccessContext.Configurations.GetValue( "AnonymousCheckoutAllowed" );
}
if (!IsAdminModifiable())
{
uxUpdateButton.Visible = false;
}
}
protected void uxUpdateButton_Click( object sender, EventArgs e )
{
try
{
uxTaxConfig.Update();
uxProductImageSizeConfig.Update();
uxDisplay.Update();
uxRatingReview.Update();
uxGiftCertificate.Update();
uxWholesale.Update();
uxEmailNotification.Update();
uxUploadConfig.Update();
uxSeo.Update();
uxSystemConfig.Update();
uxAffiliateConfig.Update();
uxShippingTracking.Update();
uxDownloadCount.Update();
uxeBayConfig.Update();
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["UseCustomTimeZone"],
uxUseTimeZoneDrop.SelectedValue );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CustomTimeZone"],
uxCustomTimeZoneDrop.SelectedValue );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["WebServiceAdminUser"],
uxWebServiceAdminUserText.Text );
AdminUtilities.LoadSystemConfig();
AdminUtilities.ClearCurrencyCache();
uxMessage.DisplayMessage( Resources.SetupMessages.UpdateSuccess );
SiteMapManager.ClearCache();
PopulateControls();
SetUpUrlCultureID();
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["DownloadExpirePeriod"],
uxDownloadExpirePeriodText.Text );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["AnonymousCheckoutAllowed"],
uxAllowAnonymousCheckoutDropDown.SelectedValue );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["ShippingMerchantCountry"],
uxMerchantCountryList.CurrentSelected );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["ShippingIncludeDiscount"],
uxShippingIncludeDiscountDrop.SelectedValue );
SetDefaultCurrency();
SystemConfig.Load();
UpdatePanel headerPanel = (UpdatePanel) WebUtilities.FindControlRecursive( this.Page, "uxHeaderUpdatePanel" );
if (headerPanel != null)
{
Control paymentLink = (Control) WebUtilities.FindControlRecursive( headerPanel, "PaymentLink" );
if (paymentLink != null)
{
paymentLink.Visible = DataAccessContext.Configurations.GetBoolValue( "VevoPayPADSSMode" );
headerPanel.Update();
}
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
protected void uxDeleteFileTempButton_Click( object sender, EventArgs e )
{
string[] files = Directory.GetFiles( Server.MapPath( "../" + SystemConst.OptionFileTempPath ) );
try
{
foreach (string filetmp in files)
File.Delete( filetmp );
uxMessage.DisplayMessage( Resources.SiteConfigMessages.DeleteAllTempFileSuccess );
}
catch
{
uxMessage.DisplayError( Resources.SiteConfigMessages.DeleteAllTempFileError );
}
}
protected void uxDeleteSearchButton_Click( object sender, EventArgs e )
{
try
{
SearchLogAccess.DeleteAll();
uxMessage.DisplayMessage( Resources.SiteConfigMessages.DeleteAllSearchSuccess );
}
catch (Exception ex)
{
uxMessage.DisplayError( Resources.SiteConfigMessages.DeleteAllSearchError + " " + ex.Message );
}
}
protected void uxSearchButton_Click( object sender, EventArgs e )
{
if (FindSearchText() != "")
MainContext.RedirectMainControl( "SearchConfigurationResult.ascx",
String.Format( "Search={0}&Store={1}&RedirectURL={2}", FindSearchText(), "0", MainContext.LastControl ) );
}
}
| |
using System.IO.Compression;
using System.Reactive.Disposables;
using System.Text;
using Microsoft.Extensions.Hosting;
using Miningcore.Blockchain.Bitcoin.Configuration;
using Miningcore.Blockchain.Cryptonote.Configuration;
using Miningcore.Configuration;
using Miningcore.Contracts;
using Miningcore.Extensions;
using Miningcore.Messaging;
using Miningcore.Notifications.Messages;
using Miningcore.Time;
using NLog;
using ZeroMQ;
namespace Miningcore.Mining;
/// <summary>
/// Receives ready made block templates from GBTRelay
/// </summary>
public class BtStreamReceiver : BackgroundService
{
public BtStreamReceiver(
IMasterClock clock,
IMessageBus messageBus,
ClusterConfig clusterConfig)
{
Contract.RequiresNonNull(clock, nameof(clock));
Contract.RequiresNonNull(messageBus, nameof(messageBus));
this.clock = clock;
this.messageBus = messageBus;
this.clusterConfig = clusterConfig;
}
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
private readonly IMasterClock clock;
private readonly IMessageBus messageBus;
private readonly ClusterConfig clusterConfig;
private static ZSocket SetupSubSocket(ZmqPubSubEndpointConfig relay, bool silent = false)
{
var subSocket = new ZSocket(ZSocketType.SUB);
if(!string.IsNullOrEmpty(relay.SharedEncryptionKey))
subSocket.SetupCurveTlsClient(relay.SharedEncryptionKey, logger);
subSocket.Connect(relay.Url);
subSocket.SubscribeAll();
if(!silent)
{
if(subSocket.CurveServerKey != null && subSocket.CurveServerKey.Any(x => x != 0))
logger.Info($"Monitoring Bt-Stream source {relay.Url} using Curve public-key {subSocket.CurveServerKey.ToHexString()}");
else
logger.Info($"Monitoring Bt-Stream source {relay.Url}");
}
return subSocket;
}
private void ProcessMessage(ZMessage msg)
{
// extract frames
var topic = msg[0].ToString(Encoding.UTF8);
var flags = msg[1].ReadUInt32();
var data = msg[2].Read();
var sent = DateTimeOffset.FromUnixTimeMilliseconds(msg[3].ReadInt64()).DateTime;
// TMP FIX
if(flags != 0 && ((flags & 1) == 0))
flags = BitConverter.ToUInt32(BitConverter.GetBytes(flags).ToNewReverseArray());
// compressed
if((flags & 1) == 1)
{
using(var stm = new MemoryStream(data))
{
using(var stmOut = new MemoryStream())
{
using(var ds = new DeflateStream(stm, CompressionMode.Decompress))
{
ds.CopyTo(stmOut);
}
data = stmOut.ToArray();
}
}
}
// convert
var content = Encoding.UTF8.GetString(data);
// publish
messageBus.SendMessage(new BtStreamMessage(topic, content, sent, DateTime.UtcNow));
}
protected override async Task ExecuteAsync(CancellationToken ct)
{
var endpoints = clusterConfig.Pools.Select(x =>
x.Extra.SafeExtensionDataAs<BitcoinPoolConfigExtra>()?.BtStream ??
x.Extra.SafeExtensionDataAs<CryptonotePoolConfigExtra>()?.BtStream)
.Where(x => x != null)
.DistinctBy(x => $"{x.Url}:{x.SharedEncryptionKey}")
.ToArray();
if(!endpoints.Any())
return;
await Task.Run(() =>
{
var timeout = TimeSpan.FromMilliseconds(5000);
var reconnectTimeout = TimeSpan.FromSeconds(300);
var relays = endpoints
.DistinctBy(x => $"{x.Url}:{x.SharedEncryptionKey}")
.ToArray();
logger.Info(() => "Online");
while(!ct.IsCancellationRequested)
{
// track last message received per endpoint
var lastMessageReceived = relays.Select(_ => clock.Now).ToArray();
try
{
// setup sockets
var sockets = relays.Select(x=> SetupSubSocket(x)).ToArray();
using(new CompositeDisposable(sockets))
{
var pollItems = sockets.Select(_ => ZPollItem.CreateReceiver()).ToArray();
while(!ct.IsCancellationRequested)
{
if(sockets.PollIn(pollItems, out var messages, out var error, timeout))
{
for(var i = 0; i < messages.Length; i++)
{
var msg = messages[i];
if(msg != null)
{
lastMessageReceived[i] = clock.Now;
using(msg)
{
ProcessMessage(msg);
}
}
else if(clock.Now - lastMessageReceived[i] > reconnectTimeout)
{
// re-create socket
sockets[i].Dispose();
sockets[i] = SetupSubSocket(relays[i], true);
// reset clock
lastMessageReceived[i] = clock.Now;
logger.Info(() => $"Receive timeout of {reconnectTimeout.TotalSeconds} seconds exceeded. Re-connecting to {relays[i].Url} ...");
}
}
if(error != null)
logger.Error(() => $"{nameof(ShareReceiver)}: {error.Name} [{error.Name}] during receive");
}
else
{
// check for timeouts
for(var i = 0; i < messages.Length; i++)
{
if(clock.Now - lastMessageReceived[i] > reconnectTimeout)
{
// re-create socket
sockets[i].Dispose();
sockets[i] = SetupSubSocket(relays[i], true);
// reset clock
lastMessageReceived[i] = clock.Now;
logger.Info(() => $"Receive timeout of {reconnectTimeout.TotalSeconds} seconds exceeded. Re-connecting to {relays[i].Url} ...");
}
}
}
}
}
}
catch(Exception ex)
{
logger.Error(() => $"{nameof(ShareReceiver)}: {ex}");
if(!ct.IsCancellationRequested)
Thread.Sleep(1000);
}
}
logger.Info(() => "Offline");
}, ct);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Common
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using Apache.Ignite.Core.Binary;
/// <summary>
/// Converts generic and non-generic delegates.
/// </summary>
public static class DelegateConverter
{
/** */
private const string DefaultMethodName = "Invoke";
/** */
private static readonly MethodInfo ReadObjectMethod = typeof (IBinaryRawReader).GetMethod("ReadObject");
/** */
private static readonly MethodInfo ConvertArrayMethod = typeof(DelegateConverter).GetMethod("ConvertArray",
BindingFlags.Static | BindingFlags.NonPublic);
/// <summary>
/// Compiles a function without arguments.
/// </summary>
/// <param name="targetType">Type of the target.</param>
/// <returns>Compiled function that calls specified method on specified target.</returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static Func<object, object> CompileFunc(Type targetType)
{
var method = targetType.GetMethod(DefaultMethodName);
Debug.Assert(method != null, "method != null");
var targetParam = Expression.Parameter(typeof(object));
var targetParamConverted = Expression.Convert(targetParam, targetType);
var callExpr = Expression.Call(targetParamConverted, method);
var convertResultExpr = Expression.Convert(callExpr, typeof(object));
return Expression.Lambda<Func<object, object>>(convertResultExpr, targetParam).Compile();
}
/// <summary>
/// Compiles a function with arbitrary number of arguments.
/// </summary>
/// <typeparam name="T">Resulting delegate type.</typeparam>
/// <param name="targetType">Type of the target.</param>
/// <param name="argTypes">Argument types.</param>
/// <param name="convertToObject">
/// Flags that indicate whether func params and/or return value should be converted from/to object.
/// </param>
/// <param name="methodName">Name of the method.</param>
/// <returns>
/// Compiled function that calls specified method on specified target.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static T CompileFunc<T>(Type targetType, Type[] argTypes, bool[] convertToObject = null,
string methodName = null)
where T : class
{
var method = targetType.GetMethod(methodName ?? DefaultMethodName, argTypes);
return CompileFunc<T>(targetType, method, argTypes, convertToObject);
}
/// <summary>
/// Compiles a function with arbitrary number of arguments.
/// </summary>
/// <typeparam name="T">Resulting delegate type.</typeparam>
/// <param name="method">Method.</param>
/// <param name="targetType">Type of the target.</param>
/// <param name="argTypes">Argument types.</param>
/// <param name="convertToObject">
/// Flags that indicate whether func params and/or return value should be converted from/to object.
/// </param>
/// <returns>
/// Compiled function that calls specified method on specified target.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static T CompileFunc<T>(Type targetType, MethodInfo method, Type[] argTypes,
bool[] convertToObject = null)
where T : class
{
if (argTypes == null)
{
var args = method.GetParameters();
argTypes = new Type[args.Length];
for (int i = 0; i < args.Length; i++)
argTypes[i] = args[i].ParameterType;
}
Debug.Assert(convertToObject == null || (convertToObject.Length == argTypes.Length + 1));
Debug.Assert(method != null);
targetType = method.IsStatic ? null : (targetType ?? method.DeclaringType);
var targetParam = Expression.Parameter(typeof(object));
Expression targetParamConverted = null;
ParameterExpression[] argParams;
int argParamsOffset = 0;
if (targetType != null)
{
targetParamConverted = Expression.Convert(targetParam, targetType);
argParams = new ParameterExpression[argTypes.Length + 1];
argParams[0] = targetParam;
argParamsOffset = 1;
}
else
argParams = new ParameterExpression[argTypes.Length]; // static method
var argParamsConverted = new Expression[argTypes.Length];
for (var i = 0; i < argTypes.Length; i++)
{
if (convertToObject == null || convertToObject[i])
{
var argParam = Expression.Parameter(typeof (object));
argParams[i + argParamsOffset] = argParam;
argParamsConverted[i] = Expression.Convert(argParam, argTypes[i]);
}
else
{
var argParam = Expression.Parameter(argTypes[i]);
argParams[i + argParamsOffset] = argParam;
argParamsConverted[i] = argParam;
}
}
Expression callExpr = Expression.Call(targetParamConverted, method, argParamsConverted);
if (convertToObject == null || convertToObject[argTypes.Length])
callExpr = Expression.Convert(callExpr, typeof(object));
return Expression.Lambda<T>(callExpr, argParams).Compile();
}
/// <summary>
/// Compiles a function with a single object[] argument which maps array items to actual arguments.
/// </summary>
/// <param name="method">Method.</param>
/// <returns>
/// Compiled function that calls specified method.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static Func<object, object[], object> CompileFuncFromArray(MethodInfo method)
{
Debug.Assert(method != null);
Debug.Assert(method.DeclaringType != null);
var targetParam = Expression.Parameter(typeof(object));
var targetParamConverted = Expression.Convert(targetParam, method.DeclaringType);
var arrParam = Expression.Parameter(typeof(object[]));
var methodParams = method.GetParameters();
var argParams = new Expression[methodParams.Length];
for (var i = 0; i < methodParams.Length; i++)
{
var arrElem = Expression.ArrayIndex(arrParam, Expression.Constant(i));
argParams[i] = Convert(arrElem, methodParams[i].ParameterType);
}
Expression callExpr = Expression.Call(targetParamConverted, method, argParams);
if (callExpr.Type == typeof(void))
{
// Convert action to function
var action = Expression.Lambda<Action<object, object[]>>(callExpr, targetParam, arrParam).Compile();
return (obj, args) =>
{
action(obj, args);
return null;
};
}
callExpr = Expression.Convert(callExpr, typeof(object));
return Expression.Lambda<Func<object, object[], object>>(callExpr, targetParam, arrParam).Compile();
}
/// <summary>
/// Compiles a generic ctor with arbitrary number of arguments.
/// </summary>
/// <typeparam name="T">Result func type.</typeparam>
/// <param name="ctor">Constructor info.</param>
/// <param name="argTypes">Argument types.</param>
/// <param name="convertResultToObject">
/// Flag that indicates whether ctor return value should be converted to object.</param>
/// <param name="convertParamsFromObject">
/// Flag that indicates whether ctor args are object and should be converted to concrete type.</param>
/// <returns>
/// Compiled generic constructor.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static T CompileCtor<T>(ConstructorInfo ctor, Type[] argTypes, bool convertResultToObject = true,
bool convertParamsFromObject = true)
{
Debug.Assert(ctor != null);
var args = new ParameterExpression[argTypes.Length];
var argsConverted = new Expression[argTypes.Length];
for (var i = 0; i < argTypes.Length; i++)
{
if (convertParamsFromObject)
{
var arg = Expression.Parameter(typeof(object));
args[i] = arg;
argsConverted[i] = Expression.Convert(arg, argTypes[i]);
}
else
{
argsConverted[i] = args[i] = Expression.Parameter(argTypes[i]);
}
}
Expression ctorExpr = Expression.New(ctor, argsConverted); // ctor takes args of specific types
if (convertResultToObject)
ctorExpr = Expression.Convert(ctorExpr, typeof(object)); // convert ctor result to object
return Expression.Lambda<T>(ctorExpr, args).Compile(); // lambda takes args as objects
}
/// <summary>
/// Compiles a generic ctor with arbitrary number of arguments
/// that takes an uninitialized object as a first arguments.
/// </summary>
/// <typeparam name="T">Result func type.</typeparam>
/// <param name="ctor">Constructor info.</param>
/// <param name="argTypes">Argument types.</param>
/// <returns>
/// Compiled generic constructor.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static T CompileUninitializedObjectCtor<T>(ConstructorInfo ctor, Type[] argTypes)
{
Debug.Assert(ctor != null);
Debug.Assert(ctor.DeclaringType != null);
Debug.Assert(argTypes != null);
argTypes = new[] {typeof(object)}.Concat(argTypes).ToArray();
var helperMethod = new DynamicMethod(string.Empty, typeof(void), argTypes, ctor.Module, true);
var il = helperMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
if (ctor.DeclaringType.IsValueType)
il.Emit(OpCodes.Unbox, ctor.DeclaringType); // modify boxed copy
if (argTypes.Length > 1)
il.Emit(OpCodes.Ldarg_1);
if (argTypes.Length > 2)
il.Emit(OpCodes.Ldarg_2);
if (argTypes.Length > 3)
throw new NotSupportedException("Not supported: too many ctor args.");
il.Emit(OpCodes.Call, ctor);
il.Emit(OpCodes.Ret);
var constructorInvoker = helperMethod.CreateDelegate(typeof(T));
return (T) (object) constructorInvoker;
}
/// <summary>
/// Compiles a generic ctor with arbitrary number of arguments.
/// </summary>
/// <typeparam name="T">Result func type.</typeparam>
/// <param name="type">Type to be created by ctor.</param>
/// <param name="argTypes">Argument types.</param>
/// <param name="convertResultToObject">
/// Flag that indicates whether ctor return value should be converted to object.
/// </param>
/// <returns>
/// Compiled generic constructor.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static T CompileCtor<T>(Type type, Type[] argTypes, bool convertResultToObject = true)
{
var ctor = type.GetConstructor(argTypes);
return CompileCtor<T>(ctor, argTypes, convertResultToObject);
}
/// <summary>
/// Compiles a constructor that reads all arguments from a binary reader.
/// </summary>
/// <typeparam name="T">Result type</typeparam>
/// <param name="ctor">The ctor.</param>
/// <param name="innerCtorFunc">Function to retrieve reading constructor for an argument.
/// Can be null or return null, in this case the argument will be read directly via ReadObject.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static Func<IBinaryRawReader, T> CompileCtor<T>(ConstructorInfo ctor,
Func<Type, ConstructorInfo> innerCtorFunc)
{
Debug.Assert(ctor != null);
var readerParam = Expression.Parameter(typeof (IBinaryRawReader));
var ctorExpr = GetConstructorExpression(ctor, innerCtorFunc, readerParam, typeof(T));
return Expression.Lambda<Func<IBinaryRawReader, T>>(ctorExpr, readerParam).Compile();
}
/// <summary>
/// Gets the constructor expression.
/// </summary>
/// <param name="ctor">The ctor.</param>
/// <param name="innerCtorFunc">The inner ctor function.</param>
/// <param name="readerParam">The reader parameter.</param>
/// <param name="resultType">Type of the result.</param>
/// <returns>
/// Ctor call expression.
/// </returns>
private static Expression GetConstructorExpression(ConstructorInfo ctor,
Func<Type, ConstructorInfo> innerCtorFunc, Expression readerParam, Type resultType)
{
var ctorParams = ctor.GetParameters();
var paramsExpr = new List<Expression>(ctorParams.Length);
foreach (var param in ctorParams)
{
var paramType = param.ParameterType;
var innerCtor = innerCtorFunc != null ? innerCtorFunc(paramType) : null;
if (innerCtor != null)
{
var readExpr = GetConstructorExpression(innerCtor, innerCtorFunc, readerParam, paramType);
paramsExpr.Add(readExpr);
}
else
{
var readMethod = ReadObjectMethod.MakeGenericMethod(paramType);
var readExpr = Expression.Call(readerParam, readMethod);
paramsExpr.Add(readExpr);
}
}
Expression ctorExpr = Expression.New(ctor, paramsExpr);
ctorExpr = Expression.Convert(ctorExpr, resultType);
return ctorExpr;
}
/// <summary>
/// Compiles the field setter.
/// </summary>
/// <param name="field">The field.</param>
/// <returns>Compiled field setter.</returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static Action<object, object> CompileFieldSetter(FieldInfo field)
{
Debug.Assert(field != null);
Debug.Assert(field.DeclaringType != null);
var targetParam = Expression.Parameter(typeof(object));
var valParam = Expression.Parameter(typeof(object));
var valParamConverted = Expression.Convert(valParam, field.FieldType);
var assignExpr = Expression.Call(GetWriteFieldMethod(field), targetParam, valParamConverted);
return Expression.Lambda<Action<object, object>>(assignExpr, targetParam, valParam).Compile();
}
/// <summary>
/// Compiles the property setter.
/// </summary>
/// <param name="prop">The property.</param>
/// <returns>Compiled property setter.</returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static Action<object, object> CompilePropertySetter(PropertyInfo prop)
{
Debug.Assert(prop != null);
Debug.Assert(prop.DeclaringType != null);
var targetParam = Expression.Parameter(typeof(object));
var targetParamConverted = Expression.Convert(targetParam, prop.DeclaringType);
var valParam = Expression.Parameter(typeof(object));
var valParamConverted = Expression.Convert(valParam, prop.PropertyType);
var fld = Expression.Property(targetParamConverted, prop);
var assignExpr = Expression.Assign(fld, valParamConverted);
return Expression.Lambda<Action<object, object>>(assignExpr, targetParam, valParam).Compile();
}
/// <summary>
/// Compiles the property setter.
/// </summary>
/// <param name="prop">The property.</param>
/// <returns>Compiled property setter.</returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static Func<object, object> CompilePropertyGetter(PropertyInfo prop)
{
Debug.Assert(prop != null);
Debug.Assert(prop.DeclaringType != null);
var targetParam = Expression.Parameter(typeof(object));
var targetParamConverted = prop.GetGetMethod().IsStatic
? null
// ReSharper disable once AssignNullToNotNullAttribute (incorrect warning)
: Expression.Convert(targetParam, prop.DeclaringType);
var fld = Expression.Property(targetParamConverted, prop);
var fldConverted = Expression.Convert(fld, typeof (object));
return Expression.Lambda<Func<object, object>>(fldConverted, targetParam).Compile();
}
/// <summary>
/// Compiles the property setter.
/// </summary>
/// <param name="field">The field.</param>
/// <returns>Compiled property setter.</returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static Func<object, object> CompileFieldGetter(FieldInfo field)
{
Debug.Assert(field != null);
Debug.Assert(field.DeclaringType != null);
var targetParam = Expression.Parameter(typeof(object));
var targetParamConverted = field.IsStatic
? null
: Expression.Convert(targetParam, field.DeclaringType);
var fld = Expression.Field(targetParamConverted, field);
var fldConverted = Expression.Convert(fld, typeof (object));
return Expression.Lambda<Func<object, object>>(fldConverted, targetParam).Compile();
}
/// <summary>
/// Gets a method to write a field (including private and readonly).
/// NOTE: Expression Trees can't write readonly fields.
/// </summary>
/// <param name="field">The field.</param>
/// <returns>Resulting MethodInfo.</returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static DynamicMethod GetWriteFieldMethod(FieldInfo field)
{
Debug.Assert(field != null);
var declaringType = field.DeclaringType;
Debug.Assert(declaringType != null);
var method = new DynamicMethod(string.Empty, null, new[] { typeof(object), field.FieldType },
declaringType, true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
if (declaringType.IsValueType)
il.Emit(OpCodes.Unbox, declaringType); // modify boxed copy
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, field);
il.Emit(OpCodes.Ret);
return method;
}
/// <summary>
/// Gets the constructor with exactly matching signature.
/// <para />
/// Type.GetConstructor matches compatible ones (i.e. taking object instead of concrete type).
/// </summary>
/// <param name="type">The type.</param>
/// <param name="types">The argument types.</param>
/// <returns>Constructor info.</returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public static ConstructorInfo GetConstructorExact(Type type, Type[] types)
{
Debug.Assert(type != null);
Debug.Assert(types != null);
foreach (var constructorInfo in type.GetConstructors(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
var ctorTypes = constructorInfo.GetParameters().Select(x => x.ParameterType);
if (ctorTypes.SequenceEqual(types))
return constructorInfo;
}
return null;
}
/// <summary>
/// Converts expression to a given type.
/// </summary>
private static Expression Convert(Expression value, Type targetType)
{
if (targetType.IsArray && targetType.GetElementType() != typeof(object))
{
var convertMethod = ConvertArrayMethod.MakeGenericMethod(targetType.GetElementType());
var objArray = Expression.Convert(value, typeof(object[]));
return Expression.Call(null, convertMethod, objArray);
}
return Expression.Convert(value, targetType);
}
/// <summary>
/// Converts object array to typed array.
/// </summary>
// ReSharper disable once UnusedMember.Local (used by reflection).
private static T[] ConvertArray<T>(object[] arr)
{
if (arr == null)
{
return null;
}
var res = new T[arr.Length];
Array.Copy(arr, res, arr.Length);
return res;
}
}
}
| |
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;
//UPGRADE_WARNING: The entire project must be compiled once before a form with an ActiveX Control Array can be displayed
using System.ComponentModel;
namespace _4PosBackOffice.NET
{
[ProvideProperty("Index", typeof(AxMSComCtl2.AxDTPicker))]
public class AxDTPickerArray : Microsoft.VisualBasic.Compatibility.VB6.BaseOcxArray, IExtenderProvider
{
public AxDTPickerArray() : base()
{
}
public AxDTPickerArray(IContainer Container) : base(Container)
{
}
public new event CallbackKeyDownEventHandler CallbackKeyDown;
public new delegate void CallbackKeyDownEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_CallbackKeyDown e);
public new event ChangeEventHandler Change;
public new delegate void ChangeEventHandler(System.Object sender, System.EventArgs e);
public new event CloseUpEventHandler CloseUp;
public new delegate void CloseUpEventHandler(System.Object sender, System.EventArgs e);
public new event DropDownEventHandler DropDown;
public new delegate void DropDownEventHandler(System.Object sender, System.EventArgs e);
public new event FormatEventEventHandler FormatEvent;
public new delegate void FormatEventEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_FormatEvent e);
public new event FormatSizeEventHandler FormatSize;
public new delegate void FormatSizeEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_FormatSizeEvent e);
public new event ClickEventEventHandler ClickEvent;
public new delegate void ClickEventEventHandler(System.Object sender, System.EventArgs e);
public new event DblClickEventHandler DblClick;
public new delegate void DblClickEventHandler(System.Object sender, System.EventArgs e);
public new event KeyDownEventHandler KeyDown;
public new delegate void KeyDownEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_KeyDown e);
public new event KeyUpEventEventHandler KeyUpEvent;
public new delegate void KeyUpEventEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_KeyUpEvent e);
public new event KeyPressEventHandler KeyPress;
public new delegate void KeyPressEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_KeyPress e);
public new event MouseDownEventHandler MouseDown;
public new delegate void MouseDownEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_MouseDown e);
public new event MouseMoveEventEventHandler MouseMoveEvent;
public new delegate void MouseMoveEventEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_MouseMoveEvent e);
public new event MouseUpEventEventHandler MouseUpEvent;
public new delegate void MouseUpEventEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_MouseUpEvent e);
public new event OLEStartDragEventHandler OLEStartDrag;
public new delegate void OLEStartDragEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLEStartDragEvent e);
public new event OLEGiveFeedbackEventHandler OLEGiveFeedback;
public new delegate void OLEGiveFeedbackEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLEGiveFeedbackEvent e);
public new event OLESetDataEventHandler OLESetData;
public new delegate void OLESetDataEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLESetDataEvent e);
public new event OLECompleteDragEventHandler OLECompleteDrag;
public new delegate void OLECompleteDragEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLECompleteDragEvent e);
public new event OLEDragOverEventHandler OLEDragOver;
public new delegate void OLEDragOverEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLEDragOverEvent e);
public new event OLEDragDropEventHandler OLEDragDrop;
public new delegate void OLEDragDropEventHandler(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLEDragDropEvent e);
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public bool CanExtend(object target)
{
if (target is AxMSComCtl2.AxDTPicker) {
return BaseCanExtend(target);
}
}
public short GetIndex(AxMSComCtl2.AxDTPicker o)
{
return BaseGetIndex(o);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void SetIndex(AxMSComCtl2.AxDTPicker o, short Index)
{
BaseSetIndex(o, Index);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public bool ShouldSerializeIndex(AxMSComCtl2.AxDTPicker o)
{
return BaseShouldSerializeIndex(o);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void ResetIndex(AxMSComCtl2.AxDTPicker o)
{
BaseResetIndex(o);
}
public AxMSComCtl2.AxDTPicker this[short Index] {
get { return (AxMSComCtl2.AxDTPicker)BaseGetItem(Index); }
}
protected override System.Type GetControlInstanceType()
{
return typeof(AxMSComCtl2.AxDTPicker);
}
protected override void HookUpControlEvents(object o)
{
AxMSComCtl2.AxDTPicker ctl = (AxMSComCtl2.AxDTPicker)o;
base.HookUpControlEvents(o);
if ((CallbackKeyDown != null)) {
ctl.CallbackKeyDown += new AxMSComCtl2.DDTPickerEvents_CallbackKeyDownHandler(HandleCallbackKeyDown);
}
if ((ChangeEvent != null)) {
ctl.Change += new System.EventHandler(HandleChange);
}
if ((CloseUpEvent != null)) {
ctl.CloseUp += new System.EventHandler(HandleCloseUp);
}
if ((DropDownEvent != null)) {
ctl.DropDown += new System.EventHandler(HandleDropDown);
}
if ((FormatEventEvent != null)) {
ctl.FormatEvent += new AxMSComCtl2.DDTPickerEvents_FormatEventHandler(HandleFormatEvent);
}
if ((FormatSizeEvent != null)) {
ctl.FormatSize += new AxMSComCtl2.DDTPickerEvents_FormatSizeEventHandler(HandleFormatSize);
}
if ((ClickEventEvent != null)) {
ctl.ClickEvent += new System.EventHandler(HandleClickEvent);
}
if ((DblClickEvent != null)) {
ctl.DblClick += new System.EventHandler(HandleDblClick);
}
if ((KeyDownEvent != null)) {
ctl.KeyDown += new AxMSComCtl2.DDTPickerEvents_KeyDownHandler(HandleKeyDown);
}
if ((KeyUpEventEvent != null)) {
ctl.KeyUpEvent += new AxMSComCtl2.DDTPickerEvents_KeyUpEventHandler(HandleKeyUpEvent);
}
if ((KeyPressEvent != null)) {
ctl.KeyPress += new AxMSComCtl2.DDTPickerEvents_KeyPressHandler(HandleKeyPress);
}
if ((MouseDownEvent != null)) {
ctl.MouseDown += new AxMSComCtl2.DDTPickerEvents_MouseDownHandler(HandleMouseDown);
}
if ((MouseMoveEventEvent != null)) {
ctl.MouseMoveEvent += new AxMSComCtl2.DDTPickerEvents_MouseMoveEventHandler(HandleMouseMoveEvent);
}
if ((MouseUpEventEvent != null)) {
ctl.MouseUpEvent += new AxMSComCtl2.DDTPickerEvents_MouseUpEventHandler(HandleMouseUpEvent);
}
if ((OLEStartDragEvent != null)) {
ctl.OLEStartDrag += new AxMSComCtl2.DDTPickerEvents_OLEStartDragEventHandler(HandleOLEStartDrag);
}
if ((OLEGiveFeedbackEvent != null)) {
ctl.OLEGiveFeedback += new AxMSComCtl2.DDTPickerEvents_OLEGiveFeedbackEventHandler(HandleOLEGiveFeedback);
}
if ((OLESetDataEvent != null)) {
ctl.OLESetData += new AxMSComCtl2.DDTPickerEvents_OLESetDataEventHandler(HandleOLESetData);
}
if ((OLECompleteDragEvent != null)) {
ctl.OLECompleteDrag += new AxMSComCtl2.DDTPickerEvents_OLECompleteDragEventHandler(HandleOLECompleteDrag);
}
if ((OLEDragOverEvent != null)) {
ctl.OLEDragOver += new AxMSComCtl2.DDTPickerEvents_OLEDragOverEventHandler(HandleOLEDragOver);
}
if ((OLEDragDropEvent != null)) {
ctl.OLEDragDrop += new AxMSComCtl2.DDTPickerEvents_OLEDragDropEventHandler(HandleOLEDragDrop);
}
}
private void HandleCallbackKeyDown(System.Object sender, AxMSComCtl2.DDTPickerEvents_CallbackKeyDown e)
{
if (CallbackKeyDown != null) {
CallbackKeyDown(sender, e);
}
}
private void HandleChange(System.Object sender, System.EventArgs e)
{
if (Change != null) {
Change(sender, e);
}
}
private void HandleCloseUp(System.Object sender, System.EventArgs e)
{
if (CloseUp != null) {
CloseUp(sender, e);
}
}
private void HandleDropDown(System.Object sender, System.EventArgs e)
{
if (DropDown != null) {
DropDown(sender, e);
}
}
private void HandleFormatEvent(System.Object sender, AxMSComCtl2.DDTPickerEvents_FormatEvent e)
{
if (FormatEvent != null) {
FormatEvent(sender, e);
}
}
private void HandleFormatSize(System.Object sender, AxMSComCtl2.DDTPickerEvents_FormatSizeEvent e)
{
if (FormatSize != null) {
FormatSize(sender, e);
}
}
private void HandleClickEvent(System.Object sender, System.EventArgs e)
{
if (ClickEvent != null) {
ClickEvent(sender, e);
}
}
private void HandleDblClick(System.Object sender, System.EventArgs e)
{
if (DblClick != null) {
DblClick(sender, e);
}
}
private void HandleKeyDown(System.Object sender, AxMSComCtl2.DDTPickerEvents_KeyDown e)
{
if (KeyDown != null) {
KeyDown(sender, e);
}
}
private void HandleKeyUpEvent(System.Object sender, AxMSComCtl2.DDTPickerEvents_KeyUpEvent e)
{
if (KeyUpEvent != null) {
KeyUpEvent(sender, e);
}
}
private void HandleKeyPress(System.Object sender, AxMSComCtl2.DDTPickerEvents_KeyPress e)
{
if (KeyPress != null) {
KeyPress(sender, e);
}
}
private void HandleMouseDown(System.Object sender, AxMSComCtl2.DDTPickerEvents_MouseDown e)
{
if (MouseDown != null) {
MouseDown(sender, e);
}
}
private void HandleMouseMoveEvent(System.Object sender, AxMSComCtl2.DDTPickerEvents_MouseMoveEvent e)
{
if (MouseMoveEvent != null) {
MouseMoveEvent(sender, e);
}
}
private void HandleMouseUpEvent(System.Object sender, AxMSComCtl2.DDTPickerEvents_MouseUpEvent e)
{
if (MouseUpEvent != null) {
MouseUpEvent(sender, e);
}
}
private void HandleOLEStartDrag(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLEStartDragEvent e)
{
if (OLEStartDrag != null) {
OLEStartDrag(sender, e);
}
}
private void HandleOLEGiveFeedback(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLEGiveFeedbackEvent e)
{
if (OLEGiveFeedback != null) {
OLEGiveFeedback(sender, e);
}
}
private void HandleOLESetData(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLESetDataEvent e)
{
if (OLESetData != null) {
OLESetData(sender, e);
}
}
private void HandleOLECompleteDrag(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLECompleteDragEvent e)
{
if (OLECompleteDrag != null) {
OLECompleteDrag(sender, e);
}
}
private void HandleOLEDragOver(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLEDragOverEvent e)
{
if (OLEDragOver != null) {
OLEDragOver(sender, e);
}
}
private void HandleOLEDragDrop(System.Object sender, AxMSComCtl2.DDTPickerEvents_OLEDragDropEvent e)
{
if (OLEDragDrop != null) {
OLEDragDrop(sender, e);
}
}
}
}
| |
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 frmCashTransaction
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmCashTransaction() : base()
{
FormClosed += frmCashTransaction_FormClosed;
KeyPress += frmCashTransaction_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_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_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;
}
}
}
public System.Windows.Forms.Panel picButtons;
private System.Windows.Forms.Button withEventsField_cmdDelete;
public System.Windows.Forms.Button cmdDelete {
get { return withEventsField_cmdDelete; }
set {
if (withEventsField_cmdDelete != null) {
withEventsField_cmdDelete.Click -= cmdDelete_Click;
}
withEventsField_cmdDelete = value;
if (withEventsField_cmdDelete != null) {
withEventsField_cmdDelete.Click += cmdDelete_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdNew;
public System.Windows.Forms.Button cmdNew {
get { return withEventsField_cmdNew; }
set {
if (withEventsField_cmdNew != null) {
withEventsField_cmdNew.Click -= cmdNew_Click;
}
withEventsField_cmdNew = value;
if (withEventsField_cmdNew != null) {
withEventsField_cmdNew.Click += cmdNew_Click;
}
}
}
private System.Windows.Forms.ListView withEventsField_lvItem;
public System.Windows.Forms.ListView lvItem {
get { return withEventsField_lvItem; }
set {
if (withEventsField_lvItem != null) {
withEventsField_lvItem.DoubleClick -= lvItem_DoubleClick;
withEventsField_lvItem.KeyPress -= lvItem_KeyPress;
}
withEventsField_lvItem = value;
if (withEventsField_lvItem != null) {
withEventsField_lvItem.DoubleClick += lvItem_DoubleClick;
withEventsField_lvItem.KeyPress += lvItem_KeyPress;
}
}
}
//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()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmCashTransaction));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.picButtons = new System.Windows.Forms.Panel();
this.cmdClose = new System.Windows.Forms.Button();
this.cmdPrint = new System.Windows.Forms.Button();
this.cmdDelete = new System.Windows.Forms.Button();
this.cmdNew = new System.Windows.Forms.Button();
this.lvItem = new System.Windows.Forms.ListView();
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Cash Transactions";
this.ClientSize = new System.Drawing.Size(461, 515);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmCashTransaction";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(461, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 3;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(369, 3);
this.cmdClose.TabIndex = 5;
this.cmdClose.TabStop = false;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Name = "cmdClose";
this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPrint.Text = "&Print";
this.cmdPrint.Size = new System.Drawing.Size(73, 29);
this.cmdPrint.Location = new System.Drawing.Point(9, 3);
this.cmdPrint.TabIndex = 4;
this.cmdPrint.TabStop = false;
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.CausesValidation = true;
this.cmdPrint.Enabled = true;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.Name = "cmdPrint";
this.cmdDelete.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdDelete.Text = "&Delete";
this.cmdDelete.Size = new System.Drawing.Size(97, 34);
this.cmdDelete.Location = new System.Drawing.Point(351, 465);
this.cmdDelete.TabIndex = 2;
this.cmdDelete.TabStop = false;
this.cmdDelete.BackColor = System.Drawing.SystemColors.Control;
this.cmdDelete.CausesValidation = true;
this.cmdDelete.Enabled = true;
this.cmdDelete.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdDelete.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdDelete.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdDelete.Name = "cmdDelete";
this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNew.Text = "&Add";
this.cmdNew.Size = new System.Drawing.Size(97, 34);
this.cmdNew.Location = new System.Drawing.Point(9, 465);
this.cmdNew.TabIndex = 0;
this.cmdNew.TabStop = false;
this.cmdNew.BackColor = System.Drawing.SystemColors.Control;
this.cmdNew.CausesValidation = true;
this.cmdNew.Enabled = true;
this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNew.Name = "cmdNew";
this.lvItem.Size = new System.Drawing.Size(445, 409);
this.lvItem.Location = new System.Drawing.Point(6, 45);
this.lvItem.TabIndex = 1;
this.lvItem.View = System.Windows.Forms.View.Details;
this.lvItem.LabelWrap = true;
this.lvItem.HideSelection = false;
this.lvItem.FullRowSelect = true;
this.lvItem.GridLines = true;
this.lvItem.ForeColor = System.Drawing.SystemColors.WindowText;
this.lvItem.BackColor = System.Drawing.SystemColors.Window;
this.lvItem.LabelEdit = true;
this.lvItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lvItem.Name = "lvItem";
this.Controls.Add(picButtons);
this.Controls.Add(cmdDelete);
this.Controls.Add(cmdNew);
this.Controls.Add(lvItem);
this.picButtons.Controls.Add(cmdClose);
this.picButtons.Controls.Add(cmdPrint);
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// Copyright (c) 2010-2019 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace SIL.Progress
{
public class MultiProgress : IProgress, IDisposable
{
private class ProgressHandler
{
public IProgress Handler { get; private set; }
public bool CanHandleStatus { get; private set; }
public bool CanHandleMessages { get; private set; }
public ProgressHandler(IProgress p, Capabilities c)
{
Handler = p;
CanHandleStatus = false;
CanHandleMessages = false;
if (c == Capabilities.Status || c == Capabilities.All)
{
CanHandleStatus = true;
}
if (c == Capabilities.Message || c == Capabilities.All)
{
CanHandleMessages = true;
}
}
}
private enum Capabilities
{
Status,
Message,
All
}
private readonly List<ProgressHandler> _progressHandlers =new List<ProgressHandler>();
private bool _cancelRequested;
private ProgressIndicatorForMultiProgress _indicatorForMultiProgress;
public MultiProgress(IEnumerable<IProgress> progressHandlers)
{
ErrorEncountered = false;
WarningsEncountered = false;
foreach (IProgress progressHandler in progressHandlers)
{
_progressHandlers.Add(new ProgressHandler(progressHandler, Capabilities.All));
}
_indicatorForMultiProgress = new ProgressIndicatorForMultiProgress();
}
public MultiProgress()
{
_indicatorForMultiProgress = new ProgressIndicatorForMultiProgress();
}
public SynchronizationContext SyncContext {
get { return _indicatorForMultiProgress.SyncContext; }
set
{
foreach (ProgressHandler progressHandler in _progressHandlers)
{
progressHandler.Handler.SyncContext = value;
if (progressHandler.Handler.ProgressIndicator != null)
{
progressHandler.Handler.ProgressIndicator.SyncContext = value;
}
}
_indicatorForMultiProgress.SyncContext = value;
}
}
public bool CancelRequested
{
get
{
if (_progressHandlers.Any(h => h.Handler.CancelRequested))
{
return true;
}
return _cancelRequested;
}
set
{
_cancelRequested = value;
}
}
public bool ErrorEncountered
{
get
{ return _progressHandlers.Any(h => h.Handler.ErrorEncountered); }
set
{
foreach (var h in _progressHandlers)
{
h.Handler.ErrorEncountered = value;
}
}
}
public bool WarningsEncountered { get; set; }
public IProgressIndicator ProgressIndicator
{
get { return _indicatorForMultiProgress; }
set
{
// cjh: this could cause confusion by wrapping AddIndicator() with a property setter. There's no way to "undo" the set later on.
_indicatorForMultiProgress.AddIndicator(value);
}
}
public void WriteStatus(string message, params object[] args)
{
foreach (var h in _progressHandlers)
{
if (h.CanHandleStatus)
{
h.Handler.WriteStatus(message, args);
}
if (h.CanHandleMessages)
{
h.Handler.WriteVerbose(message, args);
}
}
}
public void WriteMessage(string message, params object[] args)
{
foreach (var h in _progressHandlers.Where(h => h.CanHandleMessages))
{
h.Handler.WriteMessage(message, args);
}
}
public void WriteMessageWithColor(string colorName, string message, params object[] args)
{
foreach (var h in _progressHandlers.Where(h => h.CanHandleMessages))
{
h.Handler.WriteMessageWithColor(colorName, message, args);
}
}
public void WriteWarning(string message, params object[] args)
{
foreach (var h in _progressHandlers.Where(h => h.CanHandleMessages))
{
h.Handler.WriteWarning(message, args);
}
WarningsEncountered = true;
}
public void WriteException(Exception error)
{
foreach (var h in _progressHandlers)
{
if (h.CanHandleMessages)
{
h.Handler.WriteException(error);
}
}
ErrorEncountered = true;
}
public void WriteError(string message, params object[] args)
{
foreach (var h in _progressHandlers.Where(h => h.CanHandleMessages))
{
h.Handler.WriteError(message, args);
}
ErrorEncountered = true;
}
public void WriteVerbose(string message, params object[] args)
{
foreach (var h in _progressHandlers.Where(h => h.CanHandleMessages))
{
h.Handler.WriteVerbose(message, args);
}
}
public bool ShowVerbose
{
set //review: the best policy isn't completely clear here
{
foreach (var handler in _progressHandlers)
{
handler.Handler.ShowVerbose = value;
}
}
}
public void Dispose()
{
foreach (ProgressHandler handler in _progressHandlers)
{
var d = handler as IDisposable;
if (d != null)
d.Dispose();
}
}
public void Add(IProgress progress)
{
_progressHandlers.Add(new ProgressHandler(progress, Capabilities.All));
if (progress.ProgressIndicator != null)
{
_indicatorForMultiProgress.AddIndicator(progress.ProgressIndicator);
}
}
public void AddStatusProgress(IProgress p)
{
_progressHandlers.Add(new ProgressHandler(p, Capabilities.Status));
if (p.ProgressIndicator != null)
{
_indicatorForMultiProgress.AddIndicator(p.ProgressIndicator);
}
}
public void AddMessageProgress(IProgress p)
{
_progressHandlers.Add(new ProgressHandler(p, Capabilities.Message));
if (p.ProgressIndicator != null)
{
_indicatorForMultiProgress.AddIndicator(p.ProgressIndicator);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
// It's a Water script from Pro Standard Assets,
// just refraction stuff was removed.
[ExecuteInEditMode] // Make mirror live-update even when not in play mode
public class WaterMirrorReflection : MonoBehaviour
{
//public int custom_scale = 1;
public bool m_DisablePixelLights = true;
public int m_TextureSize = 256;
public float m_ClipPlaneOffset = 0.07f;
public bool m_BackSide = false;
public LayerMask m_ReflectLayers = -1;
private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table
private RenderTexture m_ReflectionTexture = null;
private int m_OldReflectionTextureSize = 0;
private static bool s_InsideRendering = false;
// This is called when it's known that the object will be rendered by some
// camera. We render reflections and do other updates here.
// Because the script executes in edit mode, reflections for the scene view
// camera will just work!
public void OnWillRenderObject()
{
if( !enabled || !renderer || !renderer.sharedMaterial || !renderer.enabled )
return;
Camera cam = Camera.current;
if( !cam )
return;
// Safeguard from recursive reflections.
if( s_InsideRendering )
return;
s_InsideRendering = true;
Camera reflectionCamera;
CreateMirrorObjects( cam, out reflectionCamera );
reflectionCamera.renderingPath = RenderingPath.Forward;
// find out the reflection plane: position and normal in world space
Vector3 pos = transform.position;
Vector3 normal = transform.up;
if(m_BackSide) normal = -normal;
// Optionally disable pixel lights for reflection
//int oldPixelLightCount = QualitySettings.pixelLightCount;
//if( m_DisablePixelLights )
// QualitySettings.pixelLightCount = 0;
UpdateCameraModes( cam, reflectionCamera );
// Render reflection
// Reflect camera around reflection plane
float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;
Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
CalculateReflectionMatrix (ref reflection, reflectionPlane);
Vector3 oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint( oldpos );
reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );
Matrix4x4 projection = cam.projectionMatrix;
CalculateObliqueMatrix (ref projection, clipPlane);
reflectionCamera.projectionMatrix = projection;
reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // never render water layer
reflectionCamera.targetTexture = m_ReflectionTexture;
GL.SetRevertBackfacing (true);
reflectionCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
reflectionCamera.Render();
reflectionCamera.transform.position = oldpos;
GL.SetRevertBackfacing (false);
Material[] materials = renderer.sharedMaterials;
foreach( Material mat in materials ) {
if( mat.HasProperty("_ReflectionTex") )
mat.SetTexture( "_ReflectionTex", m_ReflectionTexture );
}
// Set matrix on the shader that transforms UVs from object space into screen
// space. We want to just project reflection texture on screen.
Matrix4x4 scaleOffset = Matrix4x4.TRS(
new Vector3(0.5f,0.5f,0.5f), Quaternion.identity, new Vector3(0.5f,0.5f,0.5f) );
Vector3 scale = transform.lossyScale;
Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale( new Vector3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z) );
//Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale( new Vector3(custom_scale/scale.x, custom_scale/scale.y, custom_scale/scale.z) );
mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
foreach( Material mat in materials ) {
mat.SetMatrix( "_ProjMatrix", mtx );
}
// Restore pixel light count
//if( m_DisablePixelLights )
// QualitySettings.pixelLightCount = oldPixelLightCount;
s_InsideRendering = false;
}
// Cleanup all the objects we possibly have created
void OnDisable()
{
if( m_ReflectionTexture ) {
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = null;
}
foreach( DictionaryEntry kvp in m_ReflectionCameras )
DestroyImmediate( ((Camera)kvp.Value).gameObject );
m_ReflectionCameras.Clear();
}
private void UpdateCameraModes( Camera src, Camera dest )
{
if( dest == null )
return;
// set camera to clear the same way as current camera
dest.clearFlags = src.clearFlags;
dest.backgroundColor = src.backgroundColor;
if( src.clearFlags == CameraClearFlags.Skybox )
{
Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
if( !sky || !sky.material )
{
mysky.enabled = false;
}
else
{
mysky.enabled = true;
mysky.material = sky.material;
}
}
// update other values to match current camera.
// even if we are supplying custom camera&projection matrices,
// some of values are used elsewhere (e.g. skybox uses far plane)
dest.farClipPlane = src.farClipPlane;
dest.nearClipPlane = src.nearClipPlane;
dest.orthographic = src.orthographic;
dest.fieldOfView = src.fieldOfView;
dest.aspect = src.aspect;
dest.orthographicSize = src.orthographicSize;
}
// On-demand create any objects we need
private void CreateMirrorObjects( Camera currentCamera, out Camera reflectionCamera )
{
reflectionCamera = null;
// Reflection render texture
if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
{
if( m_ReflectionTexture )
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID();
m_ReflectionTexture.isPowerOfTwo = true;
m_ReflectionTexture.hideFlags = HideFlags.DontSave;
m_OldReflectionTextureSize = m_TextureSize;
}
// Camera for reflection
reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject( "Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
reflectionCamera = go.camera;
reflectionCamera.enabled = false;
reflectionCamera.transform.position = transform.position;
reflectionCamera.transform.rotation = transform.rotation;
reflectionCamera.gameObject.AddComponent("FlareLayer");
go.hideFlags = HideFlags.HideAndDontSave;
m_ReflectionCameras[currentCamera] = reflectionCamera;
}
}
// Extended sign: returns -1, 0 or 1 based on sign of a
private static float sgn(float a)
{
if (a > 0.0f) return 1.0f;
if (a < 0.0f) return -1.0f;
return 0.0f;
}
// Given position/normal of the plane, calculates plane in camera space.
private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint( offsetPos );
Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
}
// Adjusts the given projection matrix so that near plane is the given clipPlane
// clipPlane is given in camera space. See article in Game Programming Gems 5 and
// http://aras-p.info/texts/obliqueortho.html
private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
sgn(clipPlane.x),
sgn(clipPlane.y),
1.0f,
1.0f
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
}
// Calculates reflection matrix around the given plane
private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
reflectionMat.m01 = ( - 2F*plane[0]*plane[1]);
reflectionMat.m02 = ( - 2F*plane[0]*plane[2]);
reflectionMat.m03 = ( - 2F*plane[3]*plane[0]);
reflectionMat.m10 = ( - 2F*plane[1]*plane[0]);
reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
reflectionMat.m12 = ( - 2F*plane[1]*plane[2]);
reflectionMat.m13 = ( - 2F*plane[3]*plane[1]);
reflectionMat.m20 = ( - 2F*plane[2]*plane[0]);
reflectionMat.m21 = ( - 2F*plane[2]*plane[1]);
reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
reflectionMat.m23 = ( - 2F*plane[3]*plane[2]);
reflectionMat.m30 = 0F;
reflectionMat.m31 = 0F;
reflectionMat.m32 = 0F;
reflectionMat.m33 = 1F;
}
}
| |
using System;
using UIKit;
using CoreGraphics;
using System.Threading;
using System.Threading.Tasks;
namespace UISlideNotification
{
public enum UISlideNotificationPosition
{
Top,
Bottom
}
public class UISlideNotification
{
private UIView _parentView;
private UIViewController _parentController;
private string _notificationText;
private UIColor _backgroundColor = UIColor.Black;
private UIColor _textColor = UIColor.White;
private UITextAlignment _textAlignment = UITextAlignment.Center;
private float _labelAlpha = 0.8f;
private UIActivityIndicatorViewStyle _activityIndicatorViewStyle = UIActivityIndicatorViewStyle.White;
private float _activityIndicatorViewAlpha = 1.0f;
private CGPoint _activityIndicatorViewCenter = new CGPoint (15, 15);
private bool _showActivitySpinner;
private int _notificationDuration = 3000;
private int _animationDuration = 300;
private UISlideNotificationPosition _position = UISlideNotificationPosition.Bottom;
private int labelHeight = 30;
private int statusBarHeight = 20;
private int toolbarHeight = 44;
/// <summary>
/// Gets or sets how long the notification stays open after displaying.
/// </summary>
/// <value>The duration of the notification in milliseconds</value>
public int NotificationDuration
{
get { return _notificationDuration; }
set { _notificationDuration = value; }
}
/// <summary>
/// Gets or sets the duration of the notification animation in milliseconds.
/// </summary>
/// <value>Duration in milliseconds</value>
public int NotificationAnimationDuration
{
get { return _animationDuration; }
set { _animationDuration = value; }
}
/// <summary>
/// Gets or sets the center point of the activity indicator.
/// </summary>
/// <value>Activity Indicator center point</value>
public CGPoint ActivityIndicatorViewCenter
{
get { return _activityIndicatorViewCenter; }
set { _activityIndicatorViewCenter = value; }
}
/// <summary>
/// Gets or sets the activity indicator view alpha value.
/// </summary>
/// <value>The activity indicator view alpha.</value>
public float ActivityIndicatorViewAlpha
{
get { return _activityIndicatorViewAlpha; }
set { _activityIndicatorViewAlpha = value; }
}
/// <summary>
/// Gets or sets the activity indicator view style.
/// </summary>
/// <value>The activity indicator view style.</value>
public UIActivityIndicatorViewStyle ActivityIndicatorViewStyle
{
get { return _activityIndicatorViewStyle; }
set { _activityIndicatorViewStyle = value; }
}
/// <summary>
/// Gets or sets the background color of the notification.
/// </summary>
/// <value>The color of the background.</value>
public UIColor BackgroundColor
{
get { return _backgroundColor; }
set { _backgroundColor = value; }
}
/// <summary>
/// Gets or sets the text color of the notification text
/// </summary>
/// <value>The color of the text.</value>
public UIColor TextColor
{
get { return _textColor; }
set { _textColor = value; }
}
/// <summary>
/// Gets or sets the text alignment of the notification text.
/// </summary>
/// <value>The text alignment.</value>
public UITextAlignment TextAlignment
{
get { return _textAlignment; }
set { _textAlignment = value; }
}
/// <summary>
/// Gets or sets the alpha value of the notification.
/// </summary>
/// <value>The alpha.</value>
public float Alpha
{
get { return _labelAlpha; }
set { _labelAlpha = value; }
}
private nfloat NotificationLabelTop
{
get
{
_parentController = _parentView.GetParentUIViewController ();
if (_parentController != null)
{
if (_position == UISlideNotificationPosition.Bottom)
{
if ((_parentController.ToolbarItems != null && _parentController.ToolbarItems.Length > 0) ||
(_parentController.NavigationController != null && !_parentController.NavigationController.ToolbarHidden))
{
return (iOSHelpers.IsIOS7) ? _parentView.Frame.Bottom - toolbarHeight : _parentView.Frame.Bottom;
}
}
else if (_position == UISlideNotificationPosition.Top)
{
if (_parentController.NavigationController != null && !_parentController.NavigationController.NavigationBarHidden)
{
return (iOSHelpers.IsIOS7) ? _parentView.Frame.Top + labelHeight : _parentView.Frame.Top - labelHeight;
}
return (iOSHelpers.IsIOS7) ? _parentView.Frame.Top + statusBarHeight - labelHeight : _parentView.Frame.Top - labelHeight;
}
}
return (_position == UISlideNotificationPosition.Bottom) ? _parentView.Frame.Bottom : _parentView.Frame.Top;
}
}
public UISlideNotification (UIView parentView, string notificationText)
: this(parentView, notificationText, false, UISlideNotificationPosition.Bottom)
{
}
public UISlideNotification (UIView parentView, string notificationText, bool showActivitySpinner)
: this(parentView, notificationText, showActivitySpinner, UISlideNotificationPosition.Bottom)
{
}
public UISlideNotification (UIView parentView, string notificationText, UISlideNotificationPosition position)
: this(parentView, notificationText, false, position)
{
}
public UISlideNotification (UIView parentView, string notificationText, bool showActivitySpinner, UISlideNotificationPosition position)
{
_parentView = parentView;
_notificationText = notificationText;
_showActivitySpinner = showActivitySpinner;
_position = position;
}
private UILabel notificationLabel = null;
private UIActivityIndicatorView activityView = null;
private void SetupUI()
{
notificationLabel = new UILabel (new CGRect (0, this.NotificationLabelTop, _parentView.Frame.Width, labelHeight));
notificationLabel.Text = _notificationText;
notificationLabel.BackgroundColor = this.BackgroundColor;
notificationLabel.TextColor = this.TextColor;
notificationLabel.TextAlignment = this.TextAlignment;
notificationLabel.Alpha = _labelAlpha;
if (_showActivitySpinner)
{
activityView = new UIActivityIndicatorView (this.ActivityIndicatorViewStyle);
activityView.Alpha = this.ActivityIndicatorViewAlpha;
activityView.HidesWhenStopped = false;
activityView.Center = this.ActivityIndicatorViewCenter;
notificationLabel.AddSubview (activityView);
}
}
public void ShowNotification()
{
SetupUI ();
_parentView.AddSubview (notificationLabel);
notificationLabel.Hidden = false;
if (_showActivitySpinner)
activityView.StartAnimating ();
var newFrame = new CGRect (notificationLabel.Frame.X, notificationLabel.Frame.Y, notificationLabel.Frame.Width, notificationLabel.Frame.Height);
if (_position == UISlideNotificationPosition.Bottom)
newFrame.Y -= labelHeight;
else
newFrame.Y += labelHeight;
UIView.Transition(notificationLabel, (_animationDuration / 1000f), UIViewAnimationOptions.CurveEaseInOut, () => {
notificationLabel.Frame = newFrame;
}, () => {
var ctx = TaskScheduler.FromCurrentSynchronizationContext();
Task.Delay(_notificationDuration).ContinueWith((task) => HideNotification(), ctx);
});
}
public void HideNotification()
{
var newFrame = new CGRect (notificationLabel.Frame.X, notificationLabel.Frame.Y, notificationLabel.Frame.Width, notificationLabel.Frame.Height);
if (_position == UISlideNotificationPosition.Bottom)
newFrame.Y += labelHeight;
else
newFrame.Y -= labelHeight;
UIView.Transition(notificationLabel, (_animationDuration / 1000f), UIViewAnimationOptions.CurveEaseInOut, () => {
notificationLabel.Frame = newFrame;
}, () => {
if (_showActivitySpinner)
activityView.StopAnimating();
notificationLabel.Hidden = true;
notificationLabel.RemoveFromSuperview ();
});
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Net.Http.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Android.Net.Http
{
/// <summary>
/// <para>SSL certificate info (certificate details) class </para>
/// </summary>
/// <java-name>
/// android/net/http/SslCertificate
/// </java-name>
[Dot42.DexImport("android/net/http/SslCertificate", AccessFlags = 33)]
public partial class SslCertificate
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public SslCertificate(string @string, string string1, string string2, string string3) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new SSL certificate object from an X509 certificate </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/security/cert/X509Certificate;)V", AccessFlags = 1)]
public SslCertificate(global::Java.Security.Cert.X509Certificate certificate) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Saves the certificate state to a bundle </para>
/// </summary>
/// <returns>
/// <para>A bundle with the certificate stored in it or null if fails </para>
/// </returns>
/// <java-name>
/// saveState
/// </java-name>
[Dot42.DexImport("saveState", "(Landroid/net/http/SslCertificate;)Landroid/os/Bundle;", AccessFlags = 9)]
public static global::Android.Os.Bundle SaveState(global::Android.Net.Http.SslCertificate certificate) /* MethodBuilder.Create */
{
return default(global::Android.Os.Bundle);
}
/// <summary>
/// <para>Restores the certificate stored in the bundle </para>
/// </summary>
/// <returns>
/// <para>The SSL certificate stored in the bundle or null if fails </para>
/// </returns>
/// <java-name>
/// restoreState
/// </java-name>
[Dot42.DexImport("restoreState", "(Landroid/os/Bundle;)Landroid/net/http/SslCertificate;", AccessFlags = 9)]
public static global::Android.Net.Http.SslCertificate RestoreState(global::Android.Os.Bundle bundle) /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.SslCertificate);
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use getValidNotBeforeDate() </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Not-before date from the certificate validity period in ISO 8601 format or "" if none has been set</para>
/// </returns>
/// <java-name>
/// getValidNotBefore
/// </java-name>
[Dot42.DexImport("getValidNotBefore", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetValidNotBefore() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use getValidNotAfterDate() </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Not-after date from the certificate validity period in ISO 8601 format or "" if none has been set</para>
/// </returns>
/// <java-name>
/// getValidNotAfter
/// </java-name>
[Dot42.DexImport("getValidNotAfter", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetValidNotAfter() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Issued-to distinguished name or null if none has been set </para>
/// </returns>
/// <java-name>
/// getIssuedTo
/// </java-name>
[Dot42.DexImport("getIssuedTo", "()Landroid/net/http/SslCertificate$DName;", AccessFlags = 1)]
public virtual global::Android.Net.Http.SslCertificate.DName GetIssuedTo() /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.SslCertificate.DName);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Issued-by distinguished name or null if none has been set </para>
/// </returns>
/// <java-name>
/// getIssuedBy
/// </java-name>
[Dot42.DexImport("getIssuedBy", "()Landroid/net/http/SslCertificate$DName;", AccessFlags = 1)]
public virtual global::Android.Net.Http.SslCertificate.DName GetIssuedBy() /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.SslCertificate.DName);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>A string representation of this certificate for debugging </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal SslCertificate() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use getValidNotBeforeDate() </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Not-before date from the certificate validity period in ISO 8601 format or "" if none has been set</para>
/// </returns>
/// <java-name>
/// getValidNotBefore
/// </java-name>
public string ValidNotBefore
{
[Dot42.DexImport("getValidNotBefore", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetValidNotBefore(); }
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use getValidNotAfterDate() </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Not-after date from the certificate validity period in ISO 8601 format or "" if none has been set</para>
/// </returns>
/// <java-name>
/// getValidNotAfter
/// </java-name>
public string ValidNotAfter
{
[Dot42.DexImport("getValidNotAfter", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetValidNotAfter(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Issued-to distinguished name or null if none has been set </para>
/// </returns>
/// <java-name>
/// getIssuedTo
/// </java-name>
public global::Android.Net.Http.SslCertificate.DName IssuedTo
{
[Dot42.DexImport("getIssuedTo", "()Landroid/net/http/SslCertificate$DName;", AccessFlags = 1)]
get{ return GetIssuedTo(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Issued-by distinguished name or null if none has been set </para>
/// </returns>
/// <java-name>
/// getIssuedBy
/// </java-name>
public global::Android.Net.Http.SslCertificate.DName IssuedBy
{
[Dot42.DexImport("getIssuedBy", "()Landroid/net/http/SslCertificate$DName;", AccessFlags = 1)]
get{ return GetIssuedBy(); }
}
/// <summary>
/// <para>A distinguished name helper class: a 3-tuple of: <ul><li><para>the most specific common name (CN) </para></li><li><para>the most specific organization (O) </para></li><li><para>the most specific organizational unit (OU) <ul><li></li></ul></para></li></ul></para>
/// </summary>
/// <java-name>
/// android/net/http/SslCertificate$DName
/// </java-name>
[Dot42.DexImport("android/net/http/SslCertificate$DName", AccessFlags = 1)]
public partial class DName
/* scope: __dot42__ */
{
/// <java-name>
/// this$0
/// </java-name>
[Dot42.DexImport("this$0", "Landroid/net/http/SslCertificate;", AccessFlags = 4112)]
internal readonly global::Android.Net.Http.SslCertificate This_0;
[Dot42.DexImport("<init>", "(Landroid/net/http/SslCertificate;Ljava/lang/String;)V", AccessFlags = 1)]
public DName(global::Android.Net.Http.SslCertificate sslCertificate, string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The distinguished name (normally includes CN, O, and OU names) </para>
/// </returns>
/// <java-name>
/// getDName
/// </java-name>
[Dot42.DexImport("getDName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetDName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Common-name (CN) component of this name </para>
/// </returns>
/// <java-name>
/// getCName
/// </java-name>
[Dot42.DexImport("getCName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetCName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Organization (O) component of this name </para>
/// </returns>
/// <java-name>
/// getOName
/// </java-name>
[Dot42.DexImport("getOName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetOName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Organizational Unit (OU) component of this name </para>
/// </returns>
/// <java-name>
/// getUName
/// </java-name>
[Dot42.DexImport("getUName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetUName() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal DName() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Common-name (CN) component of this name </para>
/// </returns>
/// <java-name>
/// getCName
/// </java-name>
public string CName
{
[Dot42.DexImport("getCName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetCName(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Organization (O) component of this name </para>
/// </returns>
/// <java-name>
/// getOName
/// </java-name>
public string OName
{
[Dot42.DexImport("getOName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetOName(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Organizational Unit (OU) component of this name </para>
/// </returns>
/// <java-name>
/// getUName
/// </java-name>
public string UName
{
[Dot42.DexImport("getUName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetUName(); }
}
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using Microsoft.Web.Services3.Design;
using Vim25Api;
namespace AppUtil
{
/// <summary>
/// Connection Handler for WebService
/// </summary>
public class SvcConnection
{
public enum ConnectionState
{
Connected,
Disconnected,
}
public VimService _service;
protected ConnectionState _state;
public ServiceContent _sic;
protected ManagedObjectReference _svcRef;
public event ConnectionEventHandler AfterConnect;
public event ConnectionEventHandler AfterDisconnect;
public event ConnectionEventHandler BeforeDisconnect;
private bool _ignoreCert;
public bool ignoreCert
{
get { return _ignoreCert; }
set
{
if (value)
{
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
}
_ignoreCert = value;
}
}
/// <summary>
/// This method is used to validate remote certificate
/// </summary>
/// <param name="sender">string Array</param>
/// <param name="certificate">X509Certificate certificate</param>
/// <param name="chain">X509Chain chain</param>
/// <param name="policyErrors">SslPolicyErrors policyErrors</param>
private static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
return true;
}
public SvcConnection(string svcRefVal)
{
_state = ConnectionState.Disconnected;
if (ignoreCert)
{
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
}
_svcRef = new ManagedObjectReference();
_svcRef.type = "ServiceInstance";
_svcRef.Value = svcRefVal;
}
/// <summary>
/// Creates an instance of the VMA proxy and establishes a connection
/// </summary>
/// <param name="url"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public void Connect(string url, string username, string password)
{
if (_service != null)
{
Disconnect();
}
_service = new VimService();
_service.Url = url;
_service.Timeout = 600000; //The value can be set to some higher value also.
_service.CookieContainer = new System.Net.CookieContainer();
_sic = _service.RetrieveServiceContent(_svcRef);
if (_sic.sessionManager != null)
{
_service.Login(_sic.sessionManager, username, password, null);
}
_state = ConnectionState.Connected;
if (AfterConnect != null)
{
AfterConnect(this, new ConnectionEventArgs());
}
}
public void Connect(string url, Cookie cookie)
{
if (_service != null)
{
Disconnect();
}
_service = new VimService();
_service.Url = url;
_service.Timeout = 600000; //The value can be set to some higher value also.
_service.CookieContainer = new System.Net.CookieContainer();
_service.CookieContainer.Add(cookie);
_sic = _service.RetrieveServiceContent(_svcRef);
_state = ConnectionState.Connected;
if (AfterConnect != null)
{
AfterConnect(this, new ConnectionEventArgs());
}
}
public void SaveSession(String fileName, String urlString)
{
Cookie cookie = _service.CookieContainer.GetCookies(
new Uri(urlString))[0];
BinaryFormatter bf = new BinaryFormatter();
Stream s = File.Open(fileName, FileMode.Create);
bf.Serialize(s, cookie);
s.Close();
}
public void LoadSession(String fileName, String urlString)
{
if (_service != null)
{
Disconnect();
}
_service = new VimService();
_service.Url = urlString;
_service.Timeout = 600000;
_service.CookieContainer = new System.Net.CookieContainer();
BinaryFormatter bf = new BinaryFormatter();
Stream s = File.Open(fileName, FileMode.Open);
Cookie c = bf.Deserialize(s) as Cookie;
s.Close();
_service.CookieContainer.Add(c);
_sic = _service.RetrieveServiceContent(_svcRef);
_state = ConnectionState.Connected;
if (AfterConnect != null)
{
AfterConnect(this, new ConnectionEventArgs());
}
}
public VimService Service
{
get
{
return _service;
}
}
public ManagedObjectReference ServiceRef
{
get
{
return _svcRef;
}
}
public ServiceContent ServiceContent
{
get
{
return _sic;
}
}
public ManagedObjectReference PropCol
{
get
{
return _sic.propertyCollector;
}
}
public ManagedObjectReference Root
{
get
{
return _sic.rootFolder;
}
}
public ConnectionState State
{
get
{
return _state;
}
}
/// <summary>
/// Disconnects the Connection
/// </summary>
public void Disconnect()
{
if (_service != null)
{
if (BeforeDisconnect != null)
{
BeforeDisconnect(this, new ConnectionEventArgs());
}
if (_sic != null)
_service.Logout(_sic.sessionManager);
_service.Dispose();
_service = null;
_sic = null;
_state = ConnectionState.Disconnected;
if (AfterDisconnect != null)
{
AfterDisconnect(this, new ConnectionEventArgs());
}
}
}
public void SSOConnect(XmlElement token, string url)
{
if (_service != null)
{
Disconnect();
}
_service = new VimService();
_service.Url = url;
_service.Timeout = 600000; //The value can be set to some higher value also.
_service.CookieContainer = new System.Net.CookieContainer();
//...
//When this property is set to true, client requests that use the POST method
//expect to receive a 100-Continue response from the server to indicate that
//the client should send the data to be posted. This mechanism allows clients
//to avoid sending large amounts of data over the network when the server,
//based on the request headers, intends to reject the request
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
var customSecurityAssertion = new CustomSecurityAssertionBearer();
customSecurityAssertion.BinaryToken = token;
//Setting up the security policy for the request
Policy policySAML = new Policy();
policySAML.Assertions.Add(customSecurityAssertion);
// Setting policy of the service
_service.SetPolicy(policySAML);
_sic = _service.RetrieveServiceContent(_svcRef);
if (_sic.sessionManager != null)
{
_service.LoginByToken(_sic.sessionManager, null);
}
_state = ConnectionState.Connected;
if (AfterConnect != null)
{
AfterConnect(this, new ConnectionEventArgs());
}
}
}
public class ConnectionEventArgs : System.EventArgs
{
}
public delegate void ConnectionEventHandler(object sender, ConnectionEventArgs e);
}
| |
//------------------------------------------------------------------------------
// <copyright file="DBPropSet.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.ConstrainedExecution;
namespace System.Data.OleDb {
sealed internal class DBPropSet : SafeHandle {
private readonly Int32 propertySetCount;
// VSDD 621427: stores the exception with last error.HRESULT from IDBProperties.GetProperties
private Exception lastErrorFromProvider;
private DBPropSet() : base(IntPtr.Zero, true) {
propertySetCount = 0;
}
internal DBPropSet(int propertysetCount) : this() {
this.propertySetCount = propertysetCount;
IntPtr countOfBytes = (IntPtr)(propertysetCount * ODB.SizeOf_tagDBPROPSET);
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
base.handle = SafeNativeMethods.CoTaskMemAlloc(countOfBytes);
if (ADP.PtrZero != base.handle) {
SafeNativeMethods.ZeroMemory(base.handle, countOfBytes);
}
}
if (ADP.PtrZero == base.handle) {
throw new OutOfMemoryException();
}
}
internal DBPropSet(UnsafeNativeMethods.IDBProperties properties, PropertyIDSet propidset, out OleDbHResult hr) : this() {
Debug.Assert(null != properties, "null IDBProperties");
int propidsetcount = 0;
if (null != propidset) {
propidsetcount = propidset.Count;
}
Bid.Trace("<oledb.IDBProperties.GetProperties|API|OLEDB>\n");
hr = properties.GetProperties(propidsetcount, propidset, out this.propertySetCount, out base.handle);
Bid.Trace("<oledb.IDBProperties.GetProperties|API|OLEDB|RET> %08X{HRESULT}\n", hr);
if (hr < 0) {
// VSDD 621427: remember the last HRESULT. Note we do not want to raise exception now to avoid breaking change from Orcas RTM/SP1
SetLastErrorInfo(hr);
}
}
internal DBPropSet(UnsafeNativeMethods.IRowsetInfo properties, PropertyIDSet propidset, out OleDbHResult hr) : this() {
Debug.Assert(null != properties, "null IRowsetInfo");
int propidsetcount = 0;
if (null != propidset) {
propidsetcount = propidset.Count;
}
Bid.Trace("<oledb.IRowsetInfo.GetProperties|API|OLEDB>\n");
hr = properties.GetProperties(propidsetcount, propidset, out this.propertySetCount, out base.handle);
Bid.Trace("<oledb.IRowsetInfo.GetProperties|API|OLEDB|RET> %08X{HRESULT}\n", hr);
if (hr < 0) {
// VSDD 621427: remember the last HRESULT. Note we do not want to raise exception now to avoid breaking change from Orcas RTM/SP1
SetLastErrorInfo(hr);
}
}
internal DBPropSet(UnsafeNativeMethods.ICommandProperties properties, PropertyIDSet propidset, out OleDbHResult hr) : this() {
Debug.Assert(null != properties, "null ICommandProperties");
int propidsetcount = 0;
if (null != propidset) {
propidsetcount = propidset.Count;
}
Bid.Trace("<oledb.ICommandProperties.GetProperties|API|OLEDB>\n");
hr = properties.GetProperties(propidsetcount, propidset, out this.propertySetCount, out base.handle);
Bid.Trace("<oledb.ICommandProperties.GetProperties|API|OLEDB|RET> %08X{HRESULT}\n", hr);
if (hr < 0) {
// VSDD 621427: remember the last HRESULT. Note we do not want to raise exception now to avoid breaking change from Orcas RTM/SP1
SetLastErrorInfo(hr);
}
}
private void SetLastErrorInfo(OleDbHResult lastErrorHr) {
// note: OleDbHResult is actually a simple wrapper over HRESULT with OLEDB-specific codes
UnsafeNativeMethods.IErrorInfo errorInfo = null;
string message = String.Empty;
OleDbHResult errorInfoHr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo
if ((errorInfoHr == OleDbHResult.S_OK) && (errorInfo != null)) {
ODB.GetErrorDescription(errorInfo, lastErrorHr, out message);
// note that either GetErrorInfo or GetErrorDescription might fail in which case we will have only the HRESULT value in exception message
}
lastErrorFromProvider = new COMException(message, (int)lastErrorHr);
}
public override bool IsInvalid {
get {
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle() {
// NOTE: The SafeHandle class guarantees this will be called exactly once and is non-interrutible.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
if (ADP.PtrZero != ptr) {
int count = this.propertySetCount;
for (int i = 0, offset = 0; i < count; ++i, offset += ODB.SizeOf_tagDBPROPSET) {
IntPtr rgProperties = Marshal.ReadIntPtr(ptr, offset);
if(ADP.PtrZero != rgProperties) {
int cProperties = Marshal.ReadInt32(ptr, offset + ADP.PtrSize);
IntPtr vptr = ADP.IntPtrOffset(rgProperties, ODB.OffsetOf_tagDBPROP_Value);
for (int k = 0; k < cProperties; ++k, vptr = ADP.IntPtrOffset(vptr, ODB.SizeOf_tagDBPROP)) {
SafeNativeMethods.VariantClear(vptr);
}
SafeNativeMethods.CoTaskMemFree(rgProperties);
}
}
SafeNativeMethods.CoTaskMemFree(ptr);
}
return true;
}
internal int PropertySetCount {
get {
return this.propertySetCount;
}
}
internal tagDBPROP[] GetPropertySet(int index, out Guid propertyset) {
if ((index < 0) || (PropertySetCount <= index)) {
if (lastErrorFromProvider != null)
{
// VSDD 621427: add extra error information for CSS/stress troubleshooting.
// We need to keep same exception type to avoid breaking change with Orcas RTM/SP1.
throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer, lastErrorFromProvider);
}
else {
throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer);
}
}
tagDBPROPSET propset = new tagDBPROPSET();
tagDBPROP[] properties = null;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
DangerousAddRef(ref mustRelease);
IntPtr propertySetPtr = ADP.IntPtrOffset(DangerousGetHandle(), index * ODB.SizeOf_tagDBPROPSET);
Marshal.PtrToStructure(propertySetPtr, propset);
propertyset = propset.guidPropertySet;
properties = new tagDBPROP[propset.cProperties];
for(int i = 0; i < properties.Length; ++i) {
properties[i] = new tagDBPROP();
IntPtr ptr = ADP.IntPtrOffset(propset.rgProperties, i * ODB.SizeOf_tagDBPROP);
Marshal.PtrToStructure(ptr, properties[i]);
}
}
finally {
if (mustRelease) {
DangerousRelease();
}
}
return properties;
}
internal void SetPropertySet(int index, Guid propertySet, tagDBPROP[] properties) {
if ((index < 0) || (PropertySetCount <= index)) {
if (lastErrorFromProvider != null) {
// VSDD 621427: add extra error information for CSS/stress troubleshooting.
// We need to keep same exception type to avoid breaking change with Orcas RTM/SP1.
throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer, lastErrorFromProvider);
}
else {
throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer);
}
}
Debug.Assert(Guid.Empty != propertySet, "invalid propertySet");
Debug.Assert((null != properties) && (0 < properties.Length), "invalid properties");
IntPtr countOfBytes = (IntPtr)(properties.Length * ODB.SizeOf_tagDBPROP);
tagDBPROPSET propset = new tagDBPROPSET(properties.Length, propertySet);
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
DangerousAddRef(ref mustRelease);
IntPtr propsetPtr = ADP.IntPtrOffset(DangerousGetHandle(), index * ODB.SizeOf_tagDBPROPSET);
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
// must allocate and clear the memory without interruption
propset.rgProperties = SafeNativeMethods.CoTaskMemAlloc(countOfBytes);
if (ADP.PtrZero != propset.rgProperties) {
// clearing is important so that we don't treat existing
// garbage as important information during releaseHandle
SafeNativeMethods.ZeroMemory(propset.rgProperties, countOfBytes);
// writing the structure to native memory so that it knows to free the referenced pointers
Marshal.StructureToPtr(propset, propsetPtr, false/*deleteold*/);
}
}
if (ADP.PtrZero == propset.rgProperties) {
throw new OutOfMemoryException();
}
for(int i = 0; i < properties.Length; ++i) {
Debug.Assert(null != properties[i], "null tagDBPROP " + i.ToString(CultureInfo.InvariantCulture));
IntPtr propertyPtr = ADP.IntPtrOffset(propset.rgProperties, i * ODB.SizeOf_tagDBPROP);
Marshal.StructureToPtr(properties[i], propertyPtr, false/*deleteold*/);
}
}
finally {
if (mustRelease) {
DangerousRelease();
}
}
}
static internal DBPropSet CreateProperty(Guid propertySet, int propertyId, bool required, object value) {
tagDBPROP dbprop = new tagDBPROP(propertyId, required, value);
DBPropSet propertyset = new DBPropSet(1);
propertyset.SetPropertySet(0, propertySet, new tagDBPROP[1] { dbprop });
return propertyset;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using Common.Logging;
using Rhino.ServiceBus.Internal;
namespace Rhino.ServiceBus.Impl
{
public class DefaultReflection : IReflection
{
private readonly ILog logger = LogManager.GetLogger(typeof (DefaultReflection));
private readonly IDictionary<Type, string> typeToWellKnownTypeName;
private readonly IDictionary<string, Type> wellKnownTypeNameToType;
private readonly MethodInfo internalPreserveStackTraceMethod;
public DefaultReflection()
{
internalPreserveStackTraceMethod = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
wellKnownTypeNameToType = new Dictionary<string, Type>();
typeToWellKnownTypeName = new Dictionary<Type, string>
{
{typeof (string), typeof (string).FullName},
{typeof (int), typeof (int).FullName},
{typeof (byte), typeof (byte).FullName},
{typeof (bool), typeof (bool).FullName},
{typeof (DateTime), typeof (DateTime).FullName},
{typeof (TimeSpan), typeof (TimeSpan).FullName},
{typeof (decimal), typeof (decimal).FullName},
{typeof (float), typeof (float).FullName},
{typeof (double), typeof (double).FullName},
{typeof (char), typeof (char).FullName},
{typeof (Guid), typeof (Guid).FullName},
{typeof (Uri), typeof (Uri).FullName},
{typeof (short), typeof (short).FullName},
{typeof (long), typeof (long).FullName},
{typeof(byte[]), "binary"}
};
foreach (var pair in typeToWellKnownTypeName)
{
wellKnownTypeNameToType.Add(pair.Value, pair.Key);
}
}
#region IReflection Members
public object CreateInstance(Type type, params object[] args)
{
try
{
return Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, args, null);
}
catch (Exception e)
{
throw new MissingMethodException("No parameterless constructor defined for this object: " + type, e);
}
}
public Type GetTypeFromXmlNamespace(string xmlNamespace)
{
Type value;
if (wellKnownTypeNameToType.TryGetValue(xmlNamespace, out value))
return value;
if(xmlNamespace.StartsWith("array_of_"))
{
return GetTypeFromXmlNamespace(xmlNamespace.Substring("array_of_".Length));
}
return Type.GetType(xmlNamespace);
}
public void InvokeAdd(object instance, object item)
{
try
{
Type type = instance.GetType();
MethodInfo method = type.GetMethod("Add", new[] {item.GetType()});
method.Invoke(instance, new[] {item});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public void InvokeAdd(object instance, object key, object value)
{
try
{
Type type = instance.GetType();
type.InvokeMember("Add", BindingFlags.Public| BindingFlags.InvokeMethod | BindingFlags.Instance, null, instance, new[] {key, value});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public XElement InvokeToElement(object instance, object item, Func<Type, XNamespace> getNamespace)
{
try
{
Type type = instance.GetType();
MethodInfo method = type.GetMethod("ToElement", new[] { item.GetType(), typeof(Func<Type, XNamespace>) });
return (XElement)method.Invoke(instance, new [] { item, getNamespace });
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public object InvokeFromElement(object instance, XElement value)
{
try
{
Type type = instance.GetType();
MethodInfo method = type.GetMethod("FromElement", new[] { typeof(XElement) });
return method.Invoke(instance, new [] { value });
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public void Set(object instance, string name, Func<Type, object> generateValue)
{
try
{
Type type = instance.GetType();
PropertyInfo property = type.GetProperty(name);
if (property == null || property.CanWrite == false)
{
logger.DebugFormat("Could not find settable property {0} to set on {1}", name, type);
return;
}
object value = generateValue(property.PropertyType);
property.SetValue(instance, value, null);
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
private Exception InnerExceptionWhilePreservingStackTrace(TargetInvocationException e)
{
internalPreserveStackTraceMethod.Invoke(e.InnerException, new object[0]);
return e.InnerException;
}
public object Get(object instance, string name)
{
try
{
Type type = instance.GetType();
PropertyInfo property = type.GetProperty(name);
if (property == null)
{
logger.InfoFormat("Could not find property {0} to get on {1}", name, type);
return null;
}
return property.GetValue(instance, null);
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public Type GetGenericTypeOf(Type type, object msg)
{
return GetGenericTypeOf(type, GetUnproxiedType(msg));
}
public Type GetGenericTypeOf(Type type, Type paramType)
{
return type.MakeGenericType(paramType);
}
public Type GetGenericTypeOf(Type type, params Type[] paramTypes)
{
return type.MakeGenericType(paramTypes);
}
public ICollection<Type> GetGenericTypesOfWithBaseTypes(Type type, object msg)
{
return GetGenericTypesOfWithBaseTypes(type, GetUnproxiedType(msg));
}
public ICollection<Type> GetGenericTypesOfWithBaseTypes(Type type, Type paramType)
{
var constructedTypes = new List<Type>();
//loop through all interfaces of the paramType, constructing a generic type for each.
foreach (var interfaceType in paramType.GetInterfaces())
{
var constructedTypeWithInterfaceArg = GetGenericTypeOf(type, interfaceType);
constructedTypes.Add(constructedTypeWithInterfaceArg);
}
//travel up the chain of base types, constructing a generic type for each.
Type currentParamType = paramType;
while (currentParamType != null)
{
var constructedType = GetGenericTypeOf(type, currentParamType);
constructedTypes.Add(constructedType);
currentParamType = currentParamType.BaseType;
}
return constructedTypes;
}
public void InvokeConsume(object consumer, object msg)
{
try
{
Type type = consumer.GetType();
MethodInfo consume = type.GetMethod("Consume", new[] { msg.GetType() });
consume.Invoke(consumer, new[] { msg });
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public object InvokeSagaPersisterGet(object persister, Guid correlationId)
{
try
{
Type type = persister.GetType();
MethodInfo method = type.GetMethod("Get");
return method.Invoke(persister, new object[] {correlationId});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public void InvokeSagaPersisterSave(object persister, object entity)
{
try
{
Type type = persister.GetType();
MethodInfo method = type.GetMethod("Save");
method.Invoke(persister, new object[] {entity});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public void InvokeSagaPersisterComplete(object persister, object entity)
{
try
{
Type type = persister.GetType();
MethodInfo method = type.GetMethod("Complete");
method.Invoke(persister, new object[] {entity});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public object InvokeSagaFinderFindBy(object sagaFinder, object msg)
{
try
{
Type type = sagaFinder.GetType();
MethodInfo method = type.GetMethod("FindBy", new[] { msg.GetType()} );
return method.Invoke(sagaFinder, new object[] { msg });
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public string GetNameForXml(Type type)
{
var typeName = type.Name;
typeName = typeName.Replace('[', '_').Replace(']', '_');
var indexOf = typeName.IndexOf('`');
if (indexOf == -1)
return typeName;
typeName = typeName.Substring(0, indexOf) + "_of_";
foreach (var argument in type.GetGenericArguments())
{
typeName += GetNamespacePrefixForXml(argument) + "_";
}
return typeName.Substring(0, typeName.Length - 1);
}
public string GetNamespacePrefixForXml(Type type)
{
string value;
if(typeToWellKnownTypeName.TryGetValue(type, out value))
return value;
if (type.IsArray)
return "array_of_" + GetNamespacePrefixForXml(type.GetElementType());
if (type.Namespace == null && type.Name.StartsWith("<>"))
throw new InvalidOperationException("Anonymous types are not supported");
if (type.Namespace == null) //global types?
{
return type.Name
.ToLowerInvariant();
}
var typeName = type.Namespace.Split('.')
.Last().ToLowerInvariant() + "." + type.Name.ToLowerInvariant();
var indexOf = typeName.IndexOf('`');
if (indexOf == -1)
return typeName;
typeName = typeName.Substring(0, indexOf)+ "_of_";
foreach (var argument in type.GetGenericArguments())
{
typeName += GetNamespacePrefixForXml(argument) + "_";
}
return typeName.Substring(0,typeName.Length-1);
}
public string GetNamespaceForXml(Type type)
{
string value;
if (typeToWellKnownTypeName.TryGetValue(type, out value))
return value;
Assembly assembly = type.Assembly;
string fullName = assembly.FullName ?? assembly.GetName().Name;
if (type.IsGenericType)
{
var builder = new StringBuilder();
int startOfGenericName = type.FullName.IndexOf('[');
builder.Append(type.FullName.Substring(0, startOfGenericName))
.Append("[")
.Append(String.Join(",",
type.GetGenericArguments()
.Select(t => "[" + GetNamespaceForXml(t) + "]")
.ToArray()))
.Append("], ");
if (assembly.GlobalAssemblyCache)
{
builder.Append(fullName);
}
else
{
builder.Append(fullName.Split(',')[0]);
}
return builder.ToString();
}
if (assembly.GlobalAssemblyCache == false)
{
return type.FullName + ", " + fullName.Split(',')[0];
}
return type.AssemblyQualifiedName;
}
public IEnumerable<string> GetProperties(object value)
{
return value.GetType().GetProperties()
.Select(x => x.Name);
}
public Type[] GetMessagesConsumed(IMessageConsumer consumer)
{
Type consumerType = consumer.GetType();
return GetMessagesConsumed(consumerType, type => false);
}
public Type[] GetMessagesConsumed(Type consumerType, Predicate<Type> filter)
{
var list = new HashSet<Type>();
var toRemove = new HashSet<Type>();
Type[] interfaces = consumerType.GetInterfaces();
foreach (Type type in interfaces)
{
if (type.IsGenericType == false)
continue;
if(type.GetGenericArguments()[0].IsGenericParameter)
continue;
Type definition = type.GetGenericTypeDefinition();
if (filter(definition))
{
toRemove.Add(type.GetGenericArguments()[0]);
continue;
}
if (definition != typeof (ConsumerOf<>))
continue;
list.Add(type.GetGenericArguments()[0]);
}
list.ExceptWith(toRemove);
return list.ToArray();
}
public virtual Type GetUnproxiedType(object instance)
{
// default to not understanding proxies
return instance.GetType();
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// ItemAssignmentResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Numbers.V2.RegulatoryCompliance.Bundle
{
public class ItemAssignmentResource : Resource
{
private static Request BuildCreateRequest(CreateItemAssignmentOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Numbers,
"/v2/RegulatoryCompliance/Bundles/" + options.PathBundleSid + "/ItemAssignments",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a new Assigned Item.
/// </summary>
/// <param name="options"> Create ItemAssignment parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ItemAssignment </returns>
public static ItemAssignmentResource Create(CreateItemAssignmentOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a new Assigned Item.
/// </summary>
/// <param name="options"> Create ItemAssignment parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ItemAssignment </returns>
public static async System.Threading.Tasks.Task<ItemAssignmentResource> CreateAsync(CreateItemAssignmentOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a new Assigned Item.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource. </param>
/// <param name="objectSid"> The sid of an object bag </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ItemAssignment </returns>
public static ItemAssignmentResource Create(string pathBundleSid, string objectSid, ITwilioRestClient client = null)
{
var options = new CreateItemAssignmentOptions(pathBundleSid, objectSid);
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a new Assigned Item.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource. </param>
/// <param name="objectSid"> The sid of an object bag </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ItemAssignment </returns>
public static async System.Threading.Tasks.Task<ItemAssignmentResource> CreateAsync(string pathBundleSid,
string objectSid,
ITwilioRestClient client = null)
{
var options = new CreateItemAssignmentOptions(pathBundleSid, objectSid);
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadItemAssignmentOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Numbers,
"/v2/RegulatoryCompliance/Bundles/" + options.PathBundleSid + "/ItemAssignments",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Assigned Items for an account.
/// </summary>
/// <param name="options"> Read ItemAssignment parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ItemAssignment </returns>
public static ResourceSet<ItemAssignmentResource> Read(ReadItemAssignmentOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<ItemAssignmentResource>.FromJson("results", response.Content);
return new ResourceSet<ItemAssignmentResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Assigned Items for an account.
/// </summary>
/// <param name="options"> Read ItemAssignment parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ItemAssignment </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ItemAssignmentResource>> ReadAsync(ReadItemAssignmentOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<ItemAssignmentResource>.FromJson("results", response.Content);
return new ResourceSet<ItemAssignmentResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Assigned Items for an account.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource. </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ItemAssignment </returns>
public static ResourceSet<ItemAssignmentResource> Read(string pathBundleSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadItemAssignmentOptions(pathBundleSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Assigned Items for an account.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource. </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ItemAssignment </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ItemAssignmentResource>> ReadAsync(string pathBundleSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadItemAssignmentOptions(pathBundleSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<ItemAssignmentResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<ItemAssignmentResource>.FromJson("results", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<ItemAssignmentResource> NextPage(Page<ItemAssignmentResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Numbers)
);
var response = client.Request(request);
return Page<ItemAssignmentResource>.FromJson("results", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<ItemAssignmentResource> PreviousPage(Page<ItemAssignmentResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Numbers)
);
var response = client.Request(request);
return Page<ItemAssignmentResource>.FromJson("results", response.Content);
}
private static Request BuildFetchRequest(FetchItemAssignmentOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Numbers,
"/v2/RegulatoryCompliance/Bundles/" + options.PathBundleSid + "/ItemAssignments/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch specific Assigned Item Instance.
/// </summary>
/// <param name="options"> Fetch ItemAssignment parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ItemAssignment </returns>
public static ItemAssignmentResource Fetch(FetchItemAssignmentOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch specific Assigned Item Instance.
/// </summary>
/// <param name="options"> Fetch ItemAssignment parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ItemAssignment </returns>
public static async System.Threading.Tasks.Task<ItemAssignmentResource> FetchAsync(FetchItemAssignmentOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch specific Assigned Item Instance.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource. </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ItemAssignment </returns>
public static ItemAssignmentResource Fetch(string pathBundleSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchItemAssignmentOptions(pathBundleSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch specific Assigned Item Instance.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource. </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ItemAssignment </returns>
public static async System.Threading.Tasks.Task<ItemAssignmentResource> FetchAsync(string pathBundleSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchItemAssignmentOptions(pathBundleSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteItemAssignmentOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Numbers,
"/v2/RegulatoryCompliance/Bundles/" + options.PathBundleSid + "/ItemAssignments/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Remove an Assignment Item Instance.
/// </summary>
/// <param name="options"> Delete ItemAssignment parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ItemAssignment </returns>
public static bool Delete(DeleteItemAssignmentOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// Remove an Assignment Item Instance.
/// </summary>
/// <param name="options"> Delete ItemAssignment parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ItemAssignment </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteItemAssignmentOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// Remove an Assignment Item Instance.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource. </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ItemAssignment </returns>
public static bool Delete(string pathBundleSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteItemAssignmentOptions(pathBundleSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Remove an Assignment Item Instance.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource. </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ItemAssignment </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathBundleSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteItemAssignmentOptions(pathBundleSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a ItemAssignmentResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> ItemAssignmentResource object represented by the provided JSON </returns>
public static ItemAssignmentResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<ItemAssignmentResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The unique string that identifies the Bundle resource.
/// </summary>
[JsonProperty("bundle_sid")]
public string BundleSid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The sid of an object bag
/// </summary>
[JsonProperty("object_sid")]
public string ObjectSid { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The absolute URL of the Identity resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private ItemAssignmentResource()
{
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.UserModel
{
using System;
using NPOI.SS.UserModel;
using NPOI.DDF;
using NPOI.HSSF.Record;
using System.IO;
using NPOI.Util;
/// <summary>
/// An abstract shape.
/// @author Glen Stampoultzis (glens at apache.org)
/// </summary>
[Serializable]
public abstract class HSSFShape //: IShape
{
public const int LINEWIDTH_ONE_PT = 12700; // 12700 = 1pt
public const int LINEWIDTH_DEFAULT = 9525;
public const int LINESTYLE__COLOR_DEFAULT = 0x08000040;
public const int FILL__FILLCOLOR_DEFAULT = 0x08000009;
public const bool NO_FILL_DEFAULT = true;
public const int LINESTYLE_SOLID = 0; // Solid (continuous) pen
public const int LINESTYLE_DASHSYS = 1; // PS_DASH system dash style
public const int LINESTYLE_DOTSYS = 2; // PS_DOT system dash style
public const int LINESTYLE_DASHDOTSYS = 3; // PS_DASHDOT system dash style
public const int LINESTYLE_DASHDOTDOTSYS = 4; // PS_DASHDOTDOT system dash style
public const int LINESTYLE_DOTGEL = 5; // square dot style
public const int LINESTYLE_DASHGEL = 6; // dash style
public const int LINESTYLE_LONGDASHGEL = 7; // long dash style
public const int LINESTYLE_DASHDOTGEL = 8; // dash short dash
public const int LINESTYLE_LONGDASHDOTGEL = 9; // long dash short dash
public const int LINESTYLE_LONGDASHDOTDOTGEL = 10; // long dash short dash short dash
public const int LINESTYLE_NONE = -1;
public const int LINESTYLE_DEFAULT = LINESTYLE_NONE;
public const int NO_FILLHITTEST_TRUE = 0x00110000;
public const int NO_FILLHITTEST_FALSE = 0x00010000;
HSSFShape parent;
[NonSerialized]
protected HSSFAnchor anchor;
[NonSerialized]
protected internal HSSFPatriarch _patriarch;
private EscherContainerRecord _escherContainer;
private ObjRecord _objRecord;
private EscherOptRecord _optRecord;
int lineStyleColor = 0x08000040;
int fillColor = 0x08000009;
int lineWidth = LINEWIDTH_DEFAULT;
LineStyle lineStyle = LineStyle.Solid;
bool noFill = false;
/**
* creates shapes from existing file
* @param spContainer
* @param objRecord
*/
public HSSFShape(EscherContainerRecord spContainer, ObjRecord objRecord)
{
this._escherContainer = spContainer;
this._objRecord = objRecord;
this._optRecord = (EscherOptRecord)spContainer.GetChildById(EscherOptRecord.RECORD_ID);
this.anchor = HSSFAnchor.CreateAnchorFromEscher(spContainer);
}
/// <summary>
/// Create a new shape with the specified parent and anchor.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="anchor">The anchor.</param>
public HSSFShape(HSSFShape parent, HSSFAnchor anchor)
{
this.parent = parent;
this.anchor = anchor;
this._escherContainer = CreateSpContainer();
_optRecord = (EscherOptRecord)_escherContainer.GetChildById(EscherOptRecord.RECORD_ID);
_objRecord = CreateObjRecord();
}
protected abstract EscherContainerRecord CreateSpContainer();
protected abstract ObjRecord CreateObjRecord();
internal abstract void AfterRemove(HSSFPatriarch patriarch);
internal abstract void AfterInsert(HSSFPatriarch patriarch);
public virtual int ShapeId
{
get
{
return ((EscherSpRecord)_escherContainer.GetChildById(EscherSpRecord.RECORD_ID)).ShapeId;
}
set
{
EscherSpRecord spRecord = (EscherSpRecord)_escherContainer.GetChildById(EscherSpRecord.RECORD_ID);
spRecord.ShapeId = value;
CommonObjectDataSubRecord cod = (CommonObjectDataSubRecord)_objRecord.SubRecords[0];
cod.ObjectId = (short)(value % 1024);
}
}
/// <summary>
/// Gets the parent shape.
/// </summary>
/// <value>The parent.</value>
public HSSFShape Parent
{
get { return this.parent; }
set { this.parent = value; }
}
/// <summary>
/// Gets or sets the anchor that is used by this shape.
/// </summary>
/// <value>The anchor.</value>
public HSSFAnchor Anchor
{
get { return anchor; }
set
{
int i = 0;
int recordId = -1;
if (parent == null)
{
if (value is HSSFChildAnchor)
throw new ArgumentException("Must use client anchors for shapes directly attached to sheet.");
EscherClientAnchorRecord anch = (EscherClientAnchorRecord)_escherContainer.GetChildById(EscherClientAnchorRecord.RECORD_ID);
if (null != anch)
{
for (i = 0; i < _escherContainer.ChildRecords.Count; i++)
{
if (_escherContainer.GetChild(i).RecordId == EscherClientAnchorRecord.RECORD_ID)
{
if (i != _escherContainer.ChildRecords.Count - 1)
{
recordId = _escherContainer.GetChild(i + 1).RecordId;
}
}
}
_escherContainer.RemoveChildRecord(anch);
}
}
else
{
if (value is HSSFClientAnchor)
throw new ArgumentException("Must use child anchors for shapes attached to Groups.");
EscherChildAnchorRecord anch = (EscherChildAnchorRecord)_escherContainer.GetChildById(EscherChildAnchorRecord.RECORD_ID);
if (null != anch)
{
for (i = 0; i < _escherContainer.ChildRecords.Count; i++)
{
if (_escherContainer.GetChild(i).RecordId == EscherChildAnchorRecord.RECORD_ID)
{
if (i != _escherContainer.ChildRecords.Count - 1)
{
recordId = _escherContainer.GetChild(i + 1).RecordId;
}
}
}
_escherContainer.RemoveChildRecord(anch);
}
}
if (-1 == recordId)
{
_escherContainer.AddChildRecord(value.GetEscherAnchor());
}
else
{
_escherContainer.AddChildBefore(value.GetEscherAnchor(), recordId);
}
this.anchor = value;
}
}
//public void SetLineStyleColor(int lineStyleColor)
//{
// this.lineStyleColor = lineStyleColor;
//}
/// <summary>
/// The color applied to the lines of this shape.
/// </summary>
/// <value>The color of the line style.</value>
public int LineStyleColor
{
get
{
//return lineStyleColor;
EscherRGBProperty rgbProperty = (EscherRGBProperty)_optRecord.Lookup(EscherProperties.LINESTYLE__COLOR);
return rgbProperty == null ? LINESTYLE__COLOR_DEFAULT : rgbProperty.RgbColor;
}
set
{
SetPropertyValue(new EscherRGBProperty(EscherProperties.LINESTYLE__COLOR, value));
}
}
internal EscherContainerRecord GetEscherContainer()
{
return _escherContainer;
}
/// <summary>
/// Sets the color applied to the lines of this shape
/// </summary>
/// <param name="red">The red.</param>
/// <param name="green">The green.</param>
/// <param name="blue">The blue.</param>
public void SetLineStyleColor(int red, int green, int blue)
{
int lineStyleColor = ((blue) << 16) | ((green) << 8) | red;
SetPropertyValue(new EscherRGBProperty(EscherProperties.LINESTYLE__COLOR, lineStyleColor));
}
protected void SetPropertyValue(EscherProperty property)
{
_optRecord.SetEscherProperty(property);
}
/// <summary>
/// Gets or sets the color used to fill this shape.
/// </summary>
/// <value>The color of the fill.</value>
public int FillColor
{
get
{
EscherRGBProperty rgbProperty = (EscherRGBProperty)_optRecord.Lookup(EscherProperties.FILL__FILLCOLOR);
return rgbProperty == null ? FILL__FILLCOLOR_DEFAULT : rgbProperty.RgbColor;
}
set
{
SetPropertyValue(new EscherRGBProperty(EscherProperties.FILL__FILLCOLOR, value));
}
}
/// <summary>
/// Sets the color used to fill this shape.
/// </summary>
/// <param name="red">The red.</param>
/// <param name="green">The green.</param>
/// <param name="blue">The blue.</param>
public void SetFillColor(int red, int green, int blue)
{
int fillColor = ((blue) << 16) | ((green) << 8) | red;
SetPropertyValue(new EscherRGBProperty(EscherProperties.FILL__FILLCOLOR, fillColor));
}
/// <summary>
/// Gets or sets with width of the line in EMUs. 12700 = 1 pt.
/// </summary>
/// <value>The width of the line.</value>
public int LineWidth
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)_optRecord.Lookup(EscherProperties.LINESTYLE__LINEWIDTH);
return property == null ? LINEWIDTH_DEFAULT : property.PropertyValue;
}
set
{
SetPropertyValue(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEWIDTH, value));
}
}
/// <summary>
/// Gets or sets One of the constants in LINESTYLE_*
/// </summary>
/// <value>The line style.</value>
public LineStyle LineStyle
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)_optRecord.Lookup(EscherProperties.LINESTYLE__LINEDASHING);
if (null == property)
{
return (LineStyle)LINESTYLE_DEFAULT;
}
return (LineStyle)property.PropertyValue;
}
set
{
SetPropertyValue(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEDASHING, (int)value));
if ((int)LineStyle != HSSFShape.LINESTYLE_SOLID)
{
SetPropertyValue(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEENDCAPSTYLE, 0));
if ((int)LineStyle == HSSFShape.LINESTYLE_NONE)
{
SetPropertyValue(new EscherBoolProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x00080000));
}
else
{
SetPropertyValue(new EscherBoolProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x00080008));
}
}
}
}
/// <summary>
/// Gets or sets a value indicating whether this instance is no fill.
/// </summary>
/// <value>
/// <c>true</c> if this shape Is not filled with a color; otherwise, <c>false</c>.
/// </value>
public bool IsNoFill
{
get
{
EscherBoolProperty property = (EscherBoolProperty)_optRecord.Lookup(EscherProperties.FILL__NOFILLHITTEST);
return property == null ? NO_FILL_DEFAULT : property.PropertyValue == NO_FILLHITTEST_TRUE;
}
set
{
SetPropertyValue(new EscherBoolProperty(EscherProperties.FILL__NOFILLHITTEST, value ? NO_FILLHITTEST_TRUE : NO_FILLHITTEST_FALSE));
}
}
/// <summary>
/// whether this shape is vertically flipped.
/// </summary>
public bool IsFlipVertical
{
get
{
EscherSpRecord sp = (EscherSpRecord)GetEscherContainer().GetChildById(EscherSpRecord.RECORD_ID);
return (sp.Flags & EscherSpRecord.FLAG_FLIPVERT) != 0;
}
set
{
EscherSpRecord sp = (EscherSpRecord)GetEscherContainer().GetChildById(EscherSpRecord.RECORD_ID);
if (value)
{
sp.Flags = (sp.Flags | EscherSpRecord.FLAG_FLIPVERT);
}
else
{
sp.Flags = (sp.Flags & (int.MaxValue - EscherSpRecord.FLAG_FLIPVERT));
}
}
}
/// <summary>
/// whether this shape is horizontally flipped.
/// </summary>
public bool IsFlipHorizontal
{
get
{
EscherSpRecord sp = (EscherSpRecord)GetEscherContainer().GetChildById(EscherSpRecord.RECORD_ID);
return (sp.Flags & EscherSpRecord.FLAG_FLIPHORIZ) != 0;
}
set
{
EscherSpRecord sp = (EscherSpRecord)GetEscherContainer().GetChildById(EscherSpRecord.RECORD_ID);
if (value)
{
sp.Flags=(sp.Flags | EscherSpRecord.FLAG_FLIPHORIZ);
}
else
{
sp.Flags=(sp.Flags & (int.MaxValue - EscherSpRecord.FLAG_FLIPHORIZ));
}
}
}
/**
* @return the rotation, in degrees, that is applied to a shape.
*/
//
/// <summary>
/// get or set the rotation, in degrees, that is applied to a shape.
/// Negative values specify rotation in the counterclockwise direction.
/// Rotation occurs around the center of the shape.
/// The default value for this property is 0x00000000
/// </summary>
public int RotationDegree
{
get
{
using (MemoryStream bos = new MemoryStream())
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.TRANSFORM__ROTATION);
if (null == property)
{
return 0;
}
try
{
LittleEndian.PutInt(property.PropertyValue, bos);
return LittleEndian.GetShort(bos.ToArray(), 2);
}
catch (IOException e)
{
//e.printStackTrace();
return 0;
}
}
}
set
{
SetPropertyValue(new EscherSimpleProperty(EscherProperties.TRANSFORM__ROTATION, (value << 16)));
}
}
/// <summary>
/// Count of all children and their childrens children.
/// </summary>
/// <value>The count of all children.</value>
public virtual int CountOfAllChildren
{
get { return 1; }
}
internal abstract HSSFShape CloneShape();
public HSSFPatriarch Patriarch
{
get
{
return _patriarch;
}
set
{
this._patriarch = value;
}
}
protected internal ObjRecord GetObjRecord()
{
return _objRecord;
}
protected internal EscherOptRecord GetOptRecord()
{
return _optRecord;
}
}
}
| |
using System;
using System.Diagnostics;
using UnityEngine;
[AddComponentMenu("NGUI/UI/NGUI Widget"), ExecuteInEditMode]
public class UIWidget : UIRect
{
public enum Pivot
{
TopLeft,
Top,
TopRight,
Left,
Center,
Right,
BottomLeft,
Bottom,
BottomRight
}
public enum AspectRatioSource
{
Free,
BasedOnWidth,
BasedOnHeight
}
public delegate void OnDimensionsChanged();
public delegate bool HitCheck(Vector3 worldPos);
[HideInInspector, SerializeField]
protected Color mColor = Color.white;
[HideInInspector, SerializeField]
protected UIWidget.Pivot mPivot = UIWidget.Pivot.Center;
[HideInInspector, SerializeField]
protected int mWidth = 100;
[HideInInspector, SerializeField]
protected int mHeight = 100;
[HideInInspector, SerializeField]
protected int mDepth;
public UIWidget.OnDimensionsChanged onChange;
public bool autoResizeBoxCollider;
public bool hideIfOffScreen;
public UIWidget.AspectRatioSource keepAspectRatio;
public float aspectRatio = 1f;
public UIWidget.HitCheck hitCheck;
[NonSerialized]
public UIPanel panel;
[NonSerialized]
public UIGeometry geometry = new UIGeometry();
[NonSerialized]
public bool fillGeometry = true;
protected bool mPlayMode = true;
protected Vector4 mDrawRegion = new Vector4(0f, 0f, 1f, 1f);
private Matrix4x4 mLocalToPanel;
private bool mIsVisibleByAlpha = true;
private bool mIsVisibleByPanel = true;
private bool mIsInFront = true;
private float mLastAlpha;
private bool mMoved;
[HideInInspector]
[NonSerialized]
public UIDrawCall drawCall;
protected Vector3[] mCorners = new Vector3[4];
private int mAlphaFrameID = -1;
private static Bounds tempZero = new Bounds(Vector3.zero, Vector3.zero);
protected UIWidget[] mspList;
protected GameObject moGo;
protected OnUIWidgetAtlasLoaded monLoaded;
protected OnUIWidgetAtlasAllLoaded monAllLoaded;
protected object[] margs;
private int mMatrixFrame = -1;
private Vector3 mOldV0;
private Vector3 mOldV1;
public Vector4 drawRegion
{
get
{
return this.mDrawRegion;
}
set
{
if (this.mDrawRegion != value)
{
this.mDrawRegion = value;
if (this.autoResizeBoxCollider)
{
this.ResizeCollider();
}
this.MarkAsChanged();
}
}
}
public Vector2 pivotOffset
{
get
{
return NGUIMath.GetPivotOffset(this.pivot);
}
}
public int width
{
get
{
return this.mWidth;
}
set
{
int minWidth = this.minWidth;
if (value < minWidth)
{
value = minWidth;
}
if (this.mWidth != value && this.keepAspectRatio != UIWidget.AspectRatioSource.BasedOnHeight)
{
if (this.isAnchoredHorizontally)
{
if (this.leftAnchor.target != null && this.rightAnchor.target != null)
{
if (this.mPivot == UIWidget.Pivot.BottomLeft || this.mPivot == UIWidget.Pivot.Left || this.mPivot == UIWidget.Pivot.TopLeft)
{
NGUIMath.AdjustWidget(this, 0f, 0f, (float)(value - this.mWidth), 0f);
}
else if (this.mPivot == UIWidget.Pivot.BottomRight || this.mPivot == UIWidget.Pivot.Right || this.mPivot == UIWidget.Pivot.TopRight)
{
NGUIMath.AdjustWidget(this, (float)(this.mWidth - value), 0f, 0f, 0f);
}
else
{
int num = value - this.mWidth;
num -= (num & 1);
if (num != 0)
{
NGUIMath.AdjustWidget(this, (float)(-(float)num) * 0.5f, 0f, (float)num * 0.5f, 0f);
}
}
}
else if (this.leftAnchor.target != null)
{
NGUIMath.AdjustWidget(this, 0f, 0f, (float)(value - this.mWidth), 0f);
}
else
{
NGUIMath.AdjustWidget(this, (float)(this.mWidth - value), 0f, 0f, 0f);
}
}
else
{
this.SetDimensions(value, this.mHeight);
}
}
}
}
public int height
{
get
{
return this.mHeight;
}
set
{
int minHeight = this.minHeight;
if (value < minHeight)
{
value = minHeight;
}
if (this.mHeight != value && this.keepAspectRatio != UIWidget.AspectRatioSource.BasedOnWidth)
{
if (this.isAnchoredVertically)
{
if (this.bottomAnchor.target != null && this.topAnchor.target != null)
{
if (this.mPivot == UIWidget.Pivot.BottomLeft || this.mPivot == UIWidget.Pivot.Bottom || this.mPivot == UIWidget.Pivot.BottomRight)
{
NGUIMath.AdjustWidget(this, 0f, 0f, 0f, (float)(value - this.mHeight));
}
else if (this.mPivot == UIWidget.Pivot.TopLeft || this.mPivot == UIWidget.Pivot.Top || this.mPivot == UIWidget.Pivot.TopRight)
{
NGUIMath.AdjustWidget(this, 0f, (float)(this.mHeight - value), 0f, 0f);
}
else
{
int num = value - this.mHeight;
num -= (num & 1);
if (num != 0)
{
NGUIMath.AdjustWidget(this, 0f, (float)(-(float)num) * 0.5f, 0f, (float)num * 0.5f);
}
}
}
else if (this.bottomAnchor.target != null)
{
NGUIMath.AdjustWidget(this, 0f, 0f, 0f, (float)(value - this.mHeight));
}
else
{
NGUIMath.AdjustWidget(this, 0f, (float)(this.mHeight - value), 0f, 0f);
}
}
else
{
this.SetDimensions(this.mWidth, value);
}
}
}
}
public Color color
{
get
{
return this.mColor;
}
set
{
if (this.mColor != value)
{
bool includeChildren = this.mColor.a != value.a;
this.mColor = value;
this.Invalidate(includeChildren);
}
}
}
public override float alpha
{
get
{
return this.mColor.a;
}
set
{
if (this.mColor.a != value)
{
this.mColor.a = value;
this.Invalidate(true);
}
}
}
public bool isVisible
{
get
{
return this.mIsVisibleByPanel && this.mIsVisibleByAlpha && this.mIsInFront && this.finalAlpha > 0.001f && NGUITools.GetActive(this);
}
}
public bool hasVertices
{
get
{
return this.geometry != null && this.geometry.hasVertices;
}
}
public UIWidget.Pivot rawPivot
{
get
{
return this.mPivot;
}
set
{
if (this.mPivot != value)
{
this.mPivot = value;
if (this.autoResizeBoxCollider)
{
this.ResizeCollider();
}
this.MarkAsChanged();
}
}
}
public UIWidget.Pivot pivot
{
get
{
return this.mPivot;
}
set
{
if (this.mPivot != value)
{
Vector3 vector = this.worldCorners[0];
this.mPivot = value;
this.mChanged = true;
Vector3 vector2 = this.worldCorners[0];
Transform cachedTransform = base.cachedTransform;
Vector3 vector3 = cachedTransform.position;
float z = cachedTransform.localPosition.z;
vector3.x += vector.x - vector2.x;
vector3.y += vector.y - vector2.y;
base.cachedTransform.position = vector3;
vector3 = base.cachedTransform.localPosition;
vector3.x = Mathf.Round(vector3.x);
vector3.y = Mathf.Round(vector3.y);
vector3.z = z;
base.cachedTransform.localPosition = vector3;
}
}
}
public int depth
{
get
{
return this.mDepth;
}
set
{
if (this.mDepth != value)
{
if (this.panel != null)
{
this.panel.RemoveWidget(this);
}
this.mDepth = value;
if (this.panel != null)
{
this.panel.AddWidget(this);
if (!Application.isPlaying)
{
this.panel.SortWidgets();
this.panel.RebuildAllDrawCalls();
}
}
}
}
}
public int raycastDepth
{
get
{
if (this.panel == null)
{
this.CreatePanel();
}
return (!(this.panel != null)) ? this.mDepth : (this.mDepth + this.panel.depth * 1000);
}
}
public override Vector3[] localCorners
{
get
{
Vector2 pivotOffset = this.pivotOffset;
float num = -pivotOffset.x * (float)this.mWidth;
float num2 = -pivotOffset.y * (float)this.mHeight;
float x = num + (float)this.mWidth;
float y = num2 + (float)this.mHeight;
Vector3 zero = Vector3.zero;
zero.x = num;
zero.y = num2;
this.mCorners[0] = zero;
zero.x = num;
zero.y = y;
this.mCorners[1] = zero;
zero.x = x;
zero.y = y;
this.mCorners[2] = zero;
zero.x = x;
zero.y = num2;
this.mCorners[3] = zero;
return this.mCorners;
}
}
public virtual Vector2 localSize
{
get
{
Vector3[] localCorners = this.localCorners;
return localCorners[2] - localCorners[0];
}
}
public override Vector3[] worldCorners
{
get
{
Vector2 pivotOffset = this.pivotOffset;
float num = -pivotOffset.x * (float)this.mWidth;
float num2 = -pivotOffset.y * (float)this.mHeight;
float x = num + (float)this.mWidth;
float y = num2 + (float)this.mHeight;
Transform cachedTransform = base.cachedTransform;
this.mCorners[0] = cachedTransform.TransformPoint(num, num2, 0f);
this.mCorners[1] = cachedTransform.TransformPoint(num, y, 0f);
this.mCorners[2] = cachedTransform.TransformPoint(x, y, 0f);
this.mCorners[3] = cachedTransform.TransformPoint(x, num2, 0f);
return this.mCorners;
}
}
public virtual Vector4 drawingDimensions
{
get
{
Vector2 pivotOffset = this.pivotOffset;
float num = -pivotOffset.x * (float)this.mWidth;
float num2 = -pivotOffset.y * (float)this.mHeight;
float num3 = num + (float)this.mWidth;
float num4 = num2 + (float)this.mHeight;
Vector4 zero = Vector4.zero;
zero.x = ((this.mDrawRegion.x != 0f) ? Mathf.Lerp(num, num3, this.mDrawRegion.x) : num);
zero.y = ((this.mDrawRegion.y != 0f) ? Mathf.Lerp(num2, num4, this.mDrawRegion.y) : num2);
zero.z = ((this.mDrawRegion.z != 1f) ? Mathf.Lerp(num, num3, this.mDrawRegion.z) : num3);
zero.w = ((this.mDrawRegion.w != 1f) ? Mathf.Lerp(num2, num4, this.mDrawRegion.w) : num4);
return zero;
}
}
public virtual Material material
{
get
{
return null;
}
set
{
throw new NotImplementedException(base.GetType() + " has no material setter");
}
}
public virtual Texture mainTexture
{
get
{
Material material = this.material;
return (!(material != null)) ? null : material.mainTexture;
}
set
{
throw new NotImplementedException(base.GetType() + " has no mainTexture setter");
}
}
public virtual Shader shader
{
get
{
Material material = this.material;
return (!(material != null)) ? null : material.shader;
}
set
{
throw new NotImplementedException(base.GetType() + " has no shader setter");
}
}
[Obsolete("There is no relative scale anymore. Widgets now have width and height instead")]
public Vector2 relativeSize
{
get
{
return Vector2.one;
}
}
public bool hasBoxCollider
{
get
{
BoxCollider x = base.collider as BoxCollider;
return x != null;
}
}
public virtual int minWidth
{
get
{
return 2;
}
}
public virtual int minHeight
{
get
{
return 2;
}
}
public virtual Vector4 border
{
get
{
return Vector4.zero;
}
}
public void SetDimensions(int w, int h)
{
if (this.mWidth != w || this.mHeight != h)
{
this.mWidth = w;
this.mHeight = h;
if (this.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnWidth)
{
this.mHeight = Mathf.RoundToInt((float)this.mWidth / this.aspectRatio);
}
else if (this.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnHeight)
{
this.mWidth = Mathf.RoundToInt((float)this.mHeight * this.aspectRatio);
}
else if (this.keepAspectRatio == UIWidget.AspectRatioSource.Free)
{
this.aspectRatio = (float)this.mWidth / (float)this.mHeight;
}
this.mMoved = true;
if (this.autoResizeBoxCollider)
{
this.ResizeCollider();
}
this.MarkAsChanged();
}
}
public override Vector3[] GetSides(Transform relativeTo)
{
Vector2 pivotOffset = this.pivotOffset;
float num = -pivotOffset.x * (float)this.mWidth;
float num2 = -pivotOffset.y * (float)this.mHeight;
float num3 = num + (float)this.mWidth;
float num4 = num2 + (float)this.mHeight;
float x = (num + num3) * 0.5f;
float y = (num2 + num4) * 0.5f;
Transform cachedTransform = base.cachedTransform;
this.mCorners[0] = cachedTransform.TransformPoint(num, y, 0f);
this.mCorners[1] = cachedTransform.TransformPoint(x, num4, 0f);
this.mCorners[2] = cachedTransform.TransformPoint(num3, y, 0f);
this.mCorners[3] = cachedTransform.TransformPoint(x, num2, 0f);
if (relativeTo != null)
{
for (int i = 0; i < 4; i++)
{
this.mCorners[i] = relativeTo.InverseTransformPoint(this.mCorners[i]);
}
}
return this.mCorners;
}
public override float CalculateFinalAlpha(int frameID)
{
if (this.mAlphaFrameID != frameID)
{
this.mAlphaFrameID = frameID;
this.UpdateFinalAlpha(frameID);
}
return this.finalAlpha;
}
protected void UpdateFinalAlpha(int frameID)
{
if (!this.mIsVisibleByAlpha || !this.mIsInFront)
{
this.finalAlpha = 0f;
}
else
{
UIRect parent = base.parent;
this.finalAlpha = ((!(base.parent != null)) ? this.mColor.a : (parent.CalculateFinalAlpha(frameID) * this.mColor.a));
}
}
public override void Invalidate(bool includeChildren)
{
this.mChanged = true;
this.mAlphaFrameID = -1;
if (this.panel != null)
{
bool visibleByPanel = (!this.hideIfOffScreen && !this.panel.clipsChildren) || this.panel.IsVisible(this);
this.UpdateVisibility(this.CalculateCumulativeAlpha(Time.frameCount) > 0.001f, visibleByPanel);
this.UpdateFinalAlpha(Time.frameCount);
if (includeChildren)
{
base.Invalidate(true);
}
}
}
public float CalculateCumulativeAlpha(int frameID)
{
UIRect parent = base.parent;
return (!(parent != null)) ? this.mColor.a : (parent.CalculateFinalAlpha(frameID) * this.mColor.a);
}
public void SetRect(float x, float y, float width, float height)
{
Vector2 pivotOffset = this.pivotOffset;
float num = Mathf.Lerp(x, x + width, pivotOffset.x);
float num2 = Mathf.Lerp(y, y + height, pivotOffset.y);
int num3 = Mathf.FloorToInt(width + 0.5f);
int num4 = Mathf.FloorToInt(height + 0.5f);
if (pivotOffset.x == 0.5f)
{
num3 = num3 >> 1 << 1;
}
if (pivotOffset.y == 0.5f)
{
num4 = num4 >> 1 << 1;
}
Transform transform = base.cachedTransform;
Vector3 localPosition = transform.localPosition;
localPosition.x = Mathf.Floor(num + 0.5f);
localPosition.y = Mathf.Floor(num2 + 0.5f);
if (num3 < this.minWidth)
{
num3 = this.minWidth;
}
if (num4 < this.minHeight)
{
num4 = this.minHeight;
}
transform.localPosition = localPosition;
this.width = num3;
this.height = num4;
if (base.isAnchored)
{
transform = transform.parent;
if (this.leftAnchor.target)
{
this.leftAnchor.SetHorizontal(transform, x);
}
if (this.rightAnchor.target)
{
this.rightAnchor.SetHorizontal(transform, x + width);
}
if (this.bottomAnchor.target)
{
this.bottomAnchor.SetVertical(transform, y);
}
if (this.topAnchor.target)
{
this.topAnchor.SetVertical(transform, y + height);
}
}
}
public void ResizeCollider()
{
if (NGUITools.GetActive(this))
{
BoxCollider boxCollider = base.collider as BoxCollider;
if (boxCollider != null)
{
NGUITools.UpdateWidgetCollider(boxCollider, true);
}
}
}
[DebuggerHidden, DebuggerStepThrough]
public static int FullCompareFunc(UIWidget left, UIWidget right)
{
int num = UIPanel.CompareFunc(left.panel, right.panel);
return (num != 0) ? num : UIWidget.PanelCompareFunc(left, right);
}
[DebuggerHidden, DebuggerStepThrough]
public static int PanelCompareFunc(UIWidget left, UIWidget right)
{
if (left.mDepth < right.mDepth)
{
return -1;
}
if (left.mDepth > right.mDepth)
{
return 1;
}
Material material = left.material;
Material material2 = right.material;
if (material == material2)
{
return 0;
}
if (material != null)
{
return -1;
}
if (material2 != null)
{
return 1;
}
return (material.GetInstanceID() >= material2.GetInstanceID()) ? 1 : -1;
}
public Bounds CalculateBounds()
{
return this.CalculateBounds(null);
}
public Bounds CalculateBounds(Transform relativeParent)
{
if (relativeParent == null)
{
Vector3[] localCorners = this.localCorners;
Bounds result = UIWidget.tempZero;
result.center = localCorners[0];
result.size = Vector3.zero;
for (int i = 1; i < 4; i++)
{
result.Encapsulate(localCorners[i]);
}
return result;
}
Matrix4x4 worldToLocalMatrix = relativeParent.worldToLocalMatrix;
Vector3[] worldCorners = this.worldCorners;
Bounds result2 = UIWidget.tempZero;
result2.center = worldToLocalMatrix.MultiplyPoint3x4(worldCorners[0]);
result2.size = Vector3.zero;
for (int j = 1; j < 4; j++)
{
result2.Encapsulate(worldToLocalMatrix.MultiplyPoint3x4(worldCorners[j]));
}
return result2;
}
public void SetDirty()
{
if (this.drawCall != null)
{
this.drawCall.isDirty = true;
}
else if (this.isVisible && this.hasVertices)
{
this.CreatePanel();
}
}
protected void RemoveFromPanel()
{
if (this.panel != null)
{
this.panel.RemoveWidget(this);
this.panel = null;
}
}
public virtual void MarkAsChanged()
{
if (NGUITools.GetActive(this))
{
this.mChanged = true;
if (this.panel != null && base.enabled && NGUITools.GetActive(base.gameObject) && !this.mPlayMode)
{
this.SetDirty();
this.CheckLayer();
}
}
}
public UIPanel CreatePanel()
{
if (this.mStarted && this.panel == null && base.enabled && NGUITools.GetActive(base.gameObject))
{
this.panel = UIPanel.Find(base.cachedTransform, true, base.cachedGameObject.layer);
if (this.panel != null)
{
this.mParentFound = false;
this.panel.AddWidget(this);
this.CheckLayer();
this.Invalidate(true);
}
}
return this.panel;
}
public void CheckLayer()
{
if (this.panel != null && this.panel.gameObject.layer != base.gameObject.layer)
{
LogSystem.LogWarning(new object[]
{
"You can't place widgets on a layer different than the UIPanel that manages them.\n",
"If you want to move widgets to a different layer, parent them to a new panel instead.",
this
});
base.gameObject.layer = this.panel.gameObject.layer;
}
}
public override void ParentHasChanged()
{
base.ParentHasChanged();
if (this.panel != null)
{
UIPanel y = UIPanel.Find(base.cachedTransform, true, base.cachedGameObject.layer);
if (this.panel != y)
{
this.RemoveFromPanel();
this.CreatePanel();
}
}
}
protected virtual void Awake()
{
this.mGo = base.gameObject;
this.mPlayMode = Application.isPlaying;
if (this is UILabel || this is UINumLabel)
{
UILabel uILabel = this as UILabel;
if (uILabel != null)
{
uILabel.ChangeFont();
}
}
}
protected override void OnInit()
{
base.OnInit();
this.RemoveFromPanel();
this.mMoved = true;
if (this.mWidth == 100 && this.mHeight == 100 && base.cachedTransform.localScale.magnitude > 8f)
{
this.UpgradeFrom265();
base.cachedTransform.localScale = Vector3.one;
}
base.Update();
}
protected virtual void UpgradeFrom265()
{
Vector3 localScale = base.cachedTransform.localScale;
this.mWidth = Mathf.Abs(Mathf.RoundToInt(localScale.x));
this.mHeight = Mathf.Abs(Mathf.RoundToInt(localScale.y));
if (base.GetComponent<BoxCollider>() != null)
{
NGUITools.AddWidgetCollider(base.gameObject, true);
}
}
protected override void OnStart()
{
this.CreatePanel();
}
protected override void OnAnchor()
{
Transform cachedTransform = base.cachedTransform;
Transform parent = cachedTransform.parent;
Vector3 localPosition = cachedTransform.localPosition;
Vector2 pivotOffset = this.pivotOffset;
float num;
float num2;
float num3;
float num4;
if (this.leftAnchor.target == this.bottomAnchor.target && this.leftAnchor.target == this.rightAnchor.target && this.leftAnchor.target == this.topAnchor.target)
{
Vector3[] sides = this.leftAnchor.GetSides(parent);
if (sides != null)
{
num = NGUIMath.Lerp(sides[0].x, sides[2].x, this.leftAnchor.relative) + (float)this.leftAnchor.absolute;
num2 = NGUIMath.Lerp(sides[0].x, sides[2].x, this.rightAnchor.relative) + (float)this.rightAnchor.absolute;
num3 = NGUIMath.Lerp(sides[3].y, sides[1].y, this.bottomAnchor.relative) + (float)this.bottomAnchor.absolute;
num4 = NGUIMath.Lerp(sides[3].y, sides[1].y, this.topAnchor.relative) + (float)this.topAnchor.absolute;
this.mIsInFront = true;
}
else
{
Vector3 localPos = base.GetLocalPos(this.leftAnchor, parent);
num = localPos.x + (float)this.leftAnchor.absolute;
num3 = localPos.y + (float)this.bottomAnchor.absolute;
num2 = localPos.x + (float)this.rightAnchor.absolute;
num4 = localPos.y + (float)this.topAnchor.absolute;
this.mIsInFront = (!this.hideIfOffScreen || localPos.z >= 0f);
}
}
else
{
this.mIsInFront = true;
if (this.leftAnchor.target)
{
Vector3[] sides2 = this.leftAnchor.GetSides(parent);
if (sides2 != null)
{
num = NGUIMath.Lerp(sides2[0].x, sides2[2].x, this.leftAnchor.relative) + (float)this.leftAnchor.absolute;
}
else
{
num = base.GetLocalPos(this.leftAnchor, parent).x + (float)this.leftAnchor.absolute;
}
}
else
{
num = localPosition.x - pivotOffset.x * (float)this.mWidth;
}
if (this.rightAnchor.target)
{
Vector3[] sides3 = this.rightAnchor.GetSides(parent);
if (sides3 != null)
{
num2 = NGUIMath.Lerp(sides3[0].x, sides3[2].x, this.rightAnchor.relative) + (float)this.rightAnchor.absolute;
}
else
{
num2 = base.GetLocalPos(this.rightAnchor, parent).x + (float)this.rightAnchor.absolute;
}
}
else
{
num2 = localPosition.x - pivotOffset.x * (float)this.mWidth + (float)this.mWidth;
}
if (this.bottomAnchor.target)
{
Vector3[] sides4 = this.bottomAnchor.GetSides(parent);
if (sides4 != null)
{
num3 = NGUIMath.Lerp(sides4[3].y, sides4[1].y, this.bottomAnchor.relative) + (float)this.bottomAnchor.absolute;
}
else
{
num3 = base.GetLocalPos(this.bottomAnchor, parent).y + (float)this.bottomAnchor.absolute;
}
}
else
{
num3 = localPosition.y - pivotOffset.y * (float)this.mHeight;
}
if (this.topAnchor.target)
{
Vector3[] sides5 = this.topAnchor.GetSides(parent);
if (sides5 != null)
{
num4 = NGUIMath.Lerp(sides5[3].y, sides5[1].y, this.topAnchor.relative) + (float)this.topAnchor.absolute;
}
else
{
num4 = base.GetLocalPos(this.topAnchor, parent).y + (float)this.topAnchor.absolute;
}
}
else
{
num4 = localPosition.y - pivotOffset.y * (float)this.mHeight + (float)this.mHeight;
}
}
Vector3 zero = Vector3.zero;
zero.x = Mathf.Lerp(num, num2, pivotOffset.x);
zero.y = Mathf.Lerp(num3, num4, pivotOffset.y);
zero.z = localPosition.z;
int num5 = Mathf.FloorToInt(num2 - num + 0.5f);
int num6 = Mathf.FloorToInt(num4 - num3 + 0.5f);
if (this.keepAspectRatio != UIWidget.AspectRatioSource.Free && this.aspectRatio != 0f)
{
if (this.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnHeight)
{
num5 = Mathf.RoundToInt((float)num6 * this.aspectRatio);
}
else
{
num6 = Mathf.RoundToInt((float)num5 / this.aspectRatio);
}
}
if (num5 < this.minWidth)
{
num5 = this.minWidth;
}
if (num6 < this.minHeight)
{
num6 = this.minHeight;
}
if (Vector3.SqrMagnitude(localPosition - zero) > 0.001f)
{
base.cachedTransform.localPosition = zero;
if (this.mIsInFront)
{
this.mChanged = true;
}
}
if (this.mWidth != num5 || this.mHeight != num6)
{
this.mWidth = num5;
this.mHeight = num6;
if (this.mIsInFront)
{
this.mChanged = true;
}
if (this.autoResizeBoxCollider)
{
this.ResizeCollider();
}
}
}
protected override void OnUpdate()
{
if (this.panel == null)
{
this.CreatePanel();
}
}
private void OnApplicationPause(bool paused)
{
if (!paused)
{
this.MarkAsChanged();
}
}
protected override void OnDisable()
{
this.RemoveFromPanel();
base.OnDisable();
}
public virtual bool CheckLoadAtlas(OnUIWidgetAtlasLoaded onLoaded, UIWidget[] spList, OnUIWidgetAtlasAllLoaded onAllLoaded, GameObject oGo, params object[] args)
{
return false;
}
public virtual bool CheckWaitLoadingAtlas()
{
return false;
}
public void ClearWidgetLoadInfo()
{
this.mspList = null;
this.moGo = null;
this.monLoaded = null;
this.monAllLoaded = null;
this.margs = null;
}
private void OnDestroy()
{
this.RemoveFromPanel();
}
public bool UpdateVisibility(bool visibleByAlpha, bool visibleByPanel)
{
if (this.mIsVisibleByAlpha != visibleByAlpha || this.mIsVisibleByPanel != visibleByPanel)
{
this.mChanged = true;
this.mIsVisibleByAlpha = visibleByAlpha;
this.mIsVisibleByPanel = visibleByPanel;
return true;
}
return false;
}
public bool UpdateTransform(int frame)
{
if (!this.mMoved && !this.panel.widgetsAreStatic && base.cachedTransform.hasChanged)
{
this.mTrans.hasChanged = false;
this.mLocalToPanel = this.panel.worldToLocal * base.cachedTransform.localToWorldMatrix;
this.mMatrixFrame = frame;
Vector2 pivotOffset = this.pivotOffset;
float num = -pivotOffset.x * (float)this.mWidth;
float num2 = -pivotOffset.y * (float)this.mHeight;
float x = num + (float)this.mWidth;
float y = num2 + (float)this.mHeight;
Transform cachedTransform = base.cachedTransform;
Vector3 vector = cachedTransform.TransformPoint(num, num2, 0f);
Vector3 vector2 = cachedTransform.TransformPoint(x, y, 0f);
vector = this.panel.worldToLocal.MultiplyPoint3x4(vector);
vector2 = this.panel.worldToLocal.MultiplyPoint3x4(vector2);
if (Vector3.SqrMagnitude(this.mOldV0 - vector) > 1E-06f || Vector3.SqrMagnitude(this.mOldV1 - vector2) > 1E-06f)
{
this.mMoved = true;
this.mOldV0 = vector;
this.mOldV1 = vector2;
}
}
if (this.mMoved && this.onChange != null)
{
this.onChange();
}
return this.mMoved || this.mChanged;
}
public bool UpdateGeometry(int frame)
{
float num = this.CalculateFinalAlpha(frame);
if (this.mIsVisibleByAlpha && this.mLastAlpha != num)
{
this.mChanged = true;
}
this.mLastAlpha = num;
if (this.mChanged)
{
this.mChanged = false;
if (this.mIsVisibleByAlpha && num > 0.001f && this.shader != null)
{
bool hasVertices = this.geometry.hasVertices;
if (this.fillGeometry)
{
this.geometry.Clear();
this.OnFill(this.geometry.verts, this.geometry.uvs, this.geometry.cols);
}
if (this.geometry.hasVertices)
{
if (this.mMatrixFrame != frame)
{
this.mLocalToPanel = this.panel.worldToLocal * base.cachedTransform.localToWorldMatrix;
this.mMatrixFrame = frame;
}
this.geometry.ApplyTransform(this.mLocalToPanel);
this.mMoved = false;
return true;
}
return hasVertices;
}
else if (this.geometry.hasVertices)
{
if (this.fillGeometry)
{
this.geometry.Clear();
}
this.mMoved = false;
return true;
}
}
else if (this.mMoved && this.geometry.hasVertices)
{
if (this.mMatrixFrame != frame)
{
this.mLocalToPanel = this.panel.worldToLocal * base.cachedTransform.localToWorldMatrix;
this.mMatrixFrame = frame;
}
this.geometry.ApplyTransform(this.mLocalToPanel);
this.mMoved = false;
return true;
}
this.mMoved = false;
return false;
}
public void WriteToBuffers(BetterList<Vector3> v, BetterList<Vector2> u, BetterList<Color32> c, BetterList<Vector3> n, BetterList<Vector4> t)
{
this.geometry.WriteToBuffers(v, u, c, n, t);
}
public virtual void MakePixelPerfect()
{
Vector3 localPosition = base.cachedTransform.localPosition;
localPosition.z = Mathf.Round(localPosition.z);
localPosition.x = Mathf.Round(localPosition.x);
localPosition.y = Mathf.Round(localPosition.y);
base.cachedTransform.localPosition = localPosition;
Vector3 localScale = base.cachedTransform.localScale;
Vector3 zero = Vector3.zero;
zero.x = Mathf.Sign(localScale.x);
zero.y = Mathf.Sign(localScale.y);
zero.z = 1f;
base.cachedTransform.localScale = zero;
}
public virtual void OnFill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Collections.Generic;
using System.Drawing;
namespace DotSpatial.Data
{
/// <summary>
/// ImageData (not named Image because of conflicting with the Dot Net Image object).
/// </summary>
public class ImageData : RasterBoundDataSet, IImageData
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ImageData"/> class.
/// </summary>
public ImageData()
{
WorldFile = new WorldFile();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the interpretation for the image bands. This currently is only for GDAL images.
/// </summary>
public ImageBandType BandType { get; set; }
/// <summary>
/// Gets or sets an integer indicating how many bytes exist for each pixel.
/// Eg. 32 ARGB = 4, 24 RGB = 3, 16 bit GrayScale = 2.
/// </summary>
public int BytesPerPixel { get; set; }
/// <summary>
/// Gets or sets the image height in pixels.
/// </summary>
public int Height { get; set; }
/// <summary>
/// Gets or sets the number of bands that are in the image. One band is a gray valued image, 3 bands for color RGB and 4 bands
/// for ARGB.
/// </summary>
public int NumBands { get; set; }
/// <summary>
/// Gets or sets the stride in bytes.
/// </summary>
public int Stride { get; set; }
/// <summary>
/// Gets or sets a one dimensional array of byte values.
/// </summary>
public virtual byte[] Values { get; set; }
/// <summary>
/// Gets or sets the image width in pixels.
/// </summary>
public int Width { get; set; }
/// <summary>
/// Gets or sets the world file that stores the georeferencing information for this image.
/// </summary>
public WorldFile WorldFile { get; set; }
/// <summary>
/// Gets or sets the color palette.
/// </summary>
protected IEnumerable<Color> ColorPalette { get; set; }
#endregion
#region Methods
/// <summary>
/// Opens the file with the specified fileName.
/// </summary>
/// <param name="fileName">The string fileName to open.</param>
/// <returns>ImageData of the opened file.</returns>
public static IImageData Open(string fileName)
{
return DataManager.DefaultDataManager.OpenImage(fileName);
}
/// <summary>
/// Forces the image to read values from the graphic image format to the byte array format.
/// </summary>
public virtual void CopyBitmapToValues()
{
}
/// <summary>
/// Copies the values from the specified source image.
/// </summary>
/// <param name="source">The source image to copy values from.</param>
public virtual void CopyValues(IImageData source)
{
}
/// <summary>
/// Forces the image to copy values from the byte array format to the image format.
/// </summary>
public virtual void CopyValuesToBitmap()
{
}
/// <summary>
/// Creates a new image and world file, placing the default bounds at the origin, with one pixel per unit.
/// </summary>
/// <param name="fileName">The string fileName.</param>
/// <param name="width">The integer width.</param>
/// <param name="height">The integer height.</param>
/// <param name="bandType">The color band type.</param>
/// <returns>The create image data.</returns>
public virtual IImageData Create(string fileName, int width, int height, ImageBandType bandType)
{
return DataManager.DefaultDataManager.CreateImage(fileName, height, width, bandType);
}
/// <summary>
/// Attempts to create a bitmap for the entire image. This may cause memory exceptions.
/// </summary>
/// <returns>A Bitmap of the image.</returns>
public virtual Bitmap GetBitmap()
{
return null;
}
/// <summary>
/// The geographic envelope gives the region that the image should be created for.
/// The window gives the corresponding pixel dimensions for the image, so that
/// images matching the resolution of the screen can be used.
/// </summary>
/// <param name="envelope">The geographic extents to retrieve data for.</param>
/// <param name="size">The rectangle that defines the size of the drawing area in pixels.</param>
/// <returns>A bitmap captured from the main image. </returns>
public Bitmap GetBitmap(Extent envelope, Size size)
{
return GetBitmap(envelope, new Rectangle(new Point(0, 0), size));
}
/// <summary>
/// The geographic envelope gives the region that the image should be created for.
/// The window gives the corresponding pixel dimensions for the image, so that
/// images matching the resolution of the screen can be used.
/// </summary>
/// <param name="envelope">The geographic extents to retrieve data for.</param>
/// <param name="window">The rectangle that defines the size of the drawing area in pixels.</param>
/// <returns>A bitmap captured from the main image. </returns>
public virtual Bitmap GetBitmap(Extent envelope, Rectangle window)
{
return null;
}
/// <summary>
/// Creates a color structure from the byte values in the values array that correspond to the
/// specified position.
/// </summary>
/// <param name="row">The integer row index for the pixel.</param>
/// <param name="column">The integer column index for the pixel.</param>
/// <returns>A Color.</returns>
public virtual Color GetColor(int row, int column)
{
int bpp = BytesPerPixel;
int strd = Stride;
int b = Values[(row * strd) + (column * bpp)];
int g = Values[(row * strd) + (column * bpp) + 1];
int r = Values[(row * strd) + (column * bpp) + 2];
int a = 255;
if (BytesPerPixel == 4)
{
a = Values[(row * strd) + (column * bpp) + 3];
}
return Color.FromArgb(a, r, g, b);
}
/// <summary>
/// This is only used in the palette indexed band type.
/// </summary>
/// <returns>The color palette.</returns>
public virtual IEnumerable<Color> GetColorPalette()
{
return ColorPalette;
}
/// <summary>
/// Opens the file, assuming that the fileName has already been specified.
/// </summary>
public virtual void Open()
{
// todo: determine how this ImageData should wire itself to the returned value of OpenImage()
DataManager.DefaultDataManager.OpenImage(Filename);
}
/// <summary>
/// Gets a block of data directly, converted into a bitmap.
/// </summary>
/// <param name="xOffset">The zero based integer column offset from the left.</param>
/// <param name="yOffset">The zero based integer row offset from the top.</param>
/// <param name="xSize">The integer number of pixel columns in the block. </param>
/// <param name="ySize">The integer number of pixel rows in the block.</param>
/// <returns>A Bitmap that is xSize, ySize.</returns>
public virtual Bitmap ReadBlock(int xOffset, int yOffset, int xSize, int ySize)
{
// Implemented in sub-classes.
return null;
}
/// <summary>
/// Saves the image and associated world file to the current fileName.
/// </summary>
public virtual void Save()
{
}
/// <summary>
/// Saves the image to a new fileName.
/// </summary>
/// <param name="fileName">The string fileName to save the image to.</param>
public virtual void SaveAs(string fileName)
{
DataManager.DefaultDataManager.CreateImage(fileName, Height, Width, BandType);
}
/// <summary>
/// Sets the color value into the byte array based on the row and column position of the pixel.
/// </summary>
/// <param name="row">The integer row index of the pixel to set the color of.</param>
/// <param name="column">The integer column index of the pixel to set the color of. </param>
/// <param name="col">The color to copy values from.</param>
public virtual void SetColor(int row, int column, Color col)
{
int bpp = BytesPerPixel;
int strd = Stride;
Values[(row * strd) + (column * bpp)] = col.B;
Values[(row * strd) + (column * bpp) + 1] = col.G;
Values[(row * strd) + (column * bpp) + 2] = col.R;
if (BytesPerPixel == 4)
{
Values[(row * strd) + (column * bpp) + 3] = col.A;
}
}
/// <summary>
/// This should update the palette cached and in the file.
/// </summary>
/// <param name="value">The color palette.</param>
public virtual void SetColorPalette(IEnumerable<Color> value)
{
ColorPalette = value;
}
/// <summary>
/// Finalizes the blocks. In the case of a pyramid image, this forces recalculation of the
/// various overlays. For GDAL images, this may do nothing, since the overlay recalculation
/// may be on the fly. For InRam images this does nothing.
/// </summary>
public virtual void UpdateOverviews()
{
}
/// <summary>
/// Saves a bitmap of data as a continuous block into the specified location.
/// Be sure to call UpdateOverviews after writing all blocks in pyramid images.
/// </summary>
/// <param name="value">The bitmap value to save.</param>
/// <param name="xOffset">The zero based integer column offset from the left.</param>
/// <param name="yOffset">The zero based integer row offset from the top.</param>
public virtual void WriteBlock(Bitmap value, int xOffset, int yOffset)
{
// Implemented in subclasses.
}
/// <summary>
/// Disposes the managed memory objects in the ImageData class, and then forwards
/// the Dispose operation to the internal dataset in the base class, if any.
/// </summary>
/// <param name="disposeManagedResources">Boolean, true if both managed and unmanaged resources should be finalized.</param>
protected override void Dispose(bool disposeManagedResources)
{
if (disposeManagedResources)
{
WorldFile = null;
Filename = null;
Bounds = null;
Values = null;
}
base.Dispose(disposeManagedResources);
}
/// <summary>
/// Occurs when the bounds have been set.
/// </summary>
/// <param name="bounds">The new bounds.</param>
protected override void OnBoundsChanged(IRasterBounds bounds)
{
// Bounds may be null when the image layer is being disposed.
// We could probably skip calling this event in that case, but at any rate, we don't want to crash.
if (WorldFile != null && bounds != null) WorldFile.Affine = bounds.AffineCoefficients;
}
#endregion
}
}
| |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* 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
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Sanford.Collections.Generic
{
public partial class UndoableList<T> : IList<T>
{
#region SetCommand
private class SetCommand : ICommand
{
private IList<T> theList;
private int index;
private T oldItem;
private T newItem;
private bool undone = true;
public SetCommand(IList<T> theList, int index, T item)
{
this.theList = theList;
this.index = index;
this.newItem = item;
}
#region ICommand Members
public void Execute()
{
#region Guard
if(!undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index < theList.Count);
oldItem = theList[index];
theList[index] = newItem;
undone = false;
}
public void Undo()
{
#region Guard
if(undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index < theList.Count);
Debug.Assert(theList[index].Equals(newItem));
theList[index] = oldItem;
undone = true;
}
#endregion
}
#endregion
#region InsertCommand
private class InsertCommand : ICommand
{
private IList<T> theList;
private int index;
private T item;
private bool undone = true;
private int count;
public InsertCommand(IList<T> theList, int index, T item)
{
this.theList = theList;
this.index = index;
this.item = item;
}
#region ICommand Members
public void Execute()
{
#region Guard
if(!undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index <= theList.Count);
count = theList.Count;
theList.Insert(index, item);
undone = false;
}
public void Undo()
{
#region Guard
if(undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index <= theList.Count);
Debug.Assert(theList[index].Equals(item));
theList.RemoveAt(index);
undone = true;
Debug.Assert(theList.Count == count);
}
#endregion
}
#endregion
#region InsertRangeCommand
private class InsertRangeCommand : ICommand
{
private List<T> theList;
private int index;
private List<T> insertList;
private bool undone = true;
public InsertRangeCommand(List<T> theList, int index, IEnumerable<T> collection)
{
this.theList = theList;
this.index = index;
insertList = new List<T>(collection);
}
#region ICommand Members
public void Execute()
{
#region Guard
if(!undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index <= theList.Count);
theList.InsertRange(index, insertList);
undone = false;
}
public void Undo()
{
#region Guard
if(undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index <= theList.Count);
theList.RemoveRange(index, insertList.Count);
undone = true;
}
#endregion
}
#endregion
#region RemoveAtCommand
private class RemoveAtCommand : ICommand
{
private IList<T> theList;
private int index;
private T item;
private bool undone = true;
private int count;
public RemoveAtCommand(IList<T> theList, int index)
{
this.theList = theList;
this.index = index;
}
#region ICommand Members
public void Execute()
{
#region Guard
if(!undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index < theList.Count);
item = theList[index];
count = theList.Count;
theList.RemoveAt(index);
undone = false;
}
public void Undo()
{
#region Guard
if(undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index < theList.Count);
theList.Insert(index, item);
undone = true;
Debug.Assert(theList.Count == count);
}
#endregion
}
#endregion
#region RemoveRangeCommand
private class RemoveRangeCommand : ICommand
{
private List<T> theList;
private int index;
private int count;
private List<T> rangeList = new List<T>();
private bool undone = true;
public RemoveRangeCommand(List<T> theList, int index, int count)
{
this.theList = theList;
this.index = index;
this.count = count;
}
#region ICommand Members
public void Execute()
{
#region Guard
if(!undone)
{
return;
}
#endregion
Debug.Assert(index >= 0 && index < theList.Count);
Debug.Assert(index + count <= theList.Count);
rangeList = new List<T>(theList.GetRange(index, count));
theList.RemoveRange(index, count);
undone = false;
}
public void Undo()
{
#region Guard
if(undone)
{
return;
}
#endregion
theList.InsertRange(index, rangeList);
undone = true;
}
#endregion
}
#endregion
#region ClearCommand
private class ClearCommand : ICommand
{
private IList<T> theList;
private IList<T> undoList;
private bool undone = true;
public ClearCommand(IList<T> theList)
{
this.theList = theList;
}
#region ICommand Members
public void Execute()
{
#region Guard
if(!undone)
{
return;
}
#endregion
undoList = new List<T>(theList);
theList.Clear();
undone = false;
}
public void Undo()
{
#region Guard
if(undone)
{
return;
}
#endregion
Debug.Assert(theList.Count == 0);
foreach(T item in undoList)
{
theList.Add(item);
}
undoList.Clear();
undone = true;
}
#endregion
}
#endregion
#region ReverseCommand
private class ReverseCommand : ICommand
{
private List<T> theList;
private int index;
private int count;
private bool reverseRange;
private bool undone = true;
public ReverseCommand(List<T> theList)
{
this.theList = theList;
this.reverseRange = false;
}
public ReverseCommand(List<T> theList, int index, int count)
{
this.theList = theList;
this.index = index;
this.count = count;
this.reverseRange = true;
}
#region ICommand Members
public void Execute()
{
#region Guard
if(!undone)
{
return;
}
#endregion
if(reverseRange)
{
theList.Reverse(index, count);
}
else
{
theList.Reverse();
}
undone = false;
}
public void Undo()
{
#region Guard
if(undone)
{
return;
}
#endregion
if(reverseRange)
{
theList.Reverse(index, count);
}
else
{
theList.Reverse();
}
undone = true;
}
#endregion
}
#endregion
}
}
| |
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using IO = System.IO;
namespace WixSharp.CommonTasks
{
/// <summary>
/// The utility class implementing the common 'MSI AppSearch' tasks (Directory, File, Registry and Product searches).
/// </summary>
public static class AppSearch
{
[DllImport("msi", CharSet = CharSet.Unicode)]
static extern Int32 MsiGetProductInfo(string product, string property, [Out] StringBuilder valueBuf, ref Int32 len);
[DllImport("msi")]
static extern int MsiEnumProducts(int iProductIndex, StringBuilder lpProductBuf);
/// <summary>
/// Gets the 'product code' of the installed product.
/// </summary>
/// <param name="name">The product name.</param>
/// <returns></returns>
static public string[] GetProductCode(string name)
{
var result = new List<string>();
var productCode = new StringBuilder();
int i = 0;
while (0 == MsiEnumProducts(i++, productCode))
{
var productNameLen = 512;
var productName = new StringBuilder(productNameLen);
MsiGetProductInfo(productCode.ToString(), "ProductName", productName, ref productNameLen);
if (productName.ToString() == name)
result.Add(productCode.ToString());
}
return result.ToArray();
}
/// <summary>
/// Gets array of 'product codes' (GUIDs) of all installed products.
/// </summary>
static public string[] GetProducts()
{
var result = new List<string>();
var productCode = new StringBuilder();
int i = 0;
while (0 == MsiEnumProducts(i++, productCode))
{
var productNameLen = 512;
var productName = new StringBuilder(productNameLen);
result.Add(productCode.ToString());
}
return result.ToArray();
}
/// <summary>
/// Gets the 'product name' of the installed product.
/// </summary>
/// <param name="productCode">The product code.</param>
/// <returns></returns>
static public string GetProductName(string productCode)
{
var productNameLen = 512;
var productName = new StringBuilder(productNameLen);
if (0 == MsiGetProductInfo(productCode, "ProductName", productName, ref productNameLen))
return productName.ToString();
else
return null;
}
/// <summary>
/// Determines whether the product is installed.
/// </summary>
/// <param name="productCode">The product code.</param>
/// <returns></returns>
static public bool IsProductInstalled(string productCode)
{
var productNameLen = 512;
var productName = new StringBuilder(productNameLen);
if (0 == MsiGetProductInfo(productCode, "ProductName", productName, ref productNameLen))
return !string.IsNullOrEmpty(productName.ToString());
else
return false;
}
/// <summary>
/// Determines whether the file exists.
/// </summary>
/// <param name="file">The file path.</param>
/// <returns></returns>
static public bool FileExists(string file)
{
try
{
return IO.File.Exists(file);
}
catch { }
return false;
}
/// <summary>
/// Determines whether the dir exists.
/// </summary>
/// <param name="dir">The directory path.</param>
/// <returns></returns>
static public bool DirExists(string dir)
{
try
{
return IO.Directory.Exists(dir);
}
catch { }
return false;
}
/// <summary>
/// Converts INI file content into dictionary.
/// </summary>
/// <param name="iniFile">The INI file.</param>
/// <param name="encoding">The encoding.</param>
/// <returns></returns>
static public Dictionary<string, Dictionary<string, string>> IniFileToDictionary(string iniFile, Encoding encoding = null)
{
return IniToDictionary(IO.File.ReadAllLines(iniFile, encoding ?? Encoding.Default));
}
static internal Dictionary<string, Dictionary<string, string>> IniToDictionary(string[] iniFileContent)
{
var result = new Dictionary<string, Dictionary<string, string>>();
var section = "default";
var entries = iniFileContent.Select(l => l.Trim())
.Where(l => !l.StartsWith(";") && l.IsNotEmpty());
foreach (var line in entries)
{
if (line.StartsWith("["))
{
section = line.Trim('[', ']');
continue;
}
if (!result.ContainsKey(section))
result[section] = new Dictionary<string, string>();
var pair = line.Split('=').Select(x => x.Trim());
if (pair.Count() < 2)
result[section][pair.First()] = null;
else
result[section][pair.First()] = pair.Last();
}
return result;
}
/// <summary>
/// Returns INI file the field value.
/// <para>It returns null if file or the field not found.</para>
/// </summary>
/// <param name="file">The INI file path.</param>
/// <param name="section">The section.</param>
/// <param name="field">The field.</param>
/// <param name="encoding">The encoding.</param>
/// <returns></returns>
static public string IniFileValue(string file, string section, string field, Encoding encoding = null)
{
try
{
return IniFileToDictionary(file)[section][field];
}
catch { }
return null;
}
/// <summary>
/// Determines whether the registry key exists.
/// </summary>
/// <param name="root">The root.</param>
/// <param name="keyPath">The key path.</param>
/// <returns></returns>
static public bool RegKeyExists(RegistryKey root, string keyPath)
{
using (RegistryKey key = root.OpenSubKey(keyPath))
return (key != null);
}
/// <summary>
/// Gets the registry value.
/// </summary>
/// <param name="root">The root.</param>
/// <param name="keyPath">The key path.</param>
/// <param name="valueName">Name of the value.</param>
/// <returns></returns>
static public object GetRegValue(RegistryKey root, string keyPath, string valueName)
{
using (RegistryKey key = root.OpenSubKey(keyPath))
if (key != null)
return key.GetValue(valueName);
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "Represents a multipart/* content. Even if a collection of HttpContent is stored, " +
"suffix Collection is not appropriate.")]
public class MultipartContent : HttpContent, IEnumerable<HttpContent>
{
#region Fields
private const string CrLf = "\r\n";
private static readonly int s_crlfLength = GetEncodedLength(CrLf);
private static readonly int s_dashDashLength = GetEncodedLength("--");
private static readonly int s_colonSpaceLength = GetEncodedLength(": ");
private static readonly int s_commaSpaceLength = GetEncodedLength(", ");
private readonly List<HttpContent> _nestedContent;
private readonly string _boundary;
#endregion Fields
#region Construction
public MultipartContent()
: this("mixed", GetDefaultBoundary())
{ }
public MultipartContent(string subtype)
: this(subtype, GetDefaultBoundary())
{ }
public MultipartContent(string subtype, string boundary)
{
if (string.IsNullOrWhiteSpace(subtype))
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(subtype));
}
Contract.EndContractBlock();
ValidateBoundary(boundary);
_boundary = boundary;
string quotedBoundary = boundary;
if (!quotedBoundary.StartsWith("\"", StringComparison.Ordinal))
{
quotedBoundary = "\"" + quotedBoundary + "\"";
}
MediaTypeHeaderValue contentType = new MediaTypeHeaderValue("multipart/" + subtype);
contentType.Parameters.Add(new NameValueHeaderValue(nameof(boundary), quotedBoundary));
Headers.ContentType = contentType;
_nestedContent = new List<HttpContent>();
}
private static void ValidateBoundary(string boundary)
{
// NameValueHeaderValue is too restrictive for boundary.
// Instead validate it ourselves and then quote it.
if (string.IsNullOrWhiteSpace(boundary))
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(boundary));
}
// RFC 2046 Section 5.1.1
// boundary := 0*69<bchars> bcharsnospace
// bchars := bcharsnospace / " "
// bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?"
if (boundary.Length > 70)
{
throw new ArgumentOutOfRangeException(nameof(boundary), boundary,
string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_field_too_long, 70));
}
// Cannot end with space.
if (boundary.EndsWith(" ", StringComparison.Ordinal))
{
throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary));
}
Contract.EndContractBlock();
const string AllowedMarks = @"'()+_,-./:=? ";
foreach (char ch in boundary)
{
if (('0' <= ch && ch <= '9') || // Digit.
('a' <= ch && ch <= 'z') || // alpha.
('A' <= ch && ch <= 'Z') || // ALPHA.
(AllowedMarks.IndexOf(ch) >= 0)) // Marks.
{
// Valid.
}
else
{
throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary));
}
}
}
private static string GetDefaultBoundary()
{
return Guid.NewGuid().ToString();
}
public virtual void Add(HttpContent content)
{
if (content == null)
{
throw new ArgumentNullException(nameof(content));
}
Contract.EndContractBlock();
_nestedContent.Add(content);
}
#endregion Construction
#region Dispose
protected override void Dispose(bool disposing)
{
if (disposing)
{
foreach (HttpContent content in _nestedContent)
{
content.Dispose();
}
_nestedContent.Clear();
}
base.Dispose(disposing);
}
#endregion Dispose
#region IEnumerable<HttpContent> Members
public IEnumerator<HttpContent> GetEnumerator()
{
return _nestedContent.GetEnumerator();
}
#endregion
#region IEnumerable Members
Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
{
return _nestedContent.GetEnumerator();
}
#endregion
#region Serialization
// for-each content
// write "--" + boundary
// for-each content header
// write header: header-value
// write content.CopyTo[Async]
// write "--" + boundary + "--"
// Can't be canceled directly by the user. If the overall request is canceled
// then the stream will be closed an exception thrown.
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Debug.Assert(stream != null);
try
{
// Write start boundary.
await EncodeStringToStreamAsync(stream, "--" + _boundary + CrLf).ConfigureAwait(false);
// Write each nested content.
var output = new StringBuilder();
for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++)
{
// Write divider, headers, and content.
HttpContent content = _nestedContent[contentIndex];
await EncodeStringToStreamAsync(stream, SerializeHeadersToString(output, contentIndex, content)).ConfigureAwait(false);
await content.CopyToAsync(stream).ConfigureAwait(false);
}
// Write footer boundary.
await EncodeStringToStreamAsync(stream, CrLf + "--" + _boundary + "--" + CrLf).ConfigureAwait(false);
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, ex);
throw;
}
}
protected override async Task<Stream> CreateContentReadStreamAsync()
{
try
{
var streams = new Stream[2 + (_nestedContent.Count*2)];
var scratch = new StringBuilder();
int streamIndex = 0;
// Start boundary.
streams[streamIndex++] = EncodeStringToNewStream("--" + _boundary + CrLf);
// Each nested content.
for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++)
{
HttpContent nestedContent = _nestedContent[contentIndex];
streams[streamIndex++] = EncodeStringToNewStream(SerializeHeadersToString(scratch, contentIndex, nestedContent));
Stream readStream = (await nestedContent.ReadAsStreamAsync().ConfigureAwait(false)) ?? new MemoryStream();
if (!readStream.CanSeek)
{
// Seekability impacts whether HttpClientHandlers are able to rewind. To maintain compat
// and to allow such use cases when a nested stream isn't seekable (which should be rare),
// we fall back to the base behavior. We don't dispose of the streams already obtained
// as we don't necessarily own them yet.
return await base.CreateContentReadStreamAsync().ConfigureAwait(false);
}
streams[streamIndex++] = readStream;
}
// Footer boundary.
streams[streamIndex] = EncodeStringToNewStream(CrLf + "--" + _boundary + "--" + CrLf);
return new ContentReadStream(streams);
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, ex);
throw;
}
}
private string SerializeHeadersToString(StringBuilder scratch, int contentIndex, HttpContent content)
{
scratch.Clear();
// Add divider.
if (contentIndex != 0) // Write divider for all but the first content.
{
scratch.Append(CrLf + "--"); // const strings
scratch.Append(_boundary);
scratch.Append(CrLf);
}
// Add headers.
foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers)
{
scratch.Append(headerPair.Key);
scratch.Append(": ");
string delim = string.Empty;
foreach (string value in headerPair.Value)
{
scratch.Append(delim);
scratch.Append(value);
delim = ", ";
}
scratch.Append(CrLf);
}
// Extra CRLF to end headers (even if there are no headers).
scratch.Append(CrLf);
return scratch.ToString();
}
private static ValueTask EncodeStringToStreamAsync(Stream stream, string input)
{
byte[] buffer = HttpRuleParser.DefaultHttpEncoding.GetBytes(input);
return stream.WriteAsync(new ReadOnlyMemory<byte>(buffer));
}
private static Stream EncodeStringToNewStream(string input)
{
return new MemoryStream(HttpRuleParser.DefaultHttpEncoding.GetBytes(input), writable: false);
}
protected internal override bool TryComputeLength(out long length)
{
int boundaryLength = GetEncodedLength(_boundary);
long currentLength = 0;
long internalBoundaryLength = s_crlfLength + s_dashDashLength + boundaryLength + s_crlfLength;
// Start Boundary.
currentLength += s_dashDashLength + boundaryLength + s_crlfLength;
bool first = true;
foreach (HttpContent content in _nestedContent)
{
if (first)
{
first = false; // First boundary already written.
}
else
{
// Internal Boundary.
currentLength += internalBoundaryLength;
}
// Headers.
foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers)
{
currentLength += GetEncodedLength(headerPair.Key) + s_colonSpaceLength;
int valueCount = 0;
foreach (string value in headerPair.Value)
{
currentLength += GetEncodedLength(value);
valueCount++;
}
if (valueCount > 1)
{
currentLength += (valueCount - 1) * s_commaSpaceLength;
}
currentLength += s_crlfLength;
}
currentLength += s_crlfLength;
// Content.
long tempContentLength = 0;
if (!content.TryComputeLength(out tempContentLength))
{
length = 0;
return false;
}
currentLength += tempContentLength;
}
// Terminating boundary.
currentLength += s_crlfLength + s_dashDashLength + boundaryLength + s_dashDashLength + s_crlfLength;
length = currentLength;
return true;
}
private static int GetEncodedLength(string input)
{
return HttpRuleParser.DefaultHttpEncoding.GetByteCount(input);
}
private sealed class ContentReadStream : Stream
{
private readonly Stream[] _streams;
private readonly long _length;
private int _next;
private Stream _current;
private long _position;
internal ContentReadStream(Stream[] streams)
{
Debug.Assert(streams != null);
_streams = streams;
foreach (Stream stream in streams)
{
_length += stream.Length;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
foreach (Stream s in _streams)
{
s.Dispose();
}
}
}
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override int Read(byte[] buffer, int offset, int count)
{
ValidateReadArgs(buffer, offset, count);
if (count == 0)
{
return 0;
}
while (true)
{
if (_current != null)
{
int bytesRead = _current.Read(buffer, offset, count);
if (bytesRead != 0)
{
_position += bytesRead;
return bytesRead;
}
_current = null;
}
if (_next >= _streams.Length)
{
return 0;
}
_current = _streams[_next++];
}
}
public override int Read(Span<byte> buffer)
{
if (buffer.Length == 0)
{
return 0;
}
while (true)
{
if (_current != null)
{
int bytesRead = _current.Read(buffer);
if (bytesRead != 0)
{
_position += bytesRead;
return bytesRead;
}
_current = null;
}
if (_next >= _streams.Length)
{
return 0;
}
_current = _streams[_next++];
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateReadArgs(buffer, offset, count);
return ReadAsyncPrivate(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) =>
ReadAsyncPrivate(buffer, cancellationToken);
public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(ReadAsync(array, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public async ValueTask<int> ReadAsyncPrivate(Memory<byte> buffer, CancellationToken cancellationToken)
{
if (buffer.Length == 0)
{
return 0;
}
while (true)
{
if (_current != null)
{
int bytesRead = await _current.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
if (bytesRead != 0)
{
_position += bytesRead;
return bytesRead;
}
_current = null;
}
if (_next >= _streams.Length)
{
return 0;
}
_current = _streams[_next++];
}
}
public override long Position
{
get { return _position; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
long previousStreamsLength = 0;
for (int i = 0; i < _streams.Length; i++)
{
Stream curStream = _streams[i];
long curLength = curStream.Length;
if (value < previousStreamsLength + curLength)
{
_current = curStream;
i++;
_next = i;
curStream.Position = value - previousStreamsLength;
for (; i < _streams.Length; i++)
{
_streams[i].Position = 0;
}
_position = value;
return;
}
previousStreamsLength += curLength;
}
_current = null;
_next = _streams.Length;
_position = value;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
Position = offset;
break;
case SeekOrigin.Current:
Position += offset;
break;
case SeekOrigin.End:
Position = _length + offset;
break;
default:
throw new ArgumentOutOfRangeException(nameof(origin));
}
return Position;
}
public override long Length => _length;
private static void ValidateReadArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (offset > buffer.Length - count)
{
throw new ArgumentException(SR.net_http_buffer_insufficient_length, nameof(buffer));
}
}
public override void Flush() { }
public override void SetLength(long value) { throw new NotSupportedException(); }
public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override void Write(ReadOnlySpan<byte> buffer) { throw new NotSupportedException(); }
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { throw new NotSupportedException(); }
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { throw new NotSupportedException(); }
}
#endregion Serialization
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
using System.IO;
using System.Reflection;
using Xunit;
namespace CoreXml.Test.XLinq
{
public partial class XNodeBuilderFunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
public partial class NamespacehandlingSaveOptions : XLinqTestCase
{
private string _mode;
private Type _type;
public override void Init()
{
_mode = Params[0] as string;
_type = Params[1] as Type;
}
#region helpers
private void DumpMethodInfo(MethodInfo mi)
{
TestLog.WriteLineIgnore("Method with the params found: " + mi.Name);
foreach (var pi in mi.GetParameters())
{
TestLog.WriteLineIgnore(" name: " + pi.Name + " Type: " + pi.ParameterType);
}
}
private string SaveXElement(object elem, SaveOptions so)
{
string retVal = null;
switch (_mode)
{
case "Save":
using (StringWriter sw = new StringWriter())
{
if (_type.Name == "XElement")
{
(elem as XElement).Save(sw, so);
}
else if (_type.Name == "XDocument")
{
(elem as XDocument).Save(sw, so);
}
retVal = sw.ToString();
}
break;
case "ToString":
if (_type.Name == "XElement")
{
retVal = (elem as XElement).ToString(so);
}
else if (_type.Name == "XDocument")
{
retVal = (elem as XDocument).ToString(so);
}
break;
default:
TestLog.Compare(false, "TEST FAILED: wrong mode");
break;
}
return retVal;
}
private string AppendXmlDecl(string xml)
{
return _mode == "Save" ? GetXmlStringWithXmlDecl(xml) : xml;
}
private static string GetXmlStringWithXmlDecl(string xml)
{
return @"<?xml version='1.0' encoding='utf-16'?>" + xml;
}
private object Parse(string xml)
{
object o = null;
if (_type.Name == "XElement")
{
o = XElement.Parse(xml);
}
else if (_type.Name == "XDocument")
{
o = XDocument.Parse(xml);
}
return o;
}
#endregion
//[Variation(Desc = "1 level down", Priority = 0, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></p:A>" })]
//[Variation(Desc = "1 level down II.", Priority = 0, Params = new object[] { "<A><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></A>" })] // start at not root node
//[Variation(Desc = "2 levels down", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></p:A>" })]
//[Variation(Desc = "2 levels down II.", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><C xmlns:p='nsp'/></B></p:A>" })]
//[Variation(Desc = "2 levels down III.", Priority = 1, Params = new object[] { "<A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></A>" })]
//[Variation(Desc = "Siblings", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'/><C xmlns:p='nsp'/><p:C xmlns:p='nsp'/></A>" })]
//[Variation(Desc = "Children", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'><C xmlns:p='nsp'><p:C xmlns:p='nsp'/></C></p:B></A>" })]
//[Variation(Desc = "Xml namespace I.", Priority = 3, Params = new object[] { "<A xmlns:xml='http://www.w3.org/XML/1998/namespace'/>" })]
//[Variation(Desc = "Xml namespace II.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })]
//[Variation(Desc = "Xml namespace III.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:xml='http://www.w3.org/XML/1998/namespace' xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })]
//[Variation(Desc = "Default namespaces", Priority = 1, Params = new object[] { "<A xmlns='nsp'><p:B xmlns:p='nsp'><C xmlns='nsp' /></p:B></A>" })]
//[Variation(Desc = "Not used NS declarations", Priority = 2, Params = new object[] { "<A xmlns='nsp' xmlns:u='not-used'><p:B xmlns:p='nsp'><C xmlns:u='not-used' xmlns='nsp' /></p:B></A>" })]
//[Variation(Desc = "SameNS, different prefix", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><B xmlns:q='nsp'><p:C xmlns:p='nsp'/></B></p:A>" })]
private void testFromTheRootNodeSimple()
{
string xml = CurrentChild.Params[0] as string;
object elemObj = Parse(xml);
// Write using XmlWriter in duplicate namespace decl. removal mode
string removedByWriter = SaveXElement(elemObj, SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting);
XElement elem = (elemObj is XDocument) ? (elemObj as XDocument).Root : elemObj as XElement;
// Remove the namespace decl. duplicates from the Xlinq tree
(from a in elem.DescendantsAndSelf().Attributes()
where a.IsNamespaceDeclaration && ((a.Name.LocalName == "xml" && (string)a == XNamespace.Xml.NamespaceName) ||
(from parentDecls in a.Parent.Ancestors().Attributes(a.Name)
where parentDecls.IsNamespaceDeclaration && (string)parentDecls == (string)a
select parentDecls).Any()
)
select a).ToList().Remove();
// Write XElement using XmlWriter without omitting
string removedByManual = SaveXElement(elemObj, SaveOptions.DisableFormatting);
ReaderDiff.Compare(removedByWriter, removedByManual);
}
//[Variation(Desc = "Default ns parent autogenerated", Priority = 1)]
private void testFromTheRootNodeTricky()
{
object e = new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute("xmlns", "nsp")));
if (_type == typeof(XDocument))
{
XDocument d = new XDocument();
d.Add(e);
e = d;
}
string act = SaveXElement(e, SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting);
string exp = AppendXmlDecl("<A xmlns='nsp'><B/></A>");
ReaderDiff.Compare(act, exp);
}
//[Variation(Desc = "Conflicts: NS redefinition", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D xmlns:p='nsp'/></p:C></p:B></p:A>",
// "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D/></p:C></p:B></p:A>" })]
//[Variation(Desc = "Conflicts: NS redefinition, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
// "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D/></C></B></A>" })]
//[Variation(Desc = "Conflicts: NS redefinition, default NS II.", Priority = 2, Params = new object[] { "<A xmlns=''><B xmlns='ns-other'><C xmlns=''><D xmlns=''/></C></B></A>",
// "<A><B xmlns='ns-other'><C xmlns=''><D/></C></B></A>" })]
//[Variation(Desc = "Conflicts: NS undeclaration, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
// "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D/></C></B></A>" })]
public static object[][] ConFlictsNSRedefenitionParams = new object[][] {
new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D xmlns:p='nsp'/></p:C></p:B></p:A>",
"<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D/></p:C></p:B></p:A>" },
new object[] { "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
"<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D/></C></B></A>" },
new object[] { "<A xmlns=''><B xmlns='ns-other'><C xmlns=''><D xmlns=''/></C></B></A>",
"<A><B xmlns='ns-other'><C xmlns=''><D/></C></B></A>" },
new object[] { "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
"<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D/></C></B></A>" }
};
[Theory, MemberData(nameof(ConFlictsNSRedefenitionParams))]
public void XDocumentConflictsNSRedefinitionSaveToStringWriterAndGetContent(string xml1, string xml2)
{
XDocument doc = XDocument.Parse(xml1);
SaveOptions so = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
using (StringWriter sw = new StringWriter())
{
doc.Save(sw, so);
ReaderDiff.Compare(GetXmlStringWithXmlDecl(xml2), sw.ToString());
}
}
[Theory, MemberData(nameof(ConFlictsNSRedefenitionParams))]
public void XDocumentConflictsNSRedefinitionToString(string xml1, string xml2)
{
XDocument doc = XDocument.Parse(xml1);
SaveOptions so = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
ReaderDiff.Compare(xml2, doc.ToString(so));
}
[Theory, MemberData(nameof(ConFlictsNSRedefenitionParams))]
public void XElementConflictsNSRedefinitionSaveToStringWriterAndGetContent(string xml1, string xml2)
{
XElement el = XElement.Parse(xml1);
SaveOptions so = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
using (StringWriter sw = new StringWriter())
{
el.Save(sw, so);
ReaderDiff.Compare(GetXmlStringWithXmlDecl(xml2), sw.ToString());
}
}
[Theory, MemberData(nameof(ConFlictsNSRedefenitionParams))]
public void XElementConflictsNSRedefinitionToString(string xml1, string xml2)
{
XElement el = XElement.Parse(xml1);
SaveOptions so = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
ReaderDiff.Compare(xml2, el.ToString(so));
}
//[Variation(Desc = "Not from root", Priority = 1)]
private void testFromChildNode1()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute("xmlns", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Element("{nsp}A"), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:A xmlns:p1='nsp'><B xmlns='nsp'/></p1:A>"));
}
//[Variation(Desc = "Not from root II.", Priority = 1)]
private void testFromChildNode2()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Element("{nsp}A"), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:A xmlns:p1='nsp'><p1:B/></p1:A>"));
}
//[Variation(Desc = "Not from root III.", Priority = 2)]
private void testFromChildNode3()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Descendants("{nsp}B").FirstOrDefault(), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:B xmlns:p1='nsp'/>"));
}
//[Variation(Desc = "Not from root IV.", Priority = 2)]
private void testFromChildNode4()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B")));
ReaderDiff.Compare(SaveXElement(e.Descendants("{nsp}B").FirstOrDefault(), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:B xmlns:p1='nsp'/>"));
}
}
}
}
}
| |
using System;
using AutoMapper;
namespace Benchmark.Flattening
{
using System.Collections.Generic;
using System.Linq;
public class DeepTypeMapper : IObjectToObjectMapper
{
private Customer _customer;
public string Name { get; } = "Deep Types";
public void Initialize()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Address, Address>();
cfg.CreateMap<Address, AddressDTO>();
cfg.CreateMap<Customer, CustomerDTO>();
});
_customer = new Customer()
{
Address = new Address() { City = "istanbul", Country = "turkey", Id = 1, Street = "istiklal cad." },
HomeAddress = new Address() { City = "istanbul", Country = "turkey", Id = 2, Street = "istiklal cad." },
Id = 1,
Name = "Eduardo Najera",
Credit = 234.7m,
WorkAddresses = new List<Address>()
{
new Address() {City = "istanbul", Country = "turkey", Id = 5, Street = "istiklal cad."},
new Address() {City = "izmir", Country = "turkey", Id = 6, Street = "konak"}
},
Addresses = new List<Address>()
{
new Address() {City = "istanbul", Country = "turkey", Id = 3, Street = "istiklal cad."},
new Address() {City = "izmir", Country = "turkey", Id = 4, Street = "konak"}
}.ToArray()
};
}
public object Map()
{
return Mapper.Map<Customer, CustomerDTO>(_customer);
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class AddressDTO
{
public int Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public decimal? Credit { get; set; }
public Address Address { get; set; }
public Address HomeAddress { get; set; }
public Address[] Addresses { get; set; }
public List<Address> WorkAddresses { get; set; }
}
public class CustomerDTO
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public AddressDTO HomeAddress { get; set; }
public AddressDTO[] Addresses { get; set; }
public List<AddressDTO> WorkAddresses { get; set; }
public string AddressCity { get; set; }
}
}
public class ManualDeepTypeMapper : IObjectToObjectMapper
{
private Customer _customer;
public string Name { get; } = "Manual Deep Types";
public void Initialize()
{
_customer = new Customer()
{
Address = new Address() { City = "istanbul", Country = "turkey", Id = 1, Street = "istiklal cad." },
HomeAddress = new Address() { City = "istanbul", Country = "turkey", Id = 2, Street = "istiklal cad." },
Id = 1,
Name = "Eduardo Najera",
Credit = 234.7m,
WorkAddresses = new List<Address>()
{
new Address() {City = "istanbul", Country = "turkey", Id = 5, Street = "istiklal cad."},
new Address() {City = "izmir", Country = "turkey", Id = 6, Street = "konak"}
},
Addresses = new List<Address>()
{
new Address() {City = "istanbul", Country = "turkey", Id = 3, Street = "istiklal cad."},
new Address() {City = "izmir", Country = "turkey", Id = 4, Street = "konak"}
}.ToArray()
};
}
public object Map()
{
var dto = new CustomerDTO();
dto.Id = _customer.Id;
dto.Name = _customer.Name;
dto.AddressCity = _customer.Address.City;
dto.Address = new Address() { Id = _customer.Address.Id, Street = _customer.Address.Street, Country = _customer.Address.Country, City = _customer.Address.City };
dto.HomeAddress = new AddressDTO() { Id = _customer.HomeAddress.Id, Country = _customer.HomeAddress.Country, City = _customer.HomeAddress.City };
dto.Addresses = new AddressDTO[_customer.Addresses.Length];
for (int i = 0; i < _customer.Addresses.Length; i++)
{
dto.Addresses[i] = new AddressDTO() { Id = _customer.Addresses[i].Id, Country = _customer.Addresses[i].Country, City = _customer.Addresses[i].City };
}
dto.WorkAddresses = new List<AddressDTO>();
foreach (var workAddress in _customer.WorkAddresses)
{
dto.WorkAddresses.Add(new AddressDTO() { Id = workAddress.Id, Country = workAddress.Country, City = workAddress.City });
}
return dto;
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class AddressDTO
{
public int Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public decimal? Credit { get; set; }
public Address Address { get; set; }
public Address HomeAddress { get; set; }
public Address[] Addresses { get; set; }
public ICollection<Address> WorkAddresses { get; set; }
}
public class CustomerDTO
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public AddressDTO HomeAddress { get; set; }
public AddressDTO[] Addresses { get; set; }
public List<AddressDTO> WorkAddresses { get; set; }
public string AddressCity { get; set; }
}
}
public class ComplexTypeMapper : IObjectToObjectMapper
{
private Foo _foo;
public string Name { get; } = "Complex Types";
public void Initialize()
{
Mapper.Initialize(cfg => cfg.CreateMap<Foo, Foo>());
_foo = new Foo
{
Name = "foo",
Int32 = 12,
Int64 = 123123,
NullInt = 16,
DateTime = DateTime.Now,
Doublen = 2312112,
Foo1 = new Foo { Name = "foo one" },
Foos = new List<Foo>
{
new Foo {Name = "j1", Int64 = 123, NullInt = 321},
new Foo {Name = "j2", Int32 = 12345, NullInt = 54321},
new Foo {Name = "j3", Int32 = 12345, NullInt = 54321},
},
FooArr = new[]
{
new Foo {Name = "a1"},
new Foo {Name = "a2"},
new Foo {Name = "a3"},
},
IntArr = new[] { 1, 2, 3, 4, 5 },
Ints = new[] { 7, 8, 9 },
};
}
public object Map()
{
return Mapper.Map<Foo, Foo>(_foo);
}
public class Foo
{
public string Name { get; set; }
public int Int32 { get; set; }
public long Int64 { set; get; }
public int? NullInt { get; set; }
public float Floatn { get; set; }
public double Doublen { get; set; }
public DateTime DateTime { get; set; }
public Foo Foo1 { get; set; }
public List<Foo> Foos { get; set; }
public Foo[] FooArr { get; set; }
public int[] IntArr { get; set; }
public int[] Ints { get; set; }
}
}
public class ManualComplexTypeMapper : IObjectToObjectMapper
{
private Foo _foo;
public string Name { get; } = "Manual Complex Types";
public void Initialize()
{
_foo = new Foo
{
Name = "foo",
Int32 = 12,
Int64 = 123123,
NullInt = 16,
DateTime = DateTime.Now,
Doublen = 2312112,
Foo1 = new Foo { Name = "foo one" },
Foos = new List<Foo>
{
new Foo {Name = "j1", Int64 = 123, NullInt = 321},
new Foo {Name = "j2", Int32 = 12345, NullInt = 54321},
new Foo {Name = "j3", Int32 = 12345, NullInt = 54321},
},
FooArr = new[]
{
new Foo {Name = "a1"},
new Foo {Name = "a2"},
new Foo {Name = "a3"},
},
IntArr = new[] { 1, 2, 3, 4, 5 },
Ints = new[] { 7, 8, 9 },
};
}
public object Map()
{
return new Foo
{
Name = _foo.Name,
Int32 = _foo.Int32,
Int64 = _foo.Int64,
NullInt = _foo.NullInt,
DateTime = _foo.DateTime,
Doublen = _foo.Doublen,
Foo1 = new Foo { Name = _foo.Foo1.Name },
Foos = _foo.Foos.Select(f => new Foo { Name = f.Name, Int64 = f.Int64, NullInt = f.NullInt }).ToList(),
FooArr = _foo.Foos.Select(f => new Foo { Name = f.Name, Int64 = f.Int64, NullInt = f.NullInt }).ToArray(),
IntArr = _foo.IntArr.Select(i => i).ToArray(),
Ints = _foo.Ints.ToArray(),
};
}
public class Foo
{
public string Name { get; set; }
public int Int32 { get; set; }
public long Int64 { set; get; }
public int? NullInt { get; set; }
public float Floatn { get; set; }
public double Doublen { get; set; }
public DateTime DateTime { get; set; }
public Foo Foo1 { get; set; }
public IEnumerable<Foo> Foos { get; set; }
public Foo[] FooArr { get; set; }
public int[] IntArr { get; set; }
public IEnumerable<int> Ints { get; set; }
}
}
public class CtorMapper : IObjectToObjectMapper
{
private Model11 _model;
public string Name => "CtorMapper";
public void Initialize()
{
Mapper.Initialize(cfg => cfg.CreateMap<Model11, Dto11>());
_model = new Model11 { Value = 5 };
}
public object Map()
{
return Mapper.Map<Model11, Dto11>(_model);
}
}
public class ManualCtorMapper : IObjectToObjectMapper
{
private Model11 _model;
public string Name => "ManualCtorMapper";
public void Initialize()
{
_model = new Model11 { Value = 5 };
}
public object Map()
{
return new Dto11(_model.Value);
}
}
public class FlatteningMapper : IObjectToObjectMapper
{
private ModelObject _source;
public string Name
{
get { return "AutoMapper"; }
}
public void Initialize()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Model1, Dto1>();
cfg.CreateMap<Model2, Dto2>();
cfg.CreateMap<Model3, Dto3>();
cfg.CreateMap<Model4, Dto4>();
cfg.CreateMap<Model5, Dto5>();
cfg.CreateMap<Model6, Dto6>();
cfg.CreateMap<Model7, Dto7>();
cfg.CreateMap<Model8, Dto8>();
cfg.CreateMap<Model9, Dto9>();
cfg.CreateMap<Model10, Dto10>();
cfg.CreateMap<ModelObject, ModelDto>();
});
_source = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
};
}
public object Map()
{
return Mapper.Map<ModelObject, ModelDto>(_source);
}
}
public class ManualMapper : IObjectToObjectMapper
{
private ModelObject _source;
public string Name
{
get { return "Manual"; }
}
public void Initialize()
{
_source = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
};
}
public object Map()
{
return new ModelDto
{
BaseDate = _source.BaseDate,
Sub2ProperName = _source.Sub2.ProperName,
SubProperName = _source.Sub.ProperName,
SubSubSubIAmACoolProperty = _source.Sub.SubSub.IAmACoolProperty,
SubWithExtraNameProperName = _source.SubWithExtraName.ProperName
};
}
}
public class Model1
{
public int Value { get; set; }
}
public class Model2
{
public int Value { get; set; }
}
public class Model3
{
public int Value { get; set; }
}
public class Model4
{
public int Value { get; set; }
}
public class Model5
{
public int Value { get; set; }
}
public class Model6
{
public int Value { get; set; }
}
public class Model7
{
public int Value { get; set; }
}
public class Model8
{
public int Value { get; set; }
}
public class Model9
{
public int Value { get; set; }
}
public class Model10
{
public int Value { get; set; }
}
public class Model11
{
public int Value { get; set; }
}
public class Dto1
{
public int Value { get; set; }
}
public class Dto2
{
public int Value { get; set; }
}
public class Dto3
{
public int Value { get; set; }
}
public class Dto4
{
public int Value { get; set; }
}
public class Dto5
{
public int Value { get; set; }
}
public class Dto6
{
public int Value { get; set; }
}
public class Dto7
{
public int Value { get; set; }
}
public class Dto8
{
public int Value { get; set; }
}
public class Dto9
{
public int Value { get; set; }
}
public class Dto10
{
public int Value { get; set; }
}
public class Dto11
{
public Dto11(int value)
{
_value = value;
}
private readonly int _value;
public int Value
{
get { return _value; }
}
}
public class ModelObject
{
public DateTime BaseDate { get; set; }
public ModelSubObject Sub { get; set; }
public ModelSubObject Sub2 { get; set; }
public ModelSubObject SubWithExtraName { get; set; }
}
public class ModelSubObject
{
public string ProperName { get; set; }
public ModelSubSubObject SubSub { get; set; }
}
public class ModelSubSubObject
{
public string IAmACoolProperty { get; set; }
}
public class ModelDto
{
public DateTime BaseDate { get; set; }
public string SubProperName { get; set; }
public string Sub2ProperName { get; set; }
public string SubWithExtraNameProperName { get; set; }
public string SubSubSubIAmACoolProperty { get; set; }
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Text;
namespace Orleans.Runtime
{
/// <summary>
/// Abstract class for histgram value statistics, instantiate either HistogramValueStatistic or LinearHistogramValueStatistic
/// </summary>
internal abstract class HistogramValueStatistic
{
protected Object Lockable;
protected CounterStatistic[] Buckets;
public abstract void AddData(long data);
public abstract void AddData(TimeSpan data);
protected HistogramValueStatistic(string name, int numBuckets)
{
Lockable = new object();
Buckets = new CounterStatistic[numBuckets];
// Create a hidden counter per bucket to reuse the counter code for efficient counting without reporting each individual counter as a statistic.
for (int i = 0; i < numBuckets; i++)
Buckets[i] = CounterStatistic.FindOrCreate(
new StatisticName(String.Format("{0}.Bucket#{1}", name, i)),
false,
CounterStorage.DontStore,
isHidden: true);
}
internal string PrintHistogram()
{
return PrintHistogramImpl(false);
}
internal string PrintHistogramInMillis()
{
return PrintHistogramImpl(true);
}
protected void AddToCategory(uint histogramCategory)
{
histogramCategory = Math.Min(histogramCategory, (uint)(Buckets.Length - 1));
Buckets[histogramCategory].Increment();
}
protected abstract double BucketStart(int i);
protected abstract double BucketEnd(int i);
protected string PrintHistogramImpl(bool inMilliseconds)
{
var sb = new StringBuilder();
for (int i = 0; i < Buckets.Length; i++)
{
long bucket = Buckets[i].GetCurrentValue();
if (bucket > 0)
{
double start = BucketStart(i);
double end = BucketEnd(i);
if (inMilliseconds)
{
string one =
Double.MaxValue == end ?
"EOT" :
TimeSpan.FromTicks((long) end).TotalMilliseconds.ToString();
sb.Append(String.Format("[{0}:{1}]={2}, ", TimeSpan.FromTicks((long)start).TotalMilliseconds, one, bucket));
}
else
{
sb.Append(String.Format("[{0}:{1}]={2}, ", start, end, bucket));
}
}
}
return sb.ToString();
}
}
/// <summary>
/// Histogram created where buckets grow exponentially
/// </summary>
internal class ExponentialHistogramValueStatistic : HistogramValueStatistic
{
private ExponentialHistogramValueStatistic(string name, int numBuckets)
: base(name, numBuckets)
{
}
public static ExponentialHistogramValueStatistic Create_ExponentialHistogram(StatisticName name, int numBuckets)
{
var hist = new ExponentialHistogramValueStatistic(name.Name, numBuckets);
StringValueStatistic.FindOrCreate(name, hist.PrintHistogram);
return hist;
}
public static ExponentialHistogramValueStatistic Create_ExponentialHistogram_ForTiming(StatisticName name, int numBuckets)
{
var hist = new ExponentialHistogramValueStatistic(name.Name, numBuckets);
StringValueStatistic.FindOrCreate(name, hist.PrintHistogramInMillis);
return hist;
}
public override void AddData(TimeSpan data)
{
uint histogramCategory = (uint)Log2((ulong)data.Ticks);
AddToCategory(histogramCategory);
}
public override void AddData(long data)
{
uint histogramCategory = (uint)Log2((ulong)data);
AddToCategory(histogramCategory);
}
protected override double BucketStart(int i)
{
if (i == 0)
{
return 0.0;
}
return Math.Pow(2, i);
}
protected override double BucketEnd(int i)
{
if (i == Buckets.Length - 1)
{
return Double.MaxValue;
}
return Math.Pow(2, i + 1) - 1;
}
// The log base 2 of an integer is the same as the position of the highest bit set (or most significant bit set, MSB). The following log base 2 methods are faster than this one.
// More impl. methods here: http://graphics.stanford.edu/~seander/bithacks.html
private static uint Log2(ulong number)
{
uint r = 0; // r will be log2(number)
while ((number >>= 1) != 0) // unroll for more speed...
{
r++;
}
return r;
}
}
/// <summary>
/// Histogram created where buckets are uniform size
/// </summary>
internal class LinearHistogramValueStatistic : HistogramValueStatistic
{
private readonly double bucketWidth;
private LinearHistogramValueStatistic(string name, int numBuckets, double maximumValue)
: base(name, numBuckets)
{
bucketWidth = maximumValue / numBuckets;
}
public static LinearHistogramValueStatistic Create_LinearHistogram(StatisticName name, int numBuckets, double maximumValue)
{
var hist = new LinearHistogramValueStatistic(name.Name, numBuckets, maximumValue);
StringValueStatistic.FindOrCreate(name, hist.PrintHistogram);
return hist;
}
public static LinearHistogramValueStatistic Create_LinearHistogram_ForTiming(StatisticName name, int numBuckets, TimeSpan maximumValue)
{
var hist = new LinearHistogramValueStatistic(name.Name, numBuckets, maximumValue.Ticks);
StringValueStatistic.FindOrCreate(name, hist.PrintHistogramInMillis);
return hist;
}
public override void AddData(TimeSpan data)
{
uint histogramCategory = (uint)(data.Ticks / bucketWidth);
AddToCategory(histogramCategory);
}
public override void AddData(long data)
{
uint histogramCategory = (uint)(data / bucketWidth);
AddToCategory(histogramCategory);
}
protected override double BucketStart(int i)
{
return i * bucketWidth;
}
protected override double BucketEnd(int i)
{
if (i == Buckets.Length - 1)
{
return Double.MaxValue;
}
return (i + 1) * bucketWidth;
}
}
}
| |
namespace Xilium.CefGlue
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
/// <summary>
/// Class that supports the reading of XML data via the libxml streaming API.
/// The methods of this class should only be called on the thread that creates
/// the object.
/// </summary>
public sealed unsafe partial class CefXmlReader
{
/// <summary>
/// Create a new CefXmlReader object. The returned object's methods can only
/// be called from the thread that created the object.
/// </summary>
public static CefXmlReader Create(CefStreamReader stream, CefXmlEncoding encodingType, string uri)
{
if (stream == null) throw new ArgumentNullException("stream");
fixed (char* uri_str = uri)
{
var n_uri = new cef_string_t(uri_str, uri != null ? uri.Length : 0);
return CefXmlReader.FromNative(
cef_xml_reader_t.create(stream.ToNative(), encodingType, &n_uri)
);
}
}
/// <summary>
/// Moves the cursor to the next node in the document. This method must be
/// called at least once to set the current cursor position. Returns true if
/// the cursor position was set successfully.
/// </summary>
public bool MoveToNextNode()
{
return cef_xml_reader_t.move_to_next_node(_self) != 0;
}
/// <summary>
/// Close the document. This should be called directly to ensure that cleanup
/// occurs on the correct thread.
/// </summary>
public bool Close()
{
return cef_xml_reader_t.close(_self) != 0;
}
/// <summary>
/// Returns true if an error has been reported by the XML parser.
/// </summary>
public bool HasError
{
get { return cef_xml_reader_t.has_error(_self) != 0; }
}
/// <summary>
/// Returns the error string.
/// </summary>
public string Error
{
get
{
var n_result = cef_xml_reader_t.get_error(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// The below methods retrieve data for the node at the current cursor
/// position.
/// Returns the node type.
/// </summary>
public CefXmlNodeType NodeType
{
get { return cef_xml_reader_t.get_type(_self); }
}
/// <summary>
/// Returns the node depth. Depth starts at 0 for the root node.
/// </summary>
public int Depth
{
get { return cef_xml_reader_t.get_depth(_self); }
}
/// <summary>
/// Returns the local name. See
/// http://www.w3.org/TR/REC-xml-names/#NT-LocalPart for additional details.
/// </summary>
public string LocalName
{
get
{
var n_result = cef_xml_reader_t.get_local_name(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the namespace prefix. See http://www.w3.org/TR/REC-xml-names/ for
/// additional details.
/// </summary>
public string Prefix
{
get
{
var n_result = cef_xml_reader_t.get_prefix(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the qualified name, equal to (Prefix:)LocalName. See
/// http://www.w3.org/TR/REC-xml-names/#ns-qualnames for additional details.
/// </summary>
public string QualifiedName
{
get
{
var n_result = cef_xml_reader_t.get_qualified_name(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the URI defining the namespace associated with the node. See
/// http://www.w3.org/TR/REC-xml-names/ for additional details.
/// </summary>
public string NamespaceUri
{
get
{
var n_result = cef_xml_reader_t.get_namespace_uri(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the base URI of the node. See http://www.w3.org/TR/xmlbase/ for
/// additional details.
/// </summary>
public string BaseUri
{
get
{
var n_result = cef_xml_reader_t.get_base_uri(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the xml:lang scope within which the node resides. See
/// http://www.w3.org/TR/REC-xml/#sec-lang-tag for additional details.
/// </summary>
public string XmlLang
{
get
{
var n_result = cef_xml_reader_t.get_xml_lang(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns true if the node represents an empty element. <a/> is considered
/// empty but <a></a> is not.
/// </summary>
public bool IsEmptyElement
{
get { return cef_xml_reader_t.is_empty_element(_self) != 0; }
}
/// <summary>
/// Returns true if the node has a text value.
/// </summary>
public bool HasValue
{
get { return cef_xml_reader_t.has_value(_self) != 0; }
}
/// <summary>
/// Returns the text value.
/// </summary>
public string Value
{
get
{
var n_result = cef_xml_reader_t.get_value(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns true if the node has attributes.
/// </summary>
public bool HasAttributes
{
get { return cef_xml_reader_t.has_attributes(_self) != 0; }
}
/// <summary>
/// Returns the number of attributes.
/// </summary>
public int AttributeCount
{
get { return (int)cef_xml_reader_t.get_attribute_count(_self); }
}
/// <summary>
/// Returns the value of the attribute at the specified 0-based index.
/// </summary>
public string GetAttribute(int index)
{
var n_result = cef_xml_reader_t.get_attribute_byindex(_self, index);
return cef_string_userfree.ToString(n_result);
}
/// <summary>
/// Returns the value of the attribute with the specified qualified name.
/// </summary>
public string GetAttribute(string qualifiedName)
{
fixed (char* qualifiedName_str = qualifiedName)
{
var n_qualifiedName = new cef_string_t(qualifiedName_str, qualifiedName != null ? qualifiedName.Length : 0);
var n_result = cef_xml_reader_t.get_attribute_byqname(_self, &n_qualifiedName);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the value of the attribute with the specified local name and
/// namespace URI.
/// </summary>
public string GetAttribute(string localName, string namespaceUri)
{
fixed (char* localName_str = localName)
fixed (char* namespaceUri_str = namespaceUri)
{
var n_localName = new cef_string_t(localName_str, localName != null ? localName.Length : 0);
var n_namespaceUri = new cef_string_t(namespaceUri_str, namespaceUri != null ? namespaceUri.Length : 0);
var n_result = cef_xml_reader_t.get_attribute_bylname(_self, &n_localName, &n_namespaceUri);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns an XML representation of the current node's children.
/// </summary>
public string GetInnerXml()
{
var n_result = cef_xml_reader_t.get_inner_xml(_self);
return cef_string_userfree.ToString(n_result);
}
/// <summary>
/// Returns an XML representation of the current node including its children.
/// </summary>
public string GetOuterXml()
{
var n_result = cef_xml_reader_t.get_outer_xml(_self);
return cef_string_userfree.ToString(n_result);
}
/// <summary>
/// Returns the line number for the current node.
/// </summary>
public int LineNumber
{
get { return cef_xml_reader_t.get_line_number(_self); }
}
/// <summary>
/// Attribute nodes are not traversed by default. The below methods can be
/// used to move the cursor to an attribute node. MoveToCarryingElement() can
/// be called afterwards to return the cursor to the carrying element. The
/// depth of an attribute node will be 1 + the depth of the carrying element.
/// Moves the cursor to the attribute at the specified 0-based index. Returns
/// true if the cursor position was set successfully.
/// </summary>
public bool MoveToAttribute(int index)
{
return cef_xml_reader_t.move_to_attribute_byindex(_self, index) != 0;
}
/// <summary>
/// Moves the cursor to the attribute with the specified qualified name.
/// Returns true if the cursor position was set successfully.
/// </summary>
public bool MoveToAttribute(string qualifiedName)
{
fixed (char* qualifiedName_str = qualifiedName)
{
var n_qualifiedName = new cef_string_t(qualifiedName_str, qualifiedName != null ? qualifiedName.Length : 0);
return cef_xml_reader_t.move_to_attribute_byqname(_self, &n_qualifiedName) != 0;
}
}
/// <summary>
/// Moves the cursor to the attribute with the specified local name and
/// namespace URI. Returns true if the cursor position was set successfully.
/// </summary>
public bool MoveToAttribute(string localName, string namespaceUri)
{
fixed (char* localName_str = localName)
fixed (char* namespaceUri_str = namespaceUri)
{
var n_localName = new cef_string_t(localName_str, localName != null ? localName.Length : 0);
var n_namespaceUri = new cef_string_t(namespaceUri_str, namespaceUri != null ? namespaceUri.Length : 0);
return cef_xml_reader_t.move_to_attribute_bylname(_self, &n_localName, &n_namespaceUri) != 0;
}
}
/// <summary>
/// Moves the cursor to the first attribute in the current element. Returns
/// true if the cursor position was set successfully.
/// </summary>
public bool MoveToFirstAttribute()
{
return cef_xml_reader_t.move_to_first_attribute(_self) != 0;
}
/// <summary>
/// Moves the cursor to the next attribute in the current element. Returns
/// true if the cursor position was set successfully.
/// </summary>
public bool MoveToNextAttribute()
{
return cef_xml_reader_t.move_to_next_attribute(_self) != 0;
}
/// <summary>
/// Moves the cursor back to the carrying element. Returns true if the cursor
/// position was set successfully.
/// </summary>
public bool MoveToCarryingElement()
{
return cef_xml_reader_t.move_to_carrying_element(_self) != 0;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class GenericTypeParameterBuilder: TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Private Data Mebers
internal TypeBuilder m_type;
#endregion
#region Constructor
internal GenericTypeParameterBuilder(TypeBuilder type)
{
m_type = type;
}
#endregion
#region Object Overrides
public override String ToString()
{
return m_type.Name;
}
public override bool Equals(object o)
{
GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder;
if (g == null)
return false;
return object.ReferenceEquals(g.m_type, m_type);
}
public override int GetHashCode() { return m_type.GetHashCode(); }
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
internal int MetadataTokenInternal { get { return m_type.MetadataTokenInternal; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*".ToCharArray(), this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&".ToCharArray(), this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]".ToCharArray(), this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
{
szrank = "*";
}
else
{
for(int i = 1; i < rank; i++)
szrank += ",";
}
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
SymbolType st = SymbolType.FormCompoundType(s.ToCharArray(), this, 0) as SymbolType;
return st;
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName { get { return null; } }
public override String Namespace { get { return null; } }
public override String AssemblyQualifiedName { get { return null; } }
public override Type BaseType { get { return m_type.BaseType; } }
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; }
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { throw new InvalidOperationException(); }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return false; } }
public override bool IsGenericParameter { get { return true; } }
public override bool IsConstructedGenericType { get { return false; } }
public override int GenericParameterPosition { get { return m_type.GenericParameterPosition; } }
public override bool ContainsGenericParameters { get { return m_type.ContainsGenericParameters; } }
public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } }
public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } }
public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); }
public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericTypeDefinition")); }
protected override bool IsValueTypeImpl() { return false; }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); }
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
#region Public Members
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_type.SetGenParamCustomAttribute(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_type.SetGenParamCustomAttribute(customBuilder);
}
public void SetBaseTypeConstraint(Type baseTypeConstraint)
{
m_type.CheckContext(baseTypeConstraint);
m_type.SetParent(baseTypeConstraint);
}
[System.Runtime.InteropServices.ComVisible(true)]
public void SetInterfaceConstraints(params Type[] interfaceConstraints)
{
m_type.CheckContext(interfaceConstraints);
m_type.SetInterfaces(interfaceConstraints);
}
public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes)
{
m_type.SetGenParamAttributes(genericParameterAttributes);
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Configurer;
using Microsoft.Extensions.EnvironmentAbstractions;
using Newtonsoft.Json;
using NuGet.Frameworks;
using NuGet.Versioning;
namespace Microsoft.DotNet.ToolPackage
{
internal class LocalToolsResolverCache : ILocalToolsResolverCache
{
private readonly DirectoryPath _cacheVersionedDirectory;
private readonly IFileSystem _fileSystem;
private const int LocalToolResolverCacheVersion = 1;
public LocalToolsResolverCache(IFileSystem fileSystem = null,
DirectoryPath? cacheDirectory = null,
int version = LocalToolResolverCacheVersion)
{
_fileSystem = fileSystem ?? new FileSystemWrapper();
DirectoryPath appliedCacheDirectory =
cacheDirectory ?? new DirectoryPath(Path.Combine(CliFolderPathCalculator.ToolsResolverCachePath));
_cacheVersionedDirectory = appliedCacheDirectory.WithSubDirectories(version.ToString());
}
public void Save(
IDictionary<RestoredCommandIdentifier, RestoredCommand> restoredCommandMap)
{
EnsureFileStorageExists();
foreach (var distinctPackageIdAndRestoredCommandMap in restoredCommandMap.GroupBy(x => x.Key.PackageId))
{
PackageId distinctPackageId = distinctPackageIdAndRestoredCommandMap.Key;
string packageCacheFile = GetCacheFile(distinctPackageId);
if (_fileSystem.File.Exists(packageCacheFile))
{
var existingCacheTable = GetCacheTable(packageCacheFile);
var diffedRow = distinctPackageIdAndRestoredCommandMap
.Where(pair => !TryGetMatchingRestoredCommand(
pair.Key,
existingCacheTable, out _))
.Select(pair => ConvertToCacheRow(pair.Key, pair.Value));
_fileSystem.File.WriteAllText(
packageCacheFile,
JsonConvert.SerializeObject(existingCacheTable.Concat(diffedRow)));
}
else
{
var rowsToAdd =
distinctPackageIdAndRestoredCommandMap
.Select(mapWithSamePackageId
=> ConvertToCacheRow(
mapWithSamePackageId.Key,
mapWithSamePackageId.Value));
_fileSystem.File.WriteAllText(
packageCacheFile,
JsonConvert.SerializeObject(rowsToAdd));
}
}
}
public bool TryLoad(
RestoredCommandIdentifier restoredCommandIdentifier,
out RestoredCommand restoredCommand)
{
string packageCacheFile = GetCacheFile(restoredCommandIdentifier.PackageId);
if (_fileSystem.File.Exists(packageCacheFile))
{
if (TryGetMatchingRestoredCommand(
restoredCommandIdentifier,
GetCacheTable(packageCacheFile),
out restoredCommand))
{
return true;
}
}
restoredCommand = null;
return false;
}
private CacheRow[] GetCacheTable(string packageCacheFile)
{
CacheRow[] cacheTable = Array.Empty<CacheRow>();
try
{
cacheTable =
JsonConvert.DeserializeObject<CacheRow[]>(_fileSystem.File.ReadAllText(packageCacheFile));
}
catch (JsonReaderException)
{
// if file is corrupted, treat it as empty since it is not the source of truth
}
return cacheTable;
}
public bool TryLoadHighestVersion(
RestoredCommandIdentifierVersionRange query,
out RestoredCommand restoredCommandList)
{
restoredCommandList = null;
string packageCacheFile = GetCacheFile(query.PackageId);
if (_fileSystem.File.Exists(packageCacheFile))
{
var list = GetCacheTable(packageCacheFile)
.Select(c => Convert(query.PackageId, c))
.Where(strongTypeStored =>
query.VersionRange.Satisfies(strongTypeStored.restoredCommandIdentifier.Version))
.Where(onlyVersionSatisfies =>
onlyVersionSatisfies.restoredCommandIdentifier ==
query.WithVersion(onlyVersionSatisfies.restoredCommandIdentifier.Version))
.OrderByDescending(allMatched => allMatched.restoredCommandIdentifier.Version)
.FirstOrDefault();
if (!list.restoredCommand.Equals(default(RestoredCommand)))
{
restoredCommandList = list.restoredCommand;
return true;
}
}
return false;
}
private string GetCacheFile(PackageId packageId)
{
return _cacheVersionedDirectory.WithFile(packageId.ToString()).Value;
}
private void EnsureFileStorageExists()
{
_fileSystem.Directory.CreateDirectory(_cacheVersionedDirectory.Value);
}
private static CacheRow ConvertToCacheRow(
RestoredCommandIdentifier restoredCommandIdentifier,
RestoredCommand restoredCommandList)
{
return new CacheRow
{
Version = restoredCommandIdentifier.Version.ToNormalizedString(),
TargetFramework = restoredCommandIdentifier.TargetFramework.GetShortFolderName(),
RuntimeIdentifier = restoredCommandIdentifier.RuntimeIdentifier.ToLowerInvariant(),
Name = restoredCommandIdentifier.CommandName.Value,
Runner = restoredCommandList.Runner,
PathToExecutable = restoredCommandList.Executable.Value
};
}
private static
(RestoredCommandIdentifier restoredCommandIdentifier,
RestoredCommand restoredCommand)
Convert(
PackageId packageId,
CacheRow cacheRow)
{
RestoredCommandIdentifier restoredCommandIdentifier =
new RestoredCommandIdentifier(
packageId,
NuGetVersion.Parse(cacheRow.Version),
NuGetFramework.Parse(cacheRow.TargetFramework),
cacheRow.RuntimeIdentifier,
new ToolCommandName(cacheRow.Name));
RestoredCommand restoredCommand =
new RestoredCommand(
new ToolCommandName(cacheRow.Name),
cacheRow.Runner,
new FilePath(cacheRow.PathToExecutable));
return (restoredCommandIdentifier, restoredCommand);
}
private static bool TryGetMatchingRestoredCommand(
RestoredCommandIdentifier restoredCommandIdentifier,
CacheRow[] cacheTable,
out RestoredCommand restoredCommandList)
{
(RestoredCommandIdentifier restoredCommandIdentifier, RestoredCommand restoredCommand)[]
matchingRow = cacheTable
.Select(c => Convert(restoredCommandIdentifier.PackageId, c))
.Where(candidate => candidate.restoredCommandIdentifier == restoredCommandIdentifier).ToArray();
if (matchingRow.Length >= 2)
{
throw new ResolverCacheInconsistentException(
$"more than one row for {restoredCommandIdentifier.DebugToString()}");
}
if (matchingRow.Length == 1)
{
restoredCommandList = matchingRow[0].restoredCommand;
return true;
}
restoredCommandList = null;
return false;
}
private class CacheRow
{
public string Version { get; set; }
public string TargetFramework { get; set; }
public string RuntimeIdentifier { get; set; }
public string Name { get; set; }
public string Runner { get; set; }
public string PathToExecutable { get; set; }
}
}
}
| |
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Xml;
using Krystals4ObjectLibrary;
using Moritz.Globals;
namespace Moritz.Palettes
{
public partial class PaletteForm : Form
{
public PaletteForm(XmlReader r, IPaletteFormsHostForm hostForm, string name, int domain, bool isPercussionPalette, FormStateFunctions fsf)
: this(hostForm, name, domain, fsf)
{
_isLoading = true;
ReadPalette(r);
this.PercussionCheckBox.Checked = isPercussionPalette;
this.ModulationWheelEnvelopesLabel.Focus();
if(this._ornamentsForm != null)
{
ShowOrnamentSettingsButton.Enabled = true;
DeleteOrnamentSettingsButton.Enabled = true;
}
_fsf.SetSettingsAreSaved(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
_isLoading = false;
}
/// <summary>
/// Creates a new, empty PalettesForm with help texts adjusted for the given domain.
/// </summary>
/// <param name="assistantComposer"></param>
/// <param name="krystal"></param>
public PaletteForm(IPaletteFormsHostForm hostForm, string name, int domain, FormStateFunctions fsf)
{
InitializeComponent();
_hostForm = hostForm;
Text = name;
_savedName = name;
_domain = domain;
_fsf = fsf;
_isLoading = true;
ConnectBasicChordControl();
if(M.Preferences.CurrentMultimediaMidiOutputDevice != null)
{
ConnectPaletteButtonsControl(domain, _hostForm.LocalScoreAudioPath);
}
_allTextBoxes = GetAllTextBoxes();
TouchAllTextBoxes();
SetDialogForDomain(domain);
ShowOrnamentSettingsButton.Enabled = false;
DeleteOrnamentSettingsButton.Enabled = false;
_fsf.SetFormState(this, SavedState.unconfirmed);
_isLoading = false;
ConfirmButton.Enabled = false;
RevertToSavedButton.Enabled = false;
RevertToSavedButton.Hide();
}
public void ShowPaletteChordForm(int midiChordIndex)
{
if(M.HasError(_allTextBoxes))
{
MessageBox.Show("Can't create a palette chord form because this palette contains errors.");
}
else
{
_paletteChordForm = new PaletteChordForm(this, _bcc, midiChordIndex, _fsf);
_paletteChordForm.Show();
_hostForm.SetAllFormsExceptChordFormEnabledState(false);
BringPaletteChordFormToFront();
}
}
/// <summary>
/// Can be called by OrnamentSettingsForm.
/// </summary>
internal void BringPaletteChordFormToFront()
{
Debug.Assert(this.Enabled == false && _paletteChordForm != null);
_paletteChordForm.BringToFront();
}
internal void ClosePaletteChordForm(int chordIndex)
{
Debug.Assert(this.Enabled);
_paletteChordForm.Close();
_paletteChordForm = null;
_hostForm.SetAllFormsExceptChordFormEnabledState(true);
// If an OrnamentSettingsForm exists, it is brought in front of Visual Studio.
if(_ornamentsForm != null)
{
_ornamentsForm.BringToFront();
}
this.BringToFront();
this.PaletteButtonsControl.PaletteChordFormButtons[chordIndex].Select();
}
public bool HasOpenChordForm { get { return this._paletteChordForm != null; } }
private void ConnectBasicChordControl()
{
_bcc = new BasicChordControl(SetDialogState)
{
Location = new Point(22, 14)
};
Controls.Add(_bcc);
_bcc.TabIndex = 5;
}
private void ConnectPaletteButtonsControl(int domain, string audioFolder)
{
Point location = new Point(this.MinMsDurationsTextBox.Location.X, this.MinMsDurationsTextBox.Location.Y + 27);
_paletteButtonsControl = new PaletteButtonsControl(domain, location, this, audioFolder);
Debug.Assert(_paletteButtonsControl != null);
Controls.Add(_paletteButtonsControl);
_paletteButtonsControl.TabIndex = 18;
}
/// <summary>
/// Can be called by OrnamentSettingsForm when clearing the ornament settings.
/// </summary>
public void NewOrnamentSettingsForm()
{
if(_ornamentsForm != null)
{
DialogResult result = MessageBox.Show("Do you really want to replace the existing ornament settings?", "Warning",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
if(result == DialogResult.Yes)
{
DeleteOrnamentsForm();
//_ornamentSettingsForm.Close();
//_ornamentSettingsForm = null;
}
}
if(_ornamentsForm == null)
{
_ornamentsForm = new OrnamentsForm(this, _hostForm, _fsf);
SetOrnamentControls();
_fsf.SetSettingsAreUnconfirmed(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
_ornamentsForm.Show();
_ornamentsForm.BringToFront();
}
}
public void BringOrnamentSettingsFormToFront()
{
if(_ornamentsForm != null)
{
_ornamentsForm.BringToFront();
}
}
private Krystal GetKrystal(string krystalFileName)
{
Krystal krystal = null;
try
{
string krystalPath = M.LocalMoritzKrystalsFolder + @"\" + krystalFileName;
krystal = K.LoadKrystal(krystalPath);
}
catch(Exception ex)
{
MessageBox.Show("Error loading krystal.\n\n" + ex.Message);
krystal = null;
}
return krystal;
}
public void SetOrnamentControls()
{
int oldNumberOfOrnaments = _numberOfOrnaments;
if(this.OrnamentsForm != null && this.OrnamentsForm.Ornaments != null)
{
_numberOfOrnaments = this.OrnamentsForm.Ornaments.Count;
OrnamentNumbersLabel.Enabled = true;
OrnamentNumbersTextBox.Enabled = true;
OrnamentNumbersHelpLabel.Enabled = true;
MinMsDurationsLabel.Enabled = true;
MinMsDurationsTextBox.Enabled = true;
MinMsDurationsHelpLabel.Enabled = true;
string valStr = (_domain == 1) ? "value" : "values";
string ornamentNumbersHelpString = String.Format("{0} integer " + valStr + " in range [0..{1}]\n(0 means no ornament)",
_domain.ToString(), _numberOfOrnaments.ToString());
OrnamentNumbersHelpLabel.Text = ornamentNumbersHelpString;
string minMsDurationsHelpString = String.Format("{0} integer values >= 0",
_domain.ToString());
MinMsDurationsHelpLabel.Text = minMsDurationsHelpString;
ShowOrnamentSettingsButton.Enabled = true;
DeleteOrnamentSettingsButton.Enabled = true;
}
else
{
OrnamentNumbersLabel.Enabled = false;
OrnamentNumbersTextBox.Enabled = false;
OrnamentNumbersHelpLabel.Enabled = false;
MinMsDurationsLabel.Enabled = false;
MinMsDurationsTextBox.Enabled = false;
MinMsDurationsHelpLabel.Enabled = false;
OrnamentNumbersHelpLabel.Text = "";
MinMsDurationsHelpLabel.Text = "";
ShowOrnamentSettingsButton.Enabled = false;
DeleteOrnamentSettingsButton.Enabled = false;
}
if(oldNumberOfOrnaments != _numberOfOrnaments)
{
OrnamentNumbersTextBox_Leave(OrnamentNumbersTextBox, null);
MinMsDurationsTextBox_Leave(MinMsDurationsTextBox, null);
}
}
protected void PaletteForm_Click(object sender, EventArgs e)
{
if(_paletteButtonsControl != null)
{
_paletteButtonsControl.StopCurrentMediaPlayer();
}
}
/// <summary>
/// Used to populate the Inversions lists
/// </summary>
class IntervalPositionDistance
{
public IntervalPositionDistance(byte value, int position)
{
Value = value;
Position = (float)position;
}
public readonly byte Value;
public readonly float Position;
public float Distance = 0;
}
private int Compare(IntervalPositionDistance ipd1, IntervalPositionDistance ipd2)
{
int rval = 0;
if(ipd1.Distance > ipd2.Distance)
rval = 1;
else if(ipd1.Distance == ipd2.Distance)
rval = 0;
else if(ipd1.Distance < ipd2.Distance)
rval = -1;
return rval;
}
/// <summary>
/// Returns a list of intLists whose first intList is inversion0.
/// If inversion0 is null or inversion0.Count == 0, the returned list of intlists is empty, otherwise
/// If inversion0.Count == 1, the contained intList is simply inversion0, otherwise
/// The returned list of intLists has a Count of (n-1)*2, where n is the Count of inversion0.
/// </summary>
/// <param name="inversion0"></param>
/// <returns></returns>
public List<List<byte>> GetLinearInversions(string inversion0String)
{
List<byte> inversion0 = M.StringToByteList(inversion0String, ',');
List<List<byte>> inversions = new List<List<byte>>();
if(inversion0 != null && inversion0.Count != 0)
{
if(inversion0.Count == 1)
inversions.Add(inversion0);
else
{
List<IntervalPositionDistance> ipdList = new List<IntervalPositionDistance>();
for(int i = 0; i < inversion0.Count; i++)
{
IntervalPositionDistance ipd = new IntervalPositionDistance(inversion0[i], i);
ipdList.Add(ipd);
}
// ipdList is a now representaion of the field, now calculate the interval hierarchy per inversion
for(float pos = 0.25F; pos < (float)inversion0.Count - 1; pos += 0.5F)
{
List<IntervalPositionDistance> newIpdList = new List<IntervalPositionDistance>(ipdList);
foreach(IntervalPositionDistance ipd in newIpdList)
{
ipd.Distance = ipd.Position - pos;
ipd.Distance = ipd.Distance > 0 ? ipd.Distance : ipd.Distance * -1;
}
newIpdList.Sort(Compare);
List<byte> intervalList = new List<byte>();
foreach(IntervalPositionDistance ipd in newIpdList)
intervalList.Add(ipd.Value);
inversions.Add(intervalList);
}
// the intervalList for a particular inversionIndex is now inversions[inversionIndex]
}
}
return inversions;
}
/// <summary>
/// called after loading a file
/// </summary>
private void TouchAllTextBoxes()
{
_bcc.TouchAllTextBoxes();
BankIndicesTextBox_Leave(BankIndicesTextBox, null);
PatchIndicesTextBox_Leave(PatchIndicesTextBox, null);
PitchwheelDeviationsTextBox_Leave(PitchwheelDeviationsTextBox, null);
PitchwheelEnvelopesTextBox_Leave(PitchwheelEnvelopesTextBox, null);
PanEnvelopesTextBox_Leave(PanEnvelopesTextBox, null);
ModulationWheelEnvelopesTextBox_Leave(ModulationWheelEnvelopesTextBox, null);
ExpressionEnvelopesTextBox_Leave(ExpressionEnvelopesTextBox, null);
if(this.OrnamentsForm != null)
{
OrnamentNumbersTextBox_Leave(OrnamentNumbersTextBox, null);
MinMsDurationsTextBox_Leave(MinMsDurationsTextBox, null);
}
}
private void ConfirmButton_Click(object sender, EventArgs e)
{
_fsf.SetSettingsAreConfirmed(this, M.HasError(_allTextBoxes), ConfirmButton);
_hostForm.UpdateForChangedPaletteForm();
}
private void RevertToSavedButton_Click(object sender, EventArgs e)
{
Debug.Assert(((SavedState)this.Tag) == SavedState.unconfirmed || ((SavedState)this.Tag) == SavedState.confirmed);
DialogResult result =
MessageBox.Show("Are you sure you want to revert this palette and its ornaments to the saved version?", "Revert?",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if(result == System.Windows.Forms.DialogResult.Yes)
{
DeleteOrnamentsForm();
try
{
using(XmlReader r = XmlReader.Create(_hostForm.SettingsPath))
{
M.ReadToXmlElementTag(r, "moritzKrystalScore");
M.ReadToXmlElementTag(r, "palette");
while(r.Name == "palette")
{
if(r.NodeType != XmlNodeType.EndElement)
{
string name = "";
int domain = 1;
bool isPercussionPalette = false;
int count = r.AttributeCount;
for(int i = 0; i < count; i++)
{
r.MoveToAttribute(i);
switch(r.Name)
{
case "name":
name = r.Value;
break;
case "domain":
domain = int.Parse(r.Value);
break;
case "percussion":
if(r.Value == "1")
isPercussionPalette = true;
break;
}
}
if(name == _savedName)
{
_domain = domain;
this.PercussionCheckBox.Checked = isPercussionPalette;
ReadPalette(r);
this.ModulationWheelEnvelopesLabel.Focus();
_fsf.SetSettingsAreSaved(this, false, ConfirmButton, RevertToSavedButton);
break;
}
}
M.ReadToXmlElementTag(r, "palette", "moritzKrystalScore");
}
}
TouchAllTextBoxes();
_fsf.SetSettingsAreSaved(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
_hostForm.UpdateForChangedPaletteForm();
}
catch(Exception ex)
{
string msg = "Exception message:\n\n" + ex.Message;
MessageBox.Show(msg, "Error reading moritz krystal score settings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ShowMainScoreFormButton_Click(object sender, EventArgs e)
{
((Form)_hostForm).BringToFront();
}
public void ShowOrnamentSettingsButton_Click(object sender, EventArgs e)
{
if(_ornamentsForm != null)
{
_ornamentsForm.Show();
_ornamentsForm.BringToFront();
}
}
private void NewOrnamentSettingsButton_Click(object sender, EventArgs e)
{
NewOrnamentSettingsForm();
ShowOrnamentSettingsButton.Enabled = true;
DeleteOrnamentSettingsButton.Enabled = true;
}
private void DeleteOrnamentSettingsButton_Click(object sender, EventArgs e)
{
string msg = "Do you really want to delete the ornament settings?";
DialogResult result = MessageBox.Show(msg, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
if(result == DialogResult.No)
return;
DeleteOrnamentsForm();
}
private void DeleteOrnamentsForm()
{
if(_ornamentsForm != null)
{
_fsf.Remove(_ornamentsForm);
_ornamentsForm.Close();
_ornamentsForm = null;
ShowOrnamentSettingsButton.Enabled = false;
DeleteOrnamentSettingsButton.Enabled = false;
OrnamentNumbersTextBox.Text = "";
OrnamentNumbersHelpLabel.Text = "";
OrnamentNumbersLabel.Enabled = false;
OrnamentNumbersTextBox.Enabled = false;
OrnamentNumbersHelpLabel.Enabled = false;
MinMsDurationsTextBox.Text = "";
MinMsDurationsHelpLabel.Text = "";
MinMsDurationsLabel.Enabled = false;
MinMsDurationsTextBox.Enabled = false;
MinMsDurationsHelpLabel.Enabled = false;
SetSettingsHaveChanged();
}
}
public void MidiPitchesHelpButton_Click(object sender, EventArgs e)
{
if(_midiPitchesHelpForm == null)
{
_midiPitchesHelpForm = new MidiPitchesHelpForm(CloseMidiPitchesHelpForm);
_midiPitchesHelpForm.Show();
}
_midiPitchesHelpForm.BringToFront();
}
private void CloseMidiPitchesHelpForm()
{
if(_midiPitchesHelpForm != null)
{
_midiPitchesHelpForm.Close();
_midiPitchesHelpForm.Dispose();
_midiPitchesHelpForm = null;
}
}
private void PercussionCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox percussionCheckBox = sender as CheckBox;
if(percussionCheckBox.Checked)
{
MidiInstrumentsHelpButton.Text = "Percussion Instr.";
MidiInstrumentsHelpButton.Click -= MidiInstrumentsHelpButton_Click;
MidiInstrumentsHelpButton.Click += PercussionInstrHelpButton_Click;
}
else
{
MidiInstrumentsHelpButton.Text = "MIDI Instruments";
MidiInstrumentsHelpButton.Click -= PercussionInstrHelpButton_Click;
MidiInstrumentsHelpButton.Click += MidiInstrumentsHelpButton_Click;
}
SetSettingsHaveChanged();
}
public void MidiInstrumentsHelpButton_Click(object sender, EventArgs e)
{
CloseMIDIInstrumentsHelpForm();
CloseMIDIPercussionHelpForm();
if(_midiInstrumentsHelpForm == null)
{
_midiInstrumentsHelpForm = new MIDIInstrumentsHelpForm(CloseMIDIInstrumentsHelpForm);
_midiInstrumentsHelpForm.Show();
}
_midiInstrumentsHelpForm.BringToFront();
}
public void PercussionInstrHelpButton_Click(object sender, EventArgs e)
{
CloseMIDIInstrumentsHelpForm();
CloseMIDIPercussionHelpForm();
if(_percussionInstrHelpForm == null)
{
_percussionInstrHelpForm = new MIDIPercussionHelpForm(CloseMIDIPercussionHelpForm);
_percussionInstrHelpForm.Show();
}
_percussionInstrHelpForm.BringToFront();
}
private void CloseMIDIInstrumentsHelpForm()
{
if(_midiInstrumentsHelpForm != null)
{
_midiInstrumentsHelpForm.Close();
_midiInstrumentsHelpForm.Dispose();
_midiInstrumentsHelpForm = null;
}
}
private void CloseMIDIPercussionHelpForm()
{
if(_percussionInstrHelpForm != null)
{
_percussionInstrHelpForm.Close();
_percussionInstrHelpForm.Dispose();
_percussionInstrHelpForm = null;
}
}
/// <summary>
/// This function enables the parameter inputs and sets this dialog's help texts accordingly.
/// The contents of the Parameter TextBoxes are not changed.
/// </summary>
protected void SetDialogForDomain(int domain)
{
_bcc.NumberOfChordValues = domain;
string countString = domain.ToString() + " ";
string integerString = "integer ";
string floatString = "float ";
string valuesInRangeString = "values in range ";
string floatsPercentageString = countString + floatString + valuesInRangeString + "[ 0.0..100.0 ]";
string envelopesHelpString = countString + "envelopes*";
EnableMainParameters();
DisableChordParameters();
#region HelpLabels
_bcc.SetHelpLabels();
BankIndicesHelpLabel.Text = countString + "integer values in range [ 0..127 ]";
PatchIndicesHelpLabel.Text = countString + "integer values in range [ 0..127 ]";
PitchwheelDeviationsHelpLabel.Text = countString + integerString + valuesInRangeString + "[ 0..127 ]";
PitchwheelEnvelopesHelpLabel.Text = envelopesHelpString;
PanEnvelopesHelpLabel.Text = envelopesHelpString;
ModulationWheelEnvelopesHelpLabel.Text = envelopesHelpString;
ExpressionEnvelopesHelpLabel.Text = envelopesHelpString;
#endregion HelpLabels
}
private void DisableChordParameters()
{
_bcc.RootInversionLabel.Enabled = false;
_bcc.RootInversionTextBox.Enabled = false;
_bcc.RootInversionTextBox.Text = "";
_bcc.InversionIndicesLabel.Enabled = false;
_bcc.InversionIndicesTextBox.Enabled = false;
_bcc.InversionIndicesTextBox.Text = "";
_bcc.VerticalVelocityFactorsLabel.Enabled = false;
_bcc.VerticalVelocityFactorsTextBox.Enabled = false;
_bcc.VerticalVelocityFactorsTextBox.Text = "";
}
private List<TextBox> GetAllTextBoxes()
{
List<TextBox> allTextBoxes = new List<TextBox>
{
_bcc.ChordDensitiesTextBox,
_bcc.DurationsTextBox,
_bcc.MidiPitchesTextBox,
_bcc.VelocitiesTextBox,
_bcc.ChordOffsTextBox,
_bcc.RootInversionTextBox,
_bcc.InversionIndicesTextBox,
_bcc.VerticalVelocityFactorsTextBox,
BankIndicesTextBox,
PatchIndicesTextBox,
PitchwheelDeviationsTextBox,
PitchwheelEnvelopesTextBox,
PanEnvelopesTextBox,
ModulationWheelEnvelopesTextBox,
ExpressionEnvelopesTextBox,
OrnamentNumbersTextBox,
MinMsDurationsTextBox
};
return allTextBoxes;
}
private void EnableMainParameters()
{
_bcc.DurationsLabel.Enabled = true;
_bcc.DurationsTextBox.Enabled = true;
_bcc.DurationsHelpLabel.Enabled = true;
_bcc.MidiPitchesLabel.Enabled = true;
_bcc.MidiPitchesTextBox.Enabled = true;
_bcc.MidiPitchesHelpLabel.Enabled = true;
_bcc.VelocitiesLabel.Enabled = true;
_bcc.VelocitiesTextBox.Enabled = true;
_bcc.VelocitiesHelpLabel.Enabled = true;
_bcc.ChordDensitiesLabel.Enabled = true;
_bcc.ChordDensitiesTextBox.Enabled = true;
_bcc.ChordDensitiesHelpLabel.Enabled = true;
BankIndicesLabel.Enabled = true;
BankIndicesLabel.Enabled = true;
BankIndicesLabel.Enabled = true;
PatchIndicesLabel.Enabled = true;
PatchIndicesTextBox.Enabled = true;
PatchIndicesHelpLabel.Enabled = true;
ModulationWheelEnvelopesLabel.Enabled = true;
ModulationWheelEnvelopesTextBox.Enabled = true;
ModulationWheelEnvelopesHelpLabel.Enabled = true;
PitchwheelDeviationsLabel.Enabled = true;
PitchwheelDeviationsTextBox.Enabled = true;
PitchwheelDeviationsHelpLabel.Enabled = true;
PitchwheelEnvelopesLabel.Enabled = true;
PitchwheelEnvelopesTextBox.Enabled = true;
PitchwheelEnvelopesHelpLabel.Enabled = true;
PanEnvelopesLabel.Enabled = true;
PanEnvelopesTextBox.Enabled = true;
PanEnvelopesHelpLabel.Enabled = true;
ExpressionEnvelopesLabel.Enabled = true;
ExpressionEnvelopesTextBox.Enabled = true;
ExpressionEnvelopesHelpLabel.Enabled = true;
}
private string DefaultRootInversionString(int count)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < count; i++)
{
switch(i)
{
case 0:
sb.Append("12,");
break;
case 1:
sb.Append("7,");
break;
case 2:
sb.Append("5,");
break;
case 3:
sb.Append("4,");
break;
case 4:
sb.Append("3,");
break;
case 5:
sb.Append("2,");
break;
default:
sb.Append("1,");
break;
}
}
sb.Remove(sb.Length - 1, 1); // final comma
return sb.ToString();
}
private List<int> DefaultRootInversionIntList(int count)
{
List<int> intList = new List<int>();
for(int i = 0; i < count; i++)
{
switch(i)
{
case 0:
intList.Add(12);
break;
case 1:
intList.Add(7);
break;
case 2:
intList.Add(5);
break;
case 3:
intList.Add(4);
break;
case 4:
intList.Add(3);
break;
case 5:
intList.Add(2);
break;
default:
intList.Add(1);
break;
}
}
return intList;
}
#region text box events
#region text changed event handler
private void SetToWhiteTextBox_TextChanged(object sender, EventArgs e)
{
M.SetToWhite(sender as TextBox);
}
#endregion text changed event handler
private void BankIndicesTextBox_Leave(object sender, EventArgs e)
{
M.LeaveIntRangeTextBox(sender as TextBox, true, (uint)_bcc.NumberOfChordValues, 0, 127, SetDialogState);
}
private void PatchIndicesTextBox_Leave(object sender, EventArgs e)
{
M.LeaveIntRangeTextBox(sender as TextBox, false, (uint)_bcc.NumberOfChordValues, 0, 127, SetDialogState);
}
private void PitchwheelDeviationsTextBox_Leave(object sender, EventArgs e)
{
M.LeaveIntRangeTextBox(sender as TextBox, true, (uint)_bcc.NumberOfChordValues, 0, 127, SetDialogState);
}
private void PitchwheelEnvelopesTextBox_Leave(object sender, EventArgs e)
{
GetEnvelopes(PitchwheelEnvelopesTextBox);
if(PitchwheelEnvelopesTextBox.Text.Length == 0)
PitchwheelDeviationsTextBox.Text = "";
}
private void PanEnvelopesTextBox_Leave(object sender, EventArgs e)
{
GetEnvelopes(PanEnvelopesTextBox);
}
private void ModulationWheelEnvelopesTextBox_Leave(object sender, EventArgs e)
{
GetEnvelopes(ModulationWheelEnvelopesTextBox);
}
private void ExpressionEnvelopesTextBox_Leave(object sender, EventArgs e)
{
GetEnvelopes(ExpressionEnvelopesTextBox);
}
private void OrnamentNumbersTextBox_Leave(object sender, EventArgs e)
{
if(OrnamentsForm != null && OrnamentsForm.Ornaments != null)
{
int nOrnaments = OrnamentsForm.Ornaments.Count;
M.LeaveIntRangeTextBox(sender as TextBox, false, (uint)_bcc.NumberOfChordValues, 0, nOrnaments, SetDialogState);
}
}
private void MinMsDurationsTextBox_Leave(object sender, EventArgs e)
{
M.LeaveIntRangeTextBox(sender as TextBox, true, (uint)_bcc.NumberOfChordValues, 0, int.MaxValue, SetDialogState);
}
#region helper functions
private void GetEnvelopes(TextBox textBox)
{
List<string> envelopes = GetEnvelopes(textBox.Text);
if(textBox.Text.Length > 0 && envelopes == null) // error
{
SetDialogState(textBox, false);
}
else
{
textBox.Text = TextBoxString(envelopes);
SetDialogState(textBox, true);
}
}
/// <summary>
/// Checks the input text for errors and converts it to a list of strings.
/// If text.Length == 0, an empty list is returned.
/// If there is an error in the input text, null is returned.
/// Each string in the result contains integers (in range [0..100]) separated by the ':' character.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private List<string> GetEnvelopes(string text)
{
List<string> returnList = new List<string>();
if(text.Length > 0)
{
StringBuilder envelopeSB = new StringBuilder();
if(text[text.Length - 1] == ',')
text = text.Remove(text.Length - 1);
string[] envelopes = text.Split(',');
if(envelopes.Length == _domain)
{
foreach(string envelope in envelopes)
{
envelopeSB.Remove(0, envelopeSB.Length);
List<string> numbers = GetCheckedIntStrings(envelope, -1, 0, 127, ':');
if(numbers != null)
{
foreach(string numberStr in numbers)
{
envelopeSB.Append(":");
envelopeSB.Append(numberStr);
}
envelopeSB.Remove(0, 1);
returnList.Add(envelopeSB.ToString());
}
else
{
returnList = null;
break;
}
}
}
else
{
returnList = null;
}
}
return returnList;
}
private string TextBoxString(List<string> envelopes)
{
StringBuilder textBoxSB = new StringBuilder();
if(envelopes.Count > 0)
{
foreach(string envelope in envelopes)
{
textBoxSB.Append(", ");
textBoxSB.Append(envelope);
}
textBoxSB.Remove(0, 3);
}
return textBoxSB.ToString();
}
/// <summary>
/// Returns null if textBox.Text is empty, or the contained values are outside the given range.
/// </summary>
private List<string> GetCheckedFloatStrings(string text, float minVal, float maxVal)
{
List<string> strings = new List<string>();
bool okay = true;
if(text.Length > 0)
{
try
{
List<float> floats = M.StringToFloatList(text, ',');
okay = CheckFloatList(floats, (int)_domain, minVal, maxVal);
if(okay)
{
foreach(float f in floats)
strings.Add(f.ToString(M.En_USNumberFormat));
}
}
catch
{
okay = false;
}
}
if(strings.Count > 0)
return strings;
else
return null;
}
/// <summary>
/// Returns null if textBox.Text is empty, or there are not count values separated by the separator
/// character, or the values are outside the given range.
/// To ignore the count parameter, pass count = -1.
/// Also used by the ornaments palette.
/// </summary>
public List<string> GetCheckedIntStrings(string text, int count, int minVal, int maxVal, char separator)
{
List<string> strings = new List<string>();
if(text.Length > 0)
{
List<int> ints = null;
try
{
ints = M.StringToIntList(text, separator);
}
catch
{
}
if(ints != null && CheckIntList(ints, count, minVal, maxVal))
{
foreach(int i in ints)
strings.Add(i.ToString());
}
}
if(strings.Count > 0)
return strings;
else return null;
}
private void SetDialogState(TextBox textBox, bool okay)
{
M.SetTextBoxErrorColorIfNotOkay(textBox, okay);
if(_paletteButtonsControl != null)
{
if(M.HasError(_allTextBoxes))
_paletteButtonsControl.Enabled = false;
else
_paletteButtonsControl.Enabled = true;
}
SetSettingsHaveChanged();
}
/// <summary>
/// Returns false if
/// count is not -1 and intList.Count is not count
/// or any value is less than minVal,
/// or any value is greater than maxVal.
/// Use count=-1 to ignore the count parameter.
/// </summary>
private bool CheckIntList(List<int> intList, int count, int minVal, int maxVal)
{
bool OK = true;
if(count != -1 && intList.Count != count)
OK = false;
else
{
foreach(int value in intList)
{
if(value < minVal || value > maxVal)
{
OK = false;
break;
}
}
}
return OK;
}
/// <summary>
/// Returne false if
/// floatList.Count != count
/// or any value is less than minVal,
/// or any value is greater than maxval.
/// </summary>
private bool CheckFloatList(List<float> floatList, int count, float minVal, float maxVal)
{
bool OK = true;
if(floatList.Count != count)
OK = false;
else
{
foreach(float value in floatList)
{
if(value < minVal || value > maxVal)
{
OK = false;
break;
}
}
}
return OK;
}
#endregion helper functions
#endregion text box events
/// <summary>
/// This form is deleted only by the AssistantComposer form.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Delete()
{
if(_ornamentsForm != null)
{
_fsf.Remove(_ornamentsForm);
_ornamentsForm.Close();
_ornamentsForm = null;
}
_fsf.Remove(this);
CloseMidiPitchesHelpForm();
CloseMIDIInstrumentsHelpForm();
this.Close();
}
#region ReviewableForm
public void SetSettingsHaveChanged()
{
_fsf.SetSettingsAreUnconfirmed(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
if(!_isLoading)
{
_hostForm.UpdateForChangedPaletteForm();
}
}
#endregion ReviewableForm
#region paletteForm
public override string ToString()
{
StringBuilder sb = new StringBuilder(Text);
if(_ornamentsForm != null)
{
sb.Append(" : ornaments");
if(_fsf.IsUnconfirmed(_ornamentsForm))
{
sb.Append(_fsf.UnconfirmedStr);
}
else if(_fsf.IsConfirmed(_ornamentsForm))
{
sb.Append(_fsf.ConfirmedStr);
}
}
return sb.ToString();
}
/// <summary>
/// Returns false if the file already exists and the user cancels the save.
/// </summary>
/// <returns></returns>
public void WritePalette(XmlWriter w)
{
w.WriteStartElement("palette");
w.WriteAttributeString("name", PaletteName);
w.WriteAttributeString("domain", _domain.ToString());
if(PercussionCheckBox.Checked)
{
w.WriteAttributeString("percussion", "1");
}
_bcc.WriteBasicChordControl(w);
if(!string.IsNullOrEmpty(this.BankIndicesTextBox.Text))
{
w.WriteStartElement("bankIndices");
w.WriteString(BankIndicesTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(!string.IsNullOrEmpty(this.PatchIndicesTextBox.Text))
{
w.WriteStartElement("patchIndices");
w.WriteString(PatchIndicesTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(!string.IsNullOrEmpty(PitchwheelDeviationsTextBox.Text))
{
w.WriteStartElement("pitchwheelDeviations");
w.WriteString(PitchwheelDeviationsTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(!string.IsNullOrEmpty(PitchwheelEnvelopesTextBox.Text))
{
w.WriteStartElement("pitchwheelEnvelopes");
w.WriteString(PitchwheelEnvelopesTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(!string.IsNullOrEmpty(PanEnvelopesTextBox.Text))
{
w.WriteStartElement("panEnvelopes");
w.WriteString(PanEnvelopesTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(!string.IsNullOrEmpty(ModulationWheelEnvelopesTextBox.Text))
{
w.WriteStartElement("modulationWheelEnvelopes");
w.WriteString(ModulationWheelEnvelopesTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(!string.IsNullOrEmpty(this.ExpressionEnvelopesTextBox.Text))
{
w.WriteStartElement("expressionEnvelopes");
w.WriteString(this.ExpressionEnvelopesTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(_paletteButtonsControl != null)
{
_paletteButtonsControl.WriteAudioFiles(w);
}
if(!string.IsNullOrEmpty(OrnamentNumbersTextBox.Text))
{
w.WriteStartElement("ornamentNumbers");
w.WriteString(OrnamentNumbersTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(!string.IsNullOrEmpty(this.MinMsDurationsTextBox.Text))
{
w.WriteStartElement("ornamentMinMsDurations");
w.WriteString(MinMsDurationsTextBox.Text.Replace(" ", ""));
w.WriteEndElement();
}
if(OrnamentsForm != null)
OrnamentsForm.WriteOrnamentSettingsForm(w);
w.WriteEndElement(); // closes the palette element
_fsf.SetSettingsAreSaved(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
}
public void ReadPalette(XmlReader r)
{
Debug.Assert(r.Name == "name" || r.Name == "domain" || r.Name == "percussion"); // attributes
Debug.Assert(_bcc != null);
#region
BankIndicesTextBox.Text = "";
PatchIndicesTextBox.Text = "";
PitchwheelDeviationsTextBox.Text = "";
PitchwheelEnvelopesTextBox.Text = "";
PanEnvelopesTextBox.Text = "";
ModulationWheelEnvelopesTextBox.Text = "";
ExpressionEnvelopesTextBox.Text = "";
OrnamentNumbersTextBox.Text = "";
MinMsDurationsTextBox.Text = "";
#endregion
M.ReadToXmlElementTag(r, "basicChord");
while(r.Name == "basicChord" || r.Name == "bankIndices" || r.Name == "patchIndices"
|| r.Name == "repeats" || r.Name == "pitchwheelDeviations"
|| r.Name == "pitchwheelEnvelopes" || r.Name == "panEnvelopes"
|| r.Name == "modulationWheelEnvelopes" || r.Name == "expressionEnvelopes"
|| r.Name == "audioFiles"
|| r.Name == "ornamentNumbers" || r.Name == "ornamentMinMsDurations"
|| r.Name == "ornamentSettings")
{
if(r.NodeType != XmlNodeType.EndElement)
{
switch(r.Name)
{
case "basicChord":
_bcc.ReadBasicChordControl(r);
break;
case "bankIndices":
BankIndicesTextBox.Text = r.ReadElementContentAsString();
break;
case "patchIndices":
PatchIndicesTextBox.Text = r.ReadElementContentAsString();
break;
case "pitchwheelDeviations":
PitchwheelDeviationsTextBox.Text = r.ReadElementContentAsString();
break;
case "pitchwheelEnvelopes":
PitchwheelEnvelopesTextBox.Text = r.ReadElementContentAsString();
break;
case "panEnvelopes":
PanEnvelopesTextBox.Text = r.ReadElementContentAsString();
break;
case "modulationWheelEnvelopes":
ModulationWheelEnvelopesTextBox.Text = r.ReadElementContentAsString();
break;
case "expressionEnvelopes":
ExpressionEnvelopesTextBox.Text = r.ReadElementContentAsString();
break;
case "audioFiles":
if(_paletteButtonsControl != null)
{
_paletteButtonsControl.ReadAudioFiles(r);
}
break;
case "ornamentNumbers":
OrnamentNumbersTextBox.Text = r.ReadElementContentAsString();
break;
case "ornamentMinMsDurations":
MinMsDurationsTextBox.Text = r.ReadElementContentAsString();
break;
case "ornamentSettings":
_ornamentsForm = new OrnamentsForm(r, this, _hostForm, _fsf);
ShowOrnamentSettingsButton.Enabled = true;
DeleteOrnamentSettingsButton.Enabled = true;
break;
}
}
M.ReadToXmlElementTag(r, "palette", "basicChord", "bankIndices", "patchIndices", "repeats",
"pitchwheelDeviations", "pitchwheelEnvelopes", "panEnvelopes", "modulationWheelEnvelopes",
"expressionEnvelopes", "audioFiles", "ornamentNumbers", "ornamentMinMsDurations", "ornamentSettings");
}
Debug.Assert(r.Name == "palette"); // end element
SetOrnamentControls();
TouchAllTextBoxes();
_fsf.SetSettingsAreSaved(this, M.HasError(_allTextBoxes), ConfirmButton, RevertToSavedButton);
}
private int _domain = 0;
private List<TextBox> _allTextBoxes = new List<TextBox>();
private PaletteButtonsControl _paletteButtonsControl = null;
#endregion paletteForm
#region public variables
public int Domain { get { return _domain; } }
public BasicChordControl BasicChordControl { get { return _bcc; } }
public OrnamentsForm OrnamentsForm { get { return _ornamentsForm; } }
public PaletteButtonsControl PaletteButtonsControl { get { return _paletteButtonsControl; } }
public bool IsPercussionPalette { get { return PercussionCheckBox.Checked; } }
public string PaletteName { get { return _savedName; } }
#endregion public variables
#region private variables
private IPaletteFormsHostForm _hostForm;
private int _numberOfOrnaments;
private OrnamentsForm _ornamentsForm = null;
private MidiPitchesHelpForm _midiPitchesHelpForm = null;
private MIDIInstrumentsHelpForm _midiInstrumentsHelpForm = null;
private MIDIPercussionHelpForm _percussionInstrHelpForm = null;
private BasicChordControl _bcc = null;
private PaletteChordForm _paletteChordForm = null;
private FormStateFunctions _fsf;
private string _savedName;
private bool _isLoading; // is true while the palettesForm is loading from a file, otherwise false
#endregion private variables
}
internal delegate void CloseMidiPitchesHelpFormDelegate();
internal delegate void CloseMIDIHelpFormDelegate();
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using IOleDataObject = Microsoft.VisualStudio.OLE.Interop.IDataObject;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// Manages the CopyPaste and Drag and Drop scenarios for a Project.
/// </summary>
/// <remarks>This is a partial class.</remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public partial class ProjectNode : IVsUIHierWinClipboardHelperEvents
{
#region fields
private uint copyPasteCookie;
private DropDataType dropDataType;
#endregion
#region override of IVsHierarchyDropDataTarget methods
/// <summary>
/// Called as soon as the mouse drags an item over a new hierarchy or hierarchy window
/// </summary>
/// <param name="pDataObject">reference to interface IDataObject of the item being dragged</param>
/// <param name="grfKeyState">Current state of the keyboard and the mouse modifier keys. See docs for a list of possible values</param>
/// <param name="itemid">Item identifier for the item currently being dragged</param>
/// <param name="pdwEffect">On entry, a pointer to the current DropEffect. On return, must contain the new valid DropEffect</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int DragEnter(IOleDataObject pDataObject, uint grfKeyState, uint itemid, ref uint pdwEffect)
{
pdwEffect = (uint)DropEffect.None;
// changed from MPFProj:
// http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=8145
/*
if(this.SourceDraggedOrCutOrCopied)
{
return VSConstants.S_OK;
}*/
this.dropDataType = QueryDropDataType(pDataObject);
if(this.dropDataType != DropDataType.None)
{
pdwEffect = (uint)this.QueryDropEffect(this.dropDataType, grfKeyState);
}
return VSConstants.S_OK;
}
/// <summary>
/// Called when one or more items are dragged out of the hierarchy or hierarchy window, or when the drag-and-drop operation is cancelled or completed.
/// </summary>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int DragLeave()
{
this.dropDataType = DropDataType.None;
return VSConstants.S_OK;
}
/// <summary>
/// Called when one or more items are dragged over the target hierarchy or hierarchy window.
/// </summary>
/// <param name="grfKeyState">Current state of the keyboard keys and the mouse modifier buttons. See <seealso cref="IVsHierarchyDropDataTarget"/></param>
/// <param name="itemid">Item identifier of the drop data target over which the item is being dragged</param>
/// <param name="pdwEffect"> On entry, reference to the value of the pdwEffect parameter of the IVsHierarchy object, identifying all effects that the hierarchy supports.
/// On return, the pdwEffect parameter must contain one of the effect flags that indicate the result of the drop operation. For a list of pwdEffects values, see <seealso cref="DragEnter"/></param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int DragOver(uint grfKeyState, uint itemid, ref uint pdwEffect)
{
pdwEffect = (uint)DropEffect.None;
// Dragging items to a project that is being debugged is not supported
// (see VSWhidbey 144785)
DBGMODE dbgMode = VsShellUtilities.GetDebugMode(this.Site) & ~DBGMODE.DBGMODE_EncMask;
if(dbgMode == DBGMODE.DBGMODE_Run || dbgMode == DBGMODE.DBGMODE_Break)
{
return VSConstants.S_OK;
}
if(this.isClosed || this.site == null)
{
return VSConstants.E_UNEXPECTED;
}
// We should also analyze if the node being dragged over can accept the drop.
if(!this.CanTargetNodeAcceptDrop(itemid))
{
return VSConstants.E_NOTIMPL;
}
if(this.dropDataType != DropDataType.None)
{
pdwEffect = (uint)this.QueryDropEffect(this.dropDataType, grfKeyState);
}
return VSConstants.S_OK;
}
/// <summary>
/// Called when one or more items are dropped into the target hierarchy or hierarchy window when the mouse button is released.
/// </summary>
/// <param name="pDataObject">Reference to the IDataObject interface on the item being dragged. This data object contains the data being transferred in the drag-and-drop operation.
/// If the drop occurs, then this data object (item) is incorporated into the target hierarchy or hierarchy window.</param>
/// <param name="grfKeyState">Current state of the keyboard and the mouse modifier keys. See <seealso cref="IVsHierarchyDropDataTarget"/></param>
/// <param name="itemid">Item identifier of the drop data target over which the item is being dragged</param>
/// <param name="pdwEffect">Visual effects associated with the drag-and drop-operation, such as a cursor, bitmap, and so on.
/// The value of dwEffects passed to the source object via the OnDropNotify method is the value of pdwEffects returned by the Drop method</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public override int Drop(IOleDataObject pDataObject, uint grfKeyState, uint itemid, ref uint pdwEffect)
{
if(pDataObject == null)
{
return VSConstants.E_INVALIDARG;
}
pdwEffect = (uint)DropEffect.None;
// Get the node that is being dragged over and ask it which node should handle this call
HierarchyNode targetNode = NodeFromItemId(itemid);
if(targetNode != null)
{
targetNode = targetNode.GetDragTargetHandlerNode();
}
else
{
// There is no target node. The drop can not be completed.
return VSConstants.S_FALSE;
}
int returnValue;
try
{
DropDataType dropDataType = DropDataType.None;
dropDataType = ProcessSelectionDataObject(pDataObject, targetNode);
pdwEffect = (uint)this.QueryDropEffect(dropDataType, grfKeyState);
// If it is a drop from windows and we get any kind of error we return S_FALSE and dropeffect none. This
// prevents bogus messages from the shell from being displayed
returnValue = (dropDataType != DropDataType.Shell) ? VSConstants.E_FAIL : VSConstants.S_OK;
}
catch(System.IO.FileNotFoundException e)
{
Trace.WriteLine("Exception : " + e.Message);
if(!Utilities.IsInAutomationFunction(this.Site))
{
string message = e.Message;
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
}
returnValue = VSConstants.E_FAIL;
}
return returnValue;
}
#endregion
#region override of IVsHierarchyDropDataSource2 methods
/// <summary>
/// Returns information about one or more of the items being dragged
/// </summary>
/// <param name="pdwOKEffects">Pointer to a DWORD value describing the effects displayed while the item is being dragged,
/// such as cursor icons that change during the drag-and-drop operation.
/// For example, if the item is dragged over an invalid target point
/// (such as the item's original location), the cursor icon changes to a circle with a line through it.
/// Similarly, if the item is dragged over a valid target point, the cursor icon changes to a file or folder.</param>
/// <param name="ppDataObject">Pointer to the IDataObject interface on the item being dragged.
/// This data object contains the data being transferred in the drag-and-drop operation.
/// If the drop occurs, then this data object (item) is incorporated into the target hierarchy or hierarchy window.</param>
/// <param name="ppDropSource">Pointer to the IDropSource interface of the item being dragged.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int GetDropInfo(out uint pdwOKEffects, out IOleDataObject ppDataObject, out IDropSource ppDropSource)
{
//init out params
pdwOKEffects = (uint)DropEffect.None;
ppDataObject = null;
ppDropSource = null;
IOleDataObject dataObject = PackageSelectionDataObject(false);
if(dataObject == null)
{
return VSConstants.E_NOTIMPL;
}
this.SourceDraggedOrCutOrCopied = true;
pdwOKEffects = (uint)(DropEffect.Move | DropEffect.Copy);
ppDataObject = dataObject;
return VSConstants.S_OK;
}
/// <summary>
/// Notifies clients that the dragged item was dropped.
/// </summary>
/// <param name="fDropped">If true, then the dragged item was dropped on the target. If false, then the drop did not occur.</param>
/// <param name="dwEffects">Visual effects associated with the drag-and-drop operation, such as cursors, bitmaps, and so on.
/// The value of dwEffects passed to the source object via OnDropNotify method is the value of pdwEffects returned by Drop method.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public override int OnDropNotify(int fDropped, uint dwEffects)
{
if(!this.SourceDraggedOrCutOrCopied)
{
return VSConstants.S_FALSE;
}
this.CleanupSelectionDataObject(fDropped != 0, false, dwEffects == (uint)DropEffect.Move);
this.SourceDraggedOrCutOrCopied = false;
return VSConstants.S_OK;
}
/// <summary>
/// Allows the drag source to prompt to save unsaved items being dropped.
/// Notifies the source hierarchy that information dragged from it is about to be dropped on a target.
/// This method is called immediately after the mouse button is released on a drop.
/// </summary>
/// <param name="o">Reference to the IDataObject interface on the item being dragged.
/// This data object contains the data being transferred in the drag-and-drop operation.
/// If the drop occurs, then this data object (item) is incorporated into the hierarchy window of the new hierarchy.</param>
/// <param name="dwEffect">Current state of the keyboard and the mouse modifier keys.</param>
/// <param name="fCancelDrop">If true, then the drop is cancelled by the source hierarchy. If false, then the drop can continue.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public override int OnBeforeDropNotify(IOleDataObject o, uint dwEffect, out int fCancelDrop)
{
// If there is nothing to be dropped just return that drop should be cancelled.
if(this.ItemsDraggedOrCutOrCopied == null)
{
fCancelDrop = 1;
return VSConstants.S_OK;
}
fCancelDrop = 0;
bool dirty = false;
foreach(HierarchyNode node in this.ItemsDraggedOrCutOrCopied)
{
bool isDirty, isOpen, isOpenedByUs;
uint docCookie;
IVsPersistDocData ppIVsPersistDocData;
DocumentManager manager = node.GetDocumentManager();
if(manager != null)
{
manager.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out ppIVsPersistDocData);
if(isDirty && isOpenedByUs)
{
dirty = true;
break;
}
}
}
// if there are no dirty docs we are ok to proceed
if(!dirty)
{
return VSConstants.S_OK;
}
// Prompt to save if there are dirty docs
string message = SR.GetString(SR.SaveModifiedDocuments, CultureInfo.CurrentUICulture);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_WARNING;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_YESNOCANCEL;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
int result = VsShellUtilities.ShowMessageBox(Site, title, message, icon, buttons, defaultButton);
switch(result)
{
case NativeMethods.IDYES:
break;
case NativeMethods.IDNO:
return VSConstants.S_OK;
case NativeMethods.IDCANCEL: goto default;
default:
fCancelDrop = 1;
return VSConstants.S_OK;
}
// Save all dirty documents
foreach(HierarchyNode node in this.ItemsDraggedOrCutOrCopied)
{
DocumentManager manager = node.GetDocumentManager();
if(manager != null)
{
manager.Save(true);
}
}
return VSConstants.S_OK;
}
#endregion
#region IVsUIHierWinClipboardHelperEvents Members
/// <summary>
/// Called after your cut/copied items has been pasted
/// </summary>
///<param name="wasCut">If true, then the IDataObject has been successfully pasted into a target hierarchy.
/// If false, then the cut or copy operation was cancelled.</param>
/// <param name="dropEffect">Visual effects associated with the drag and drop operation, such as cursors, bitmaps, and so on.
/// These should be the same visual effects used in OnDropNotify</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int OnPaste(int wasCut, uint dropEffect)
{
if(!this.SourceDraggedOrCutOrCopied)
{
return VSConstants.S_FALSE;
}
if(dropEffect == (uint)DropEffect.None)
{
return OnClear(wasCut);
}
this.CleanupSelectionDataObject(false, wasCut != 0, dropEffect == (uint)DropEffect.Move);
this.SourceDraggedOrCutOrCopied = false;
return VSConstants.S_OK;
}
/// <summary>
/// Called when your cut/copied operation is canceled
/// </summary>
/// <param name="wasCut">This flag informs the source that the Cut method was called (true),
/// rather than Copy (false), so the source knows whether to "un-cut-highlight" the items that were cut.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int OnClear(int wasCut)
{
if(!this.SourceDraggedOrCutOrCopied)
{
return VSConstants.S_FALSE;
}
this.CleanupSelectionDataObject(false, wasCut != 0, false, true);
this.SourceDraggedOrCutOrCopied = false;
return VSConstants.S_OK;
}
#endregion
#region virtual methods
/// <summary>
/// Determines if a node can accept drop opertaion.
/// </summary>
/// <param name="itemid">The id of the node.</param>
/// <returns>true if the node acceots drag operation.</returns>
protected internal virtual bool CanTargetNodeAcceptDrop(uint itemId)
{
HierarchyNode targetNode = NodeFromItemId(itemId);
if(targetNode is ReferenceContainerNode || targetNode is ReferenceNode)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Returns a dataobject from selected nodes
/// </summary>
/// <param name="cutHighlightItems">boolean that defines if the selected items must be cut</param>
/// <returns>data object for selected items</returns>
internal virtual DataObject PackageSelectionDataObject(bool cutHighlightItems)
{
this.CleanupSelectionDataObject(false, false, false);
StringBuilder sb = new StringBuilder();
DataObject dataObject = null;
try
{
IList<HierarchyNode> selectedNodes = this.GetSelectedNodes();
if(selectedNodes != null)
{
this.InstantiateItemsDraggedOrCutOrCopiedList();
StringBuilder selectionContent = null;
// If there is a selection package the data
if(selectedNodes.Count > 1)
{
foreach(HierarchyNode node in selectedNodes)
{
selectionContent = node.PrepareSelectedNodesForClipBoard();
if(selectionContent != null)
{
sb.Append(selectionContent);
}
}
}
else if(selectedNodes.Count == 1)
{
HierarchyNode selectedNode = selectedNodes[0];
selectionContent = selectedNode.PrepareSelectedNodesForClipBoard();
if(selectionContent != null)
{
sb.Append(selectionContent);
}
}
}
// Add the project items first.
IntPtr ptrToItems = this.PackageSelectionData(sb, false);
if(ptrToItems == IntPtr.Zero)
{
return null;
}
FORMATETC fmt = DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSSTGPROJECTITEMS);
dataObject = new DataObject();
dataObject.SetData(fmt, ptrToItems);
// Now add the project path that sourced data. We just write the project file path.
IntPtr ptrToProjectPath = this.PackageSelectionData(new StringBuilder(this.GetMkDocument()), true);
if(ptrToProjectPath != IntPtr.Zero)
{
dataObject.SetData(DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSPROJECTCLIPDESCRIPTOR), ptrToProjectPath);
}
if(cutHighlightItems)
{
bool first = true;
IVsUIHierarchyWindow w = UIHierarchyUtilities.GetUIHierarchyWindow(this.site, HierarchyNode.SolutionExplorer);
foreach(HierarchyNode node in this.ItemsDraggedOrCutOrCopied)
{
ErrorHandler.ThrowOnFailure(w.ExpandItem((IVsUIHierarchy)this, node.ID, first ? EXPANDFLAGS.EXPF_CutHighlightItem : EXPANDFLAGS.EXPF_AddCutHighlightItem));
first = false;
}
}
}
catch(COMException e)
{
Trace.WriteLine("Exception : " + e.Message);
dataObject = null;
}
return dataObject;
}
/// <summary>
/// This is used to recursively add a folder from an other project.
/// Note that while we copy the folder content completely, we only
/// add to the project items which are part of the source project.
/// </summary>
/// <param name="folderToAdd">Project reference (from data object) using the format: {Guid}|project|folderPath</param>
/// <param name="targetNode">Node to add the new folder to</param>
protected internal virtual void AddFolderFromOtherProject(string folderToAdd, HierarchyNode targetNode)
{
if(String.IsNullOrEmpty(folderToAdd))
throw new ArgumentNullException("folderToAdd");
if(targetNode == null)
throw new ArgumentNullException("targetNode");
// Split the reference in its 3 parts
int index1 = Guid.Empty.ToString("B").Length;
if(index1 + 1 >= folderToAdd.Length)
throw new ArgumentOutOfRangeException("folderToAdd");
// Get the Guid
string guidString = folderToAdd.Substring(1, index1 - 2);
Guid projectInstanceGuid = new Guid(guidString);
// Get the project path
int index2 = folderToAdd.IndexOf('|', index1 + 1);
if(index2 < 0 || index2 + 1 >= folderToAdd.Length)
throw new ArgumentOutOfRangeException("folderToAdd");
// Finally get the source path
string folder = folderToAdd.Substring(index2 + 1);
// Get the target path
string folderName = Path.GetFileName(Path.GetDirectoryName(folder));
string targetPath = Path.Combine(GetBaseDirectoryForAddingFiles(targetNode), folderName);
// Recursively copy the directory to the new location
Utilities.RecursivelyCopyDirectory(folder, targetPath);
// Retrieve the project from which the items are being copied
IVsHierarchy sourceHierarchy;
IVsSolution solution = (IVsSolution)GetService(typeof(SVsSolution));
ErrorHandler.ThrowOnFailure(solution.GetProjectOfGuid(ref projectInstanceGuid, out sourceHierarchy));
// Then retrieve the item ID of the item to copy
uint itemID = VSConstants.VSITEMID_ROOT;
ErrorHandler.ThrowOnFailure(sourceHierarchy.ParseCanonicalName(folder, out itemID));
// Ensure we don't end up in an endless recursion
if(Utilities.IsSameComObject(this, sourceHierarchy))
{
HierarchyNode cursorNode = targetNode;
while(cursorNode != null)
{
if(String.Compare(folder, cursorNode.GetMkDocument(), StringComparison.OrdinalIgnoreCase) == 0)
throw new Exception();
cursorNode = cursorNode.Parent;
}
}
// Now walk the source project hierarchy to see which node needs to be added.
WalkSourceProjectAndAdd(sourceHierarchy, itemID, targetNode, false);
}
/// <summary>
/// Recursive method that walk a hierarchy and add items it find to our project.
/// Note that this is meant as an helper to the Copy&Paste/Drag&Drop functionality.
/// </summary>
/// <param name="sourceHierarchy">Hierarchy to walk</param>
/// <param name="itemId">Item ID where to start walking the hierarchy</param>
/// <param name="targetNode">Node to start adding to</param>
/// <param name="addSibblings">Typically false on first call and true after that</param>
protected virtual void WalkSourceProjectAndAdd(IVsHierarchy sourceHierarchy, uint itemId, HierarchyNode targetNode, bool addSiblings)
{
if (sourceHierarchy == null)
{
throw new ArgumentNullException("sourceHierarchy");
}
// Before we start the walk, add the current node
object variant = null;
HierarchyNode newNode = targetNode;
if(itemId != VSConstants.VSITEMID_NIL)
{
// Calculate the corresponding path in our project
string source;
ErrorHandler.ThrowOnFailure(((IVsProject)sourceHierarchy).GetMkDocument(itemId, out source));
string name = Path.GetFileName(source.TrimEnd(new char[] { '/', '\\' }));
string targetPath = Path.Combine(GetBaseDirectoryForAddingFiles(targetNode), name);
// See if this is a linked item (file can be linked, not folders)
ErrorHandler.ThrowOnFailure(sourceHierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_BrowseObject, out variant), VSConstants.E_NOTIMPL);
VSLangProj.FileProperties fileProperties = variant as VSLangProj.FileProperties;
if(fileProperties != null && fileProperties.IsLink)
{
// Since we don't support linked item, we make a copy of the file into our storage where it would have been linked
File.Copy(source, targetPath, true);
}
newNode = AddNodeIfTargetExistInStorage(targetNode, name, targetPath);
// Start with child nodes (depth first)
variant = null;
ErrorHandler.ThrowOnFailure(sourceHierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_FirstVisibleChild, out variant));
uint currentItemID = (uint)(int)variant;
WalkSourceProjectAndAdd(sourceHierarchy, currentItemID, newNode, true);
if(addSiblings)
{
// Then look at siblings
currentItemID = itemId;
while(currentItemID != VSConstants.VSITEMID_NIL)
{
variant = null;
ErrorHandler.ThrowOnFailure(sourceHierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_NextVisibleSibling, out variant));
currentItemID = (uint)(int)variant;
WalkSourceProjectAndAdd(sourceHierarchy, currentItemID, targetNode, true);
}
}
}
}
/// <summary>
/// Add an existing item (file/folder) to the project if it already exist in our storage.
/// </summary>
/// <param name="parentNode">Node to that this item to</param>
/// <param name="name">Name of the item being added</param>
/// <param name="targetPath">Path of the item being added</param>
/// <returns>Node that was added</returns>
protected virtual HierarchyNode AddNodeIfTargetExistInStorage(HierarchyNode parentNode, string name, string targetPath)
{
if (parentNode == null)
{
return null;
}
HierarchyNode newNode = parentNode;
// If the file/directory exist, add a node for it
if(File.Exists(targetPath))
{
VSADDRESULT[] result = new VSADDRESULT[1];
ErrorHandler.ThrowOnFailure(this.AddItem(parentNode.ID, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, name, 1, new string[] { targetPath }, IntPtr.Zero, result));
if(result[0] != VSADDRESULT.ADDRESULT_Success)
throw new Exception();
newNode = this.FindChild(targetPath);
if(newNode == null)
throw new Exception();
}
else if(Directory.Exists(targetPath))
{
newNode = this.CreateFolderNodes(targetPath);
}
return newNode;
}
#endregion
#region non-virtual methods
/// <summary>
/// Handle the Cut operation to the clipboard
/// </summary>
protected internal override int CutToClipboard()
{
int returnValue = (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
try
{
this.RegisterClipboardNotifications(true);
// Create our data object and change the selection to show item(s) being cut
IOleDataObject dataObject = this.PackageSelectionDataObject(true);
if(dataObject != null)
{
this.SourceDraggedOrCutOrCopied = true;
// Add our cut item(s) to the clipboard
ErrorHandler.ThrowOnFailure(UnsafeNativeMethods.OleSetClipboard(dataObject));
// Inform VS (UiHierarchyWindow) of the cut
IVsUIHierWinClipboardHelper clipboardHelper = (IVsUIHierWinClipboardHelper)GetService(typeof(SVsUIHierWinClipboardHelper));
if(clipboardHelper == null)
{
return VSConstants.E_FAIL;
}
returnValue = ErrorHandler.ThrowOnFailure(clipboardHelper.Cut(dataObject));
}
}
catch(COMException e)
{
Trace.WriteLine("Exception : " + e.Message);
returnValue = e.ErrorCode;
}
return returnValue;
}
/// <summary>
/// Handle the Copy operation to the clipboard
/// </summary>
protected internal override int CopyToClipboard()
{
int returnValue = (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
try
{
this.RegisterClipboardNotifications(true);
// Create our data object and change the selection to show item(s) being copy
IOleDataObject dataObject = this.PackageSelectionDataObject(false);
if(dataObject != null)
{
this.SourceDraggedOrCutOrCopied = true;
// Add our copy item(s) to the clipboard
ErrorHandler.ThrowOnFailure(UnsafeNativeMethods.OleSetClipboard(dataObject));
// Inform VS (UiHierarchyWindow) of the copy
IVsUIHierWinClipboardHelper clipboardHelper = (IVsUIHierWinClipboardHelper)GetService(typeof(SVsUIHierWinClipboardHelper));
if(clipboardHelper == null)
{
return VSConstants.E_FAIL;
}
returnValue = ErrorHandler.ThrowOnFailure(clipboardHelper.Copy(dataObject));
}
}
catch(COMException e)
{
Trace.WriteLine("Exception : " + e.Message);
returnValue = e.ErrorCode;
}
catch(ArgumentException e)
{
Trace.WriteLine("Exception : " + e.Message);
returnValue = Marshal.GetHRForException(e);
}
return returnValue;
}
/// <summary>
/// Handle the Paste operation to a targetNode
/// </summary>
protected internal override int PasteFromClipboard(HierarchyNode targetNode)
{
int returnValue = (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
if (targetNode == null)
{
return VSConstants.E_INVALIDARG;
}
//Get the clipboardhelper service and use it after processing dataobject
IVsUIHierWinClipboardHelper clipboardHelper = (IVsUIHierWinClipboardHelper)GetService(typeof(SVsUIHierWinClipboardHelper));
if(clipboardHelper == null)
{
return VSConstants.E_FAIL;
}
try
{
//Get dataobject from clipboard
IOleDataObject dataObject = null;
ErrorHandler.ThrowOnFailure(UnsafeNativeMethods.OleGetClipboard(out dataObject));
if(dataObject == null)
{
return VSConstants.E_UNEXPECTED;
}
DropEffect dropEffect = DropEffect.None;
DropDataType dropDataType = DropDataType.None;
try
{
dropDataType = this.ProcessSelectionDataObject(dataObject, targetNode.GetDragTargetHandlerNode());
dropEffect = this.QueryDropEffect(dropDataType, 0);
}
catch(ExternalException e)
{
Trace.WriteLine("Exception : " + e.Message);
// If it is a drop from windows and we get any kind of error ignore it. This
// prevents bogus messages from the shell from being displayed
if(dropDataType != DropDataType.Shell)
{
throw;
}
}
finally
{
// Inform VS (UiHierarchyWindow) of the paste
returnValue = clipboardHelper.Paste(dataObject, (uint)dropEffect);
}
}
catch(COMException e)
{
Trace.WriteLine("Exception : " + e.Message);
returnValue = e.ErrorCode;
}
return returnValue;
}
/// <summary>
/// Determines if the paste command should be allowed.
/// </summary>
/// <returns></returns>
protected internal override bool AllowPasteCommand()
{
IOleDataObject dataObject = null;
try
{
ErrorHandler.ThrowOnFailure(UnsafeNativeMethods.OleGetClipboard(out dataObject));
if(dataObject == null)
{
return false;
}
// First see if this is a set of storage based items
FORMATETC format = DragDropHelper.CreateFormatEtc((ushort)DragDropHelper.CF_VSSTGPROJECTITEMS);
if(dataObject.QueryGetData(new FORMATETC[] { format }) == VSConstants.S_OK)
return true;
// Try reference based items
format = DragDropHelper.CreateFormatEtc((ushort)DragDropHelper.CF_VSREFPROJECTITEMS);
if(dataObject.QueryGetData(new FORMATETC[] { format }) == VSConstants.S_OK)
return true;
// Try windows explorer files format
format = DragDropHelper.CreateFormatEtc((ushort)NativeMethods.CF_HDROP);
return (dataObject.QueryGetData(new FORMATETC[] { format }) == VSConstants.S_OK);
}
// We catch External exceptions since it might be that it is not our data on the clipboard.
catch(ExternalException e)
{
Trace.WriteLine("Exception :" + e.Message);
return false;
}
}
/// <summary>
/// Register/Unregister for Clipboard events for the UiHierarchyWindow (solution explorer)
/// </summary>
/// <param name="register">true for register, false for unregister</param>
protected internal override void RegisterClipboardNotifications(bool register)
{
// Get the UiHierarchy window clipboard helper service
IVsUIHierWinClipboardHelper clipboardHelper = (IVsUIHierWinClipboardHelper)GetService(typeof(SVsUIHierWinClipboardHelper));
if(clipboardHelper == null)
{
return;
}
if(register && this.copyPasteCookie == 0)
{
// Register
ErrorHandler.ThrowOnFailure(clipboardHelper.AdviseClipboardHelperEvents(this, out this.copyPasteCookie));
Debug.Assert(this.copyPasteCookie != 0, "AdviseClipboardHelperEvents returned an invalid cookie");
}
else if(!register && this.copyPasteCookie != 0)
{
// Unregister
ErrorHandler.ThrowOnFailure(clipboardHelper.UnadviseClipboardHelperEvents(this.copyPasteCookie));
this.copyPasteCookie = 0;
}
}
/// <summary>
/// Process dataobject from Drag/Drop/Cut/Copy/Paste operation
/// </summary>
/// <remarks>The targetNode is set if the method is called from a drop operation, otherwise it is null</remarks>
internal DropDataType ProcessSelectionDataObject(IOleDataObject dataObject, HierarchyNode targetNode)
{
DropDataType dropDataType = DropDataType.None;
bool isWindowsFormat = false;
// Try to get it as a directory based project.
List<string> filesDropped = DragDropHelper.GetDroppedFiles(DragDropHelper.CF_VSSTGPROJECTITEMS, dataObject, out dropDataType);
if(filesDropped.Count == 0)
{
filesDropped = DragDropHelper.GetDroppedFiles(DragDropHelper.CF_VSREFPROJECTITEMS, dataObject, out dropDataType);
}
if(filesDropped.Count == 0)
{
filesDropped = DragDropHelper.GetDroppedFiles(NativeMethods.CF_HDROP, dataObject, out dropDataType);
isWindowsFormat = (filesDropped.Count > 0);
}
if(dropDataType != DropDataType.None && filesDropped.Count > 0)
{
string[] filesDroppedAsArray = filesDropped.ToArray();
HierarchyNode node = (targetNode == null) ? this : targetNode;
// For directory based projects the content of the clipboard is a double-NULL terminated list of Projref strings.
if(isWindowsFormat)
{
// This is the code path when source is windows explorer
VSADDRESULT[] vsaddresults = new VSADDRESULT[1];
vsaddresults[0] = VSADDRESULT.ADDRESULT_Failure;
int addResult = AddItem(node.ID, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, (uint)filesDropped.Count, filesDroppedAsArray, IntPtr.Zero, vsaddresults);
if(addResult != VSConstants.S_OK && addResult != VSConstants.S_FALSE && addResult != (int)OleConstants.OLECMDERR_E_CANCELED
&& vsaddresults[0] != VSADDRESULT.ADDRESULT_Success)
{
ErrorHandler.ThrowOnFailure(addResult);
}
return dropDataType;
}
else
{
if(AddFilesFromProjectReferences(node, filesDroppedAsArray))
{
return dropDataType;
}
}
}
// If we reached this point then the drop data must be set to None.
// Otherwise the OnPaste will be called with a valid DropData and that would actually delete the item.
return DropDataType.None;
}
/// <summary>
/// Get the dropdatatype from the dataobject
/// </summary>
/// <param name="pDataObject">The dataobject to be analysed for its format</param>
/// <returns>dropdatatype or none if dataobject does not contain known format</returns>
internal static DropDataType QueryDropDataType(IOleDataObject pDataObject)
{
if(pDataObject == null)
{
return DropDataType.None;
}
// known formats include File Drops (as from WindowsExplorer),
// VSProject Reference Items and VSProject Storage Items.
FORMATETC fmt = DragDropHelper.CreateFormatEtc(NativeMethods.CF_HDROP);
if(DragDropHelper.QueryGetData(pDataObject, ref fmt) == VSConstants.S_OK)
{
return DropDataType.Shell;
}
fmt.cfFormat = DragDropHelper.CF_VSREFPROJECTITEMS;
if(DragDropHelper.QueryGetData(pDataObject, ref fmt) == VSConstants.S_OK)
{
// Data is from a Ref-based project.
return DropDataType.VsRef;
}
fmt.cfFormat = DragDropHelper.CF_VSSTGPROJECTITEMS;
if(DragDropHelper.QueryGetData(pDataObject, ref fmt) == VSConstants.S_OK)
{
return DropDataType.VsStg;
}
return DropDataType.None;
}
/// <summary>
/// Returns the drop effect.
/// </summary>
/// <remarks>
/// // A directory based project should perform as follow:
/// NO MODIFIER
/// - COPY if not from current hierarchy,
/// - MOVE if from current hierarchy
/// SHIFT DRAG - MOVE
/// CTRL DRAG - COPY
/// CTRL-SHIFT DRAG - NO DROP (used for reference based projects only)
/// </remarks>
internal DropEffect QueryDropEffect(DropDataType dropDataType, uint grfKeyState)
{
//Validate the dropdatatype
if((dropDataType != DropDataType.Shell) && (dropDataType != DropDataType.VsRef) && (dropDataType != DropDataType.VsStg))
{
return DropEffect.None;
}
// CTRL-SHIFT
if((grfKeyState & NativeMethods.MK_CONTROL) != 0 && (grfKeyState & NativeMethods.MK_SHIFT) != 0)
{
// Because we are not referenced base, we don't support link
return DropEffect.None;
}
// CTRL
if((grfKeyState & NativeMethods.MK_CONTROL) != 0)
return DropEffect.Copy;
// SHIFT
if((grfKeyState & NativeMethods.MK_SHIFT) != 0)
return DropEffect.Move;
// no modifier
if(this.SourceDraggedOrCutOrCopied)
{
return DropEffect.Move;
}
else
{
return DropEffect.Copy;
}
}
internal void CleanupSelectionDataObject(bool dropped, bool cut, bool moved)
{
this.CleanupSelectionDataObject(dropped, cut, moved, false);
}
/// <summary>
/// After a drop or paste, will use the dwEffects
/// to determine whether we need to clean up the source nodes or not. If
/// justCleanup is set, it only does the cleanup work.
/// </summary>
internal void CleanupSelectionDataObject(bool dropped, bool cut, bool moved, bool justCleanup)
{
if(this.ItemsDraggedOrCutOrCopied == null || this.ItemsDraggedOrCutOrCopied.Count == 0)
{
return;
}
try
{
IVsUIHierarchyWindow w = UIHierarchyUtilities.GetUIHierarchyWindow(this.site, HierarchyNode.SolutionExplorer);
foreach(HierarchyNode node in this.ItemsDraggedOrCutOrCopied)
{
if((moved && (cut || dropped) && !justCleanup))
{
// do not close it if the doc is dirty or we do not own it
bool isDirty, isOpen, isOpenedByUs;
uint docCookie;
IVsPersistDocData ppIVsPersistDocData;
DocumentManager manager = node.GetDocumentManager();
if(manager != null)
{
manager.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out ppIVsPersistDocData);
if(isDirty || (isOpen && !isOpenedByUs))
{
continue;
}
// close it if opened
if(isOpen)
{
manager.Close(__FRAMECLOSE.FRAMECLOSE_NoSave);
}
}
node.Remove(true);
}
else if(w != null)
{
ErrorHandler.ThrowOnFailure(w.ExpandItem((IVsUIHierarchy)this, node.ID, EXPANDFLAGS.EXPF_UnCutHighlightItem));
}
}
}
finally
{
try
{
// Now delete the memory allocated by the packaging of datasources.
// If we just did a cut, or we are told to cleanup, then we need to free the data object. Otherwise, we leave it
// alone so that you can continue to paste the data in new locations.
if(moved || cut || justCleanup)
{
this.ItemsDraggedOrCutOrCopied.Clear();
this.CleanAndFlushClipboard();
}
}
finally
{
this.dropDataType = DropDataType.None;
}
}
}
/// <summary>
/// Moves files from one part of our project to another.
/// </summary>
/// <param name="targetNode">the targetHandler node</param>
/// <param name="projectReferences">List of projectref string</param>
/// <returns>true if succeeded</returns>
internal bool AddFilesFromProjectReferences(HierarchyNode targetNode, string[] projectReferences)
{
//Validate input
if(projectReferences == null)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "projectReferences");
}
if(targetNode == null)
{
throw new InvalidOperationException();
}
//Iteratively add files from projectref
foreach(string projectReference in projectReferences)
{
if(projectReference == null)
{
// bad projectref, bail out
return false;
}
if(projectReference.EndsWith("/", StringComparison.Ordinal) || projectReference.EndsWith("\\", StringComparison.Ordinal))
{
AddFolderFromOtherProject(projectReference, targetNode);
}
else if(!AddFileToNodeFromProjectReference(projectReference, targetNode))
{
return false;
}
}
return true;
}
#endregion
#region private helper methods
/// <summary>
/// Empties all the data structures added to the clipboard and flushes the clipboard.
/// </summary>
private void CleanAndFlushClipboard()
{
IOleDataObject oleDataObject = null;
ErrorHandler.ThrowOnFailure(UnsafeNativeMethods.OleGetClipboard(out oleDataObject));
if(oleDataObject == null)
{
return;
}
string sourceProjectPath = DragDropHelper.GetSourceProjectPath(oleDataObject);
if(!String.IsNullOrEmpty(sourceProjectPath) && NativeMethods.IsSamePath(sourceProjectPath, this.GetMkDocument()))
{
ErrorHandler.ThrowOnFailure(UnsafeNativeMethods.OleFlushClipboard());
int clipboardOpened = 0;
try
{
ErrorHandler.ThrowOnFailure(clipboardOpened = UnsafeNativeMethods.OpenClipboard(IntPtr.Zero));
ErrorHandler.ThrowOnFailure(UnsafeNativeMethods.EmptyClipboard());
}
finally
{
if(clipboardOpened == 1)
{
ErrorHandler.ThrowOnFailure(UnsafeNativeMethods.CloseClipboard());
}
}
}
}
private IntPtr PackageSelectionData(StringBuilder sb, bool addEndFormatDelimiter)
{
if(sb == null || sb.ToString().Length == 0 || this.ItemsDraggedOrCutOrCopied.Count == 0)
{
return IntPtr.Zero;
}
// Double null at end.
if(addEndFormatDelimiter)
{
if(sb.ToString()[sb.Length - 1] != '\0')
{
sb.Append('\0');
}
}
// We request unmanaged permission to execute the below.
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
_DROPFILES df = new _DROPFILES();
int dwSize = Marshal.SizeOf(df);
Int16 wideChar = 0;
int dwChar = Marshal.SizeOf(wideChar);
int structSize = dwSize + ((sb.Length + 1) * dwChar);
IntPtr ptr = Marshal.AllocHGlobal(structSize);
df.pFiles = dwSize;
df.fWide = 1;
IntPtr data = IntPtr.Zero;
try
{
data = UnsafeNativeMethods.GlobalLock(ptr);
Marshal.StructureToPtr(df, data, false);
IntPtr strData = new IntPtr((long)data + dwSize);
DragDropHelper.CopyStringToHGlobal(sb.ToString(), strData, structSize);
}
finally
{
if(data != IntPtr.Zero)
UnsafeNativeMethods.GlobalUnLock(data);
}
return ptr;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.Json;
using System;
using System.Collections.Generic;
namespace ReactNative.UIManager
{
/// <summary>
/// Class responsible for knowing how to create and update views of a given
/// type. It is also responsible for creating and updating
/// <see cref="ReactShadowNode"/> subclasses used for calculating position
/// and size for the corresponding native view.
/// </summary>
public abstract class ViewManagerBase<TView, TReactShadowNode> : IViewManager
where TReactShadowNode : ReactShadowNode
{
/// <summary>
/// The name of this view manager. This will be the name used to
/// reference this view manager from JavaScript.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// The <see cref="Type"/> instance that represents the type of shadow
/// node that this manager will return from
/// <see cref="CreateShadowNodeInstance"/>.
///
/// This method will be used in the bridge initialization phase to
/// collect props exposed using the <see cref="Annotations.ReactPropAttribute"/>
/// annotation from the <see cref="ReactShadowNode"/> subclass.
/// </summary>
public virtual Type ShadowNodeType => typeof(TReactShadowNode);
/// <summary>
/// The commands map for the view manager.
/// </summary>
[Obsolete("Use 'ViewCommandsMap' instead.")]
public virtual IReadOnlyDictionary<string, object> CommandsMap { get; }
/// <summary>
/// The commands map for the view manager.
/// </summary>
public virtual JObject ViewCommandsMap { get; }
/// <summary>
/// The exported custom bubbling event types.
/// </summary>
[Obsolete("Use 'CustomBubblingEventTypeConstants' instead.")]
public virtual IReadOnlyDictionary<string, object> ExportedCustomBubblingEventTypeConstants { get; }
/// <summary>
/// The exported custom bubbling event types.
/// </summary>
public virtual JObject CustomBubblingEventTypeConstants { get; }
/// <summary>
/// The exported custom direct event types.
/// </summary>
[Obsolete("Use 'CustomDirectEventTypeConstants' instead.")]
public virtual IReadOnlyDictionary<string, object> ExportedCustomDirectEventTypeConstants { get; }
/// <summary>
/// The exported custom direct event types.
/// </summary>
public virtual JObject CustomDirectEventTypeConstants { get; }
/// <summary>
/// The exported view constants.
/// </summary>
[Obsolete("Use 'ViewConstants' instead.")]
public virtual IReadOnlyDictionary<string, object> ExportedViewConstants { get; }
/// <summary>
/// The exported view constants.
/// </summary>
public virtual JObject ViewConstants { get; }
/// <summary>
/// Creates a view and installs event emitters on it.
/// </summary>
/// <param name="reactContext">The context.</param>
/// <returns>The view.</returns>
public virtual TView CreateView(ThemedReactContext reactContext)
{
var view = CreateViewInstance(reactContext);
OnViewInstanceCreated(reactContext, view);
AddEventEmitters(reactContext, view);
// TODO: enable touch intercepting view parents
return view;
}
/// <summary>
/// Called when view is detached from view hierarchy and allows for
/// additional cleanup by the <see cref="IViewManager"/> subclass.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view.</param>
public virtual void OnDropViewInstance(ThemedReactContext reactContext, TView view)
{
}
/// <summary>
/// This method should return the subclass of <see cref="ReactShadowNode"/>
/// which will be then used for measuring the position and size of the
/// view.
/// </summary>
/// <remarks>
/// In most cases, this will just return an instance of
/// <see cref="ReactShadowNode"/>.
/// </remarks>
/// <returns>The shadow node instance.</returns>
public abstract TReactShadowNode CreateShadowNodeInstance();
/// <summary>
/// Implement this method to receive optional extra data enqueued from
/// the corresponding instance of <see cref="ReactShadowNode"/> in
/// <see cref="ReactShadowNode.OnCollectExtraUpdates"/>.
/// </summary>
/// <param name="root">The root view.</param>
/// <param name="extraData">The extra data.</param>
public abstract void UpdateExtraData(TView root, object extraData);
/// <summary>
/// Implement this method to receive events/commands directly from
/// JavaScript through the <see cref="UIManagerModule"/>.
/// </summary>
/// <param name="view">
/// The view instance that should receive the command.
/// </param>
/// <param name="commandId">Identifer for the command.</param>
/// <param name="args">Optional arguments for the command.</param>
public virtual void ReceiveCommand(TView view, int commandId, JArray args)
{
}
/// <summary>
/// Gets the dimensions of the view.
/// </summary>
/// <param name="view">The view.</param>
/// <returns>The view dimensions.</returns>
public abstract Dimensions GetDimensions(TView view);
/// <summary>
/// Sets the dimensions of the view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="dimensions">The output buffer.</param>
public abstract void SetDimensions(TView view, Dimensions dimensions);
/// <summary>
/// Creates a new view instance of type <typeparamref name="TView"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <returns>The view instance.</returns>
protected abstract TView CreateViewInstance(ThemedReactContext reactContext);
/// <summary>
/// Subclasses can override this method to install custom event
/// emitters on the given view.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view instance.</param>
/// <remarks>
/// Consider overriding this method if your view needs to emit events
/// besides basic touch events to JavaScript (e.g., scroll events).
/// </remarks>
protected virtual void AddEventEmitters(ThemedReactContext reactContext, TView view)
{
}
/// <summary>
/// Callback that will be triggered after all props are updated in
/// the current update transation (all <see cref="Annotations.ReactPropAttribute"/> handlers
/// for props updated in the current transaction have been called).
/// </summary>
/// <param name="view">The view.</param>
protected virtual void OnAfterUpdateTransaction(TView view)
{
}
internal virtual void OnViewInstanceCreated(ThemedReactContext reactContext, TView view)
{
}
#region IViewManager
JObject IViewManager.NativeProps
{
get
{
return ViewManagersPropCache.GetNativePropsForView<TView>(GetType(), ShadowNodeType);
}
}
#pragma warning disable CS0618 // Type or member is obsolete
JObject IViewManager.CommandsMap
{
get
{
return OneOf(ViewCommandsMap, CommandsMap);
}
}
JObject IViewManager.ExportedCustomBubblingEventTypeConstants
{
get
{
return OneOf(CustomBubblingEventTypeConstants, ExportedCustomBubblingEventTypeConstants);
}
}
JObject IViewManager.ExportedCustomDirectEventTypeConstants
{
get
{
return OneOf(CustomDirectEventTypeConstants, ExportedCustomDirectEventTypeConstants);
}
}
JObject IViewManager.ExportedViewConstants
{
get
{
return OneOf(ViewConstants, ExportedViewConstants);
}
}
#pragma warning restore CS0618 // Type or member is obsolete
void IViewManager.UpdateProps(object viewToUpdate, JObject props)
{
var propSetters =
ViewManagersPropCache.GetNativePropSettersForViewManagerType<TView>(GetType());
var keys = props.Keys();
foreach (var key in keys)
{
var setter = default(IPropSetter);
if (propSetters.TryGetValue(key, out setter))
{
setter.UpdateViewManagerProp(this, viewToUpdate, props);
}
}
OnAfterUpdateTransaction((TView)viewToUpdate);
}
object IViewManager.CreateView(ThemedReactContext reactContext)
{
return CreateView(reactContext);
}
void IViewManager.OnDropViewInstance(ThemedReactContext reactContext, object view)
{
OnDropViewInstance(reactContext, (TView)view);
}
ReactShadowNode IViewManager.CreateShadowNodeInstance()
{
return CreateShadowNodeInstance();
}
void IViewManager.UpdateExtraData(object root, object extraData)
{
UpdateExtraData((TView)root, extraData);
}
void IViewManager.ReceiveCommand(object view, int commandId, JArray args)
{
ReceiveCommand((TView)view, commandId, args);
}
Dimensions IViewManager.GetDimensions(object view)
{
return GetDimensions((TView)view);
}
void IViewManager.SetDimensions(object view, Dimensions dimensions)
{
SetDimensions((TView)view, dimensions);
}
#endregion
#region Constants Helpers
private static JObject OneOf(JObject json, IReadOnlyDictionary<string, object> map)
{
if (map != null && json != null)
{
throw new NotSupportedException("Do not override both JObject and dictionary constants properties.");
}
return json ?? (map != null ? JObject.FromObject(map) : null);
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using JetBrains.Annotations;
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Config;
using NLog.Filters;
using NLog.Internal;
using NLog.Targets;
/// <summary>
/// Implementation of logging engine.
/// </summary>
internal static class LoggerImpl
{
private const int StackTraceSkipMethods = 0;
private static readonly Assembly nlogAssembly = typeof(LoggerImpl).Assembly;
private static readonly Assembly mscorlibAssembly = typeof(string).Assembly;
private static readonly Assembly systemAssembly = typeof(Debug).Assembly;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using 'NLog' in message.")]
internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
{
if (targets == null)
{
return;
}
StackTraceUsage stu = targets.GetStackTraceUsage();
if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
{
StackTrace stackTrace;
#if !SILVERLIGHT
stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
stackTrace = new StackTrace();
#endif
int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);
logEvent.SetStackTrace(stackTrace, firstUserFrame);
}
int originalThreadId = Thread.CurrentThread.ManagedThreadId;
AsyncContinuation exceptionHandler = ex =>
{
if (ex != null)
{
if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId)
{
throw new NLogRuntimeException("Exception occurred in NLog", ex);
}
}
};
for (var t = targets; t != null; t = t.NextInChain)
{
if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
{
break;
}
}
}
/// <summary>
/// Finds first user stack frame in a stack trace
/// </summary>
/// <param name="stackTrace">The stack trace of the logging method invocation</param>
/// <param name="loggerType">Type of the logger or logger wrapper</param>
/// <returns>Index of the first user stack frame or 0 if all stack frames are non-user</returns>
/// <seealso cref="IsNonUserStackFrame"/>
private static int FindCallingMethodOnStackTrace([NotNull] StackTrace stackTrace, [NotNull] Type loggerType)
{
int? firstUserFrame = null;
for (int i = 0; i < stackTrace.FrameCount; ++i)
{
StackFrame frame = stackTrace.GetFrame(i);
MethodBase mb = frame.GetMethod();
if (IsNonUserStackFrame(mb, loggerType))
firstUserFrame = i + 1;
else if (firstUserFrame != null)
return firstUserFrame.Value;
}
return 0;
}
/// <summary>
/// Defines whether a stack frame belongs to non-user code
/// </summary>
/// <param name="method">Method of the stack frame</param>
/// <param name="loggerType">Type of the logger or logger wrapper</param>
/// <returns><see langword="true"/>, if the method is from non-user code and should be skipped</returns>
/// <remarks>
/// The method is classified as non-user if its declaring assembly is from hidden assemblies list
/// or its declaring type is <paramref name="loggerType"/> or one of its subtypes.
/// </remarks>
private static bool IsNonUserStackFrame([NotNull] MethodBase method, [NotNull] Type loggerType)
{
var declaringType = method.DeclaringType;
// get assembly by declaring type or by module for global methods
var assembly = declaringType != null ? declaringType.Assembly : method.Module.Assembly;
// skip stack frame if the method declaring type assembly is from hidden assemblies list
if (SkipAssembly(assembly)) return true;
// or if that type is the loggerType or one of its subtypes
return declaringType != null && loggerType.IsAssignableFrom(declaringType);
}
private static bool SkipAssembly(Assembly assembly)
{
if (assembly == nlogAssembly)
{
return true;
}
if (assembly == mscorlibAssembly)
{
return true;
}
if (assembly == systemAssembly)
{
return true;
}
if (LogManager.IsHiddenAssembly(assembly))
{
return true;
}
return false;
}
private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
{
Target target = targetListHead.Target;
FilterResult result = GetFilterResult(targetListHead.FilterChain, logEvent);
if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal))
{
if (InternalLogger.IsDebugEnabled)
{
InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level);
}
if (result == FilterResult.IgnoreFinal)
{
return false;
}
return true;
}
target.WriteAsyncLogEvent(logEvent.WithContinuation(onException));
if (result == FilterResult.LogFinal)
{
return false;
}
return true;
}
/// <summary>
/// Gets the filter result.
/// </summary>
/// <param name="filterChain">The filter chain.</param>
/// <param name="logEvent">The log event.</param>
/// <returns>The result of the filter.</returns>
private static FilterResult GetFilterResult(IEnumerable<Filter> filterChain, LogEventInfo logEvent)
{
FilterResult result = FilterResult.Neutral;
try
{
foreach (Filter f in filterChain)
{
result = f.GetFilterResult(logEvent);
if (result != FilterResult.Neutral)
{
break;
}
}
return result;
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Exception during filter evaluation: {0}", exception);
return FilterResult.Ignore;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using Xunit;
using System.Text;
namespace System.IO.FileSystem.DriveInfoTests
{
public class DriveInfoWindowsTests
{
[Theory]
[InlineData(":")]
[InlineData("://")]
[InlineData(@":\")]
[InlineData(":/")]
[InlineData(@":\\")]
[InlineData("Az")]
[InlineData("1")]
[InlineData("a1")]
[InlineData(@"\\share")]
[InlineData(@"\\")]
[InlineData("c ")]
[InlineData("")]
[InlineData(" c")]
public void Ctor_InvalidPath_ThrowsArgumentException(string driveName)
{
AssertExtensions.Throws<ArgumentException>("driveName", null, () => new DriveInfo(driveName));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestConstructor()
{
string[] variableInput = { "{0}", "{0}", "{0}:", "{0}:", @"{0}:\", @"{0}:\\", "{0}://" };
// Test Null
Assert.Throws<ArgumentNullException>(() => { new DriveInfo(null); });
// Test Valid DriveLetter
var validDriveLetter = GetValidDriveLettersOnMachine().First();
foreach (var input in variableInput)
{
string name = string.Format(input, validDriveLetter);
DriveInfo dInfo = new DriveInfo(name);
Assert.Equal(string.Format(@"{0}:\", validDriveLetter), dInfo.Name);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestGetDrives()
{
var validExpectedDrives = GetValidDriveLettersOnMachine();
var validActualDrives = DriveInfo.GetDrives();
// Test count
Assert.Equal(validExpectedDrives.Count(), validActualDrives.Count());
for (int i = 0; i < validActualDrives.Count(); i++)
{
// Test if the driveletter is correct
Assert.Contains(validActualDrives[i].Name[0], validExpectedDrives);
}
}
[Fact]
public void TestDriveProperties_AppContainer()
{
DriveInfo validDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First();
bool isReady = validDrive.IsReady;
Assert.NotNull(validDrive.Name);
Assert.NotNull(validDrive.RootDirectory.Name);
if (PlatformDetection.IsInAppContainer)
{
Assert.Throws<UnauthorizedAccessException>(() => validDrive.AvailableFreeSpace);
Assert.Throws<UnauthorizedAccessException>(() => validDrive.DriveFormat);
Assert.Throws<UnauthorizedAccessException>(() => validDrive.TotalFreeSpace);
Assert.Throws<UnauthorizedAccessException>(() => validDrive.TotalSize);
Assert.Throws<UnauthorizedAccessException>(() => validDrive.VolumeLabel);
}
else
{
Assert.NotNull(validDrive.DriveFormat);
Assert.True(validDrive.AvailableFreeSpace > 0);
Assert.True(validDrive.TotalFreeSpace > 0);
Assert.True(validDrive.TotalSize > 0);
Assert.NotNull(validDrive.VolumeLabel);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestDriveFormat()
{
DriveInfo validDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First();
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
bool r = GetVolumeInformation(validDrive.Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
var fileSystem = fileSystemName.ToString();
if (r)
{
Assert.Equal(fileSystem, validDrive.DriveFormat);
}
else
{
Assert.Throws<IOException>(() => validDrive.DriveFormat);
}
// Test Invalid drive
var invalidDrive = new DriveInfo(GetInvalidDriveLettersOnMachine().First().ToString());
Assert.Throws<DriveNotFoundException>(() => invalidDrive.DriveFormat);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestDriveType()
{
var validDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First();
var expectedDriveType = GetDriveType(validDrive.Name);
Assert.Equal((DriveType)expectedDriveType, validDrive.DriveType);
// Test Invalid drive
var invalidDrive = new DriveInfo(GetInvalidDriveLettersOnMachine().First().ToString());
Assert.Equal(DriveType.NoRootDirectory, invalidDrive.DriveType);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestValidDiskSpaceProperties()
{
bool win32Result;
long fbUser = -1;
long tbUser;
long fbTotal;
DriveInfo drive;
drive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First();
if (drive.IsReady)
{
win32Result = GetDiskFreeSpaceEx(drive.Name, out fbUser, out tbUser, out fbTotal);
Assert.True(win32Result);
if (fbUser != drive.AvailableFreeSpace)
Assert.True(drive.AvailableFreeSpace >= 0);
// valid property getters shouldn't throw
string name = drive.Name;
string format = drive.DriveFormat;
Assert.Equal(name, drive.ToString());
// totalsize should not change for a fixed drive.
Assert.Equal(tbUser, drive.TotalSize);
if (fbTotal != drive.TotalFreeSpace)
Assert.True(drive.TotalFreeSpace >= 0);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestInvalidDiskProperties()
{
string invalidDriveName = GetInvalidDriveLettersOnMachine().First().ToString();
var invalidDrive = new DriveInfo(invalidDriveName);
Assert.Throws<DriveNotFoundException>(() => invalidDrive.AvailableFreeSpace);
Assert.Throws<DriveNotFoundException>(() => invalidDrive.DriveFormat);
Assert.Equal(DriveType.NoRootDirectory, invalidDrive.DriveType);
Assert.False(invalidDrive.IsReady);
Assert.Equal(invalidDriveName + ":\\", invalidDrive.Name);
Assert.Equal(invalidDriveName + ":\\", invalidDrive.ToString());
Assert.Equal(invalidDriveName + ":\\", invalidDrive.RootDirectory.FullName);
Assert.Throws<DriveNotFoundException>(() => invalidDrive.TotalFreeSpace);
Assert.Throws<DriveNotFoundException>(() => invalidDrive.TotalSize);
Assert.Throws<DriveNotFoundException>(() => invalidDrive.VolumeLabel);
Assert.Throws<DriveNotFoundException>(() => invalidDrive.VolumeLabel = null);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetVolumeLabel_Returns_CorrectLabel()
{
void DoDriveCheck()
{
// Get Volume Label - valid drive
int serialNumber, maxFileNameLen, fileSystemFlags;
int volNameLen = 50;
int fileNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
StringBuilder fileSystemName = new StringBuilder(fileNameLen);
DriveInfo validDrive = DriveInfo.GetDrives().First(d => d.DriveType == DriveType.Fixed);
bool volumeInformationSuccess = GetVolumeInformation(validDrive.Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileNameLen);
if (volumeInformationSuccess)
{
Assert.Equal(volumeName.ToString(), validDrive.VolumeLabel);
}
else // if we can't compare the volumeName, we should at least check that getting it doesn't throw
{
var name = validDrive.VolumeLabel;
}
};
if (PlatformDetection.IsInAppContainer)
{
Assert.Throws<UnauthorizedAccessException>(() => DoDriveCheck());
}
else
{
DoDriveCheck();
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void SetVolumeLabel_Roundtrips()
{
DriveInfo drive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First();
// Inside an AppContainer access to VolumeLabel is denied.
if (PlatformDetection.IsInAppContainer)
{
Assert.Throws<UnauthorizedAccessException>(() => drive.VolumeLabel);
return;
}
string currentLabel = drive.VolumeLabel;
try
{
drive.VolumeLabel = currentLabel; // shouldn't change the state of the drive regardless of success
}
catch (UnauthorizedAccessException) { }
Assert.Equal(drive.VolumeLabel, currentLabel);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void VolumeLabelOnNetworkOrCdRom_Throws()
{
// Test setting the volume label on a Network or CD-ROM
var noAccessDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Network || d.DriveType == DriveType.CDRom);
foreach (var adrive in noAccessDrive)
{
if (adrive.IsReady)
{
Exception e = Assert.ThrowsAny<Exception>(() => { adrive.VolumeLabel = null; });
Assert.True(
e is UnauthorizedAccessException ||
e is IOException ||
e is SecurityException);
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int GetLogicalDrives();
[DllImport("kernel32.dll", EntryPoint = "GetVolumeInformationW", CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
internal static extern bool GetVolumeInformation(string drive, StringBuilder volumeName, int volumeNameBufLen, out int volSerialNumber, out int maxFileNameLen, out int fileSystemFlags, StringBuilder fileSystemName, int fileSystemNameBufLen);
[DllImport("kernel32.dll", SetLastError = true, EntryPoint = "GetDriveTypeW", CharSet = CharSet.Unicode)]
internal static extern int GetDriveType(string drive);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
private IEnumerable<char> GetValidDriveLettersOnMachine()
{
uint mask = (uint)GetLogicalDrives();
Assert.NotEqual<uint>(0, mask);
var bits = new BitArray(new int[] { (int)mask });
for (int i = 0; i < bits.Length; i++)
{
var letter = (char)('A' + i);
if (bits[i])
yield return letter;
}
}
private IEnumerable<char> GetInvalidDriveLettersOnMachine()
{
uint mask = (uint)GetLogicalDrives();
Assert.NotEqual<uint>(0, mask);
var bits = new BitArray(new int[] { (int)mask });
for (int i = 0; i < bits.Length; i++)
{
var letter = (char)('A' + i);
if (!bits[i])
{
if (char.IsLetter(letter))
yield return letter;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.