context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation.Host;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell
{
/// <summary>
///
/// ProgressPane is a class that represents the "window" in which outstanding activities for which the host has recevied
/// progress updates are shown.
///
///</summary>
internal
class ProgressPane
{
/// <summary>
///
/// Constructs a new instance.
///
/// </summary>
/// <param name="ui">
///
/// An implementation of the PSHostRawUserInterface with which the pane will be shown and hidden.
///
/// </param>
internal
ProgressPane(ConsoleHostUserInterface ui)
{
if (ui == null) throw new ArgumentNullException("ui");
_ui = ui;
_rawui = ui.RawUI;
}
/// <summary>
///
/// Indicates whether the pane is visible on the screen buffer or not.
///
/// </summary>
/// <value>
///
/// true if the pane is visible, false if not.
///
///</value>
internal
bool
IsShowing
{
get
{
return (_savedRegion != null);
}
}
/// <summary>
///
/// Shows the pane in the screen buffer. Saves off the content of the region of the buffer that will be overwritten so
/// that it can be restored again.
///
/// </summary>
internal
void
Show()
{
if (!IsShowing)
{
// Get temporary reference to the progress region since it can be
// changed at any time by a call to WriteProgress.
BufferCell[,] tempProgressRegion = _progressRegion;
if (tempProgressRegion == null)
{
return;
}
// The location where we show ourselves is always relative to the screen buffer's current window position.
int rows = tempProgressRegion.GetLength(0);
int cols = tempProgressRegion.GetLength(1);
_location = _rawui.WindowPosition;
// We have to show the progress pane in the first column, as the screen buffer at any point might contain
// a CJK double-cell characters, which makes it impractical to try to find a position where the pane would
// not slice a character. Column 0 is the only place where we know for sure we can place the pane.
_location.X = 0;
_location.Y = Math.Min(_location.Y + 2, _bufSize.Height);
#if UNIX
// replace the saved region in the screen buffer with our progress display
_location = _rawui.CursorPosition;
//set the cursor position back to the beginning of the region to overwrite write-progress
//if the cursor is at the bottom, back it up to overwrite the previous write progress
if (_location.Y >= _rawui.BufferSize.Height - rows)
{
Console.Out.Write('\n');
if (_location.Y >= rows)
{
_location.Y -= rows;
}
}
_rawui.CursorPosition = _location;
#else
// Save off the current contents of the screen buffer in the region that we will occupy
_savedRegion =
_rawui.GetBufferContents(
new Rectangle(_location.X, _location.Y, _location.X + cols - 1, _location.Y + rows - 1));
#endif
// replace the saved region in the screen buffer with our progress display
_rawui.SetBufferContents(_location, tempProgressRegion);
}
}
/// <summary>
///
/// Hides the pane by restoring the saved contents of the region of the buffer that the pane occupies. If the pane is
/// not showing, then does nothing.
///
/// </summary>
internal
void
Hide()
{
if (IsShowing)
{
// It would be nice if we knew that the saved region could be kept for the next time Show is called, but alas,
// we have no way of knowing if the screen buffer has changed since we were hidden. By "no good way" I mean that
// detecting a change would be at least as expensive as chucking the savedRegion and rebuilding it. And it would
// be very complicated.
_rawui.SetBufferContents(_location, _savedRegion);
_savedRegion = null;
}
}
/// <summary>
///
/// Updates the pane with the rendering of the supplied PendingProgress, and shows it.
///
/// </summary>
/// <param name="pendingProgress">
///
/// A PendingProgress instance that represents the outstanding activities that should be shown.
///
/// </param>
internal
void
Show(PendingProgress pendingProgress)
{
Dbg.Assert(pendingProgress != null, "pendingProgress may not be null");
_bufSize = _rawui.BufferSize;
// In order to keep from slicing any CJK double-cell characters that might be present in the screen buffer,
// we use the full width of the buffer.
int maxWidth = _bufSize.Width;
int maxHeight = Math.Max(5, _rawui.WindowSize.Height / 3);
string[] contents = pendingProgress.Render(maxWidth, maxHeight, _rawui);
if (contents == null)
{
// There's nothing to show.
Hide();
_progressRegion = null;
return;
}
// NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...
BufferCell[,] newRegion = _rawui.NewBufferCellArray(contents, _ui.ProgressForegroundColor, _ui.ProgressBackgroundColor);
Dbg.Assert(newRegion != null, "NewBufferCellArray has failed!");
if (_progressRegion == null)
{
// we've never shown this pane before.
_progressRegion = newRegion;
Show();
}
else
{
// We have shown the pane before. We have to be smart about when we restore the saved region to minimize
// flicker. We need to decide if the new contents will change the dimmensions of the progress pane
// currently being shown. If it will, then restore the saved region, and show the new one. Otherwise,
// just blast the new one on top of the last one shown.
// We're only checking size, not content, as we assume that the content will always change upon receipt
// of a new ProgressRecord. That's not guaranteed, of course, but it's a good bet. So checking content
// would usually result in detection of a change, so why bother?
bool sizeChanged =
(newRegion.GetLength(0) != _progressRegion.GetLength(0))
|| (newRegion.GetLength(1) != _progressRegion.GetLength(1))
? true : false;
_progressRegion = newRegion;
if (sizeChanged)
{
if (IsShowing)
{
Hide();
}
Show();
}
else
{
_rawui.SetBufferContents(_location, _progressRegion);
}
}
}
private Coordinates _location = new Coordinates(0, 0);
private Size _bufSize;
private BufferCell[,] _savedRegion;
private BufferCell[,] _progressRegion;
private PSHostRawUserInterface _rawui;
private ConsoleHostUserInterface _ui;
}
} // namespace
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Collections.Generic;
using System.Collections;
namespace System.Threading
{
/// <summary>
/// FrugalThreadPool
/// </summary>
/// http://www.albahari.com/threading/part4.aspx
public class FrugalThreadPool : IDisposable
{
private Thread[] _threadPool;
private object[] _threadContext;
private Queue<IEnumerable> _workQueue = new Queue<IEnumerable>();
private ThreadStatus _threadStatus = ThreadStatus.Idle;
private int _joiningThreadPoolCount;
private object _joiningObject = new object();
private Func<object> _threadContextBuilder;
private Action<object, object> _executor;
private bool _disposed;
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
Dispose(true);
}
}
/// <summary>
/// ThreadStatus
/// </summary>
private enum ThreadStatus
{
/// <summary>
/// Idle
/// </summary>
Idle,
/// <summary>
/// Join
/// </summary>
Join,
/// <summary>
/// Stop
/// </summary>
Stop,
}
/// <summary>
/// Initializes a new instance of the <see cref="FrugalThreadPool2"/> class.
/// </summary>
public FrugalThreadPool(Action<object, object> executor)
: this(4, executor, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="FrugalThreadPool2"/> class.
/// </summary>
/// <param name="threadCount">The thread count.</param>
public FrugalThreadPool(int threadCount, Action<object, object> executor)
: this(threadCount, executor, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="FrugalThreadPool2"/> class.
/// </summary>
/// <param name="threadCount">The thread count.</param>
/// <param name="threadContext">The thread context.</param>
public FrugalThreadPool(int threadCount, Action<object, object> executor, Func<object> threadContextBuilder)
{
if (executor == null)
throw new ArgumentNullException("executor");
_executor = executor;
_threadPool = new Thread[threadCount];
_threadContext = new object[threadCount];
_threadContextBuilder = threadContextBuilder;
for (int threadIndex = 0; threadIndex < _threadPool.Length; threadIndex++)
{
object threadContext;
_threadPool[threadIndex] = CreateAndStartThread("FrugalPool: " + threadIndex.ToString(), out threadContext);
_threadContext[threadIndex] = threadContext;
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected void Dispose(bool disposing)
{
if (disposing)
{
lock (this)
{
_threadStatus = ThreadStatus.Stop;
Monitor.PulseAll(this);
}
foreach (Thread thread in _threadPool)
thread.Join();
}
}
/// <summary>
/// Creates the and start thread.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
private Thread CreateAndStartThread(string name, out object threadContext)
{
var thread = new Thread(ThreadWorker) { Name = name };
threadContext = (_threadContextBuilder == null ? null : _threadContextBuilder());
thread.Start(threadContext);
return thread;
}
/// <summary>
/// Gets the thread context.
/// </summary>
/// <value>The thread context.</value>
public object[] ThreadContexts
{
get { return _threadContext; }
}
/// <summary>
/// Threads the worker.
/// </summary>
private void ThreadWorker(object threadContext)
{
IEnumerable list;
while (true)
{
lock (this)
{
while (_workQueue.Count == 0)
{
switch (_threadStatus)
{
case ThreadStatus.Stop:
return;
case ThreadStatus.Join:
lock (_joiningObject)
{
_joiningThreadPoolCount--;
Monitor.Pulse(_joiningObject);
}
break;
}
Monitor.Wait(this);
}
list = _workQueue.Dequeue();
}
if (list != null)
foreach (object obj in list)
_executor(obj, threadContext);
}
}
/// <summary>
/// Adds the specified list.
/// </summary>
/// <param name="list">The list.</param>
public void Add(IEnumerable list)
{
if (_threadStatus != ThreadStatus.Idle)
throw new InvalidOperationException();
lock (this)
{
_workQueue.Enqueue(list);
Monitor.Pulse(this);
}
}
/// <summary>
/// Joins this instance.
/// </summary>
public void Join()
{
lock (this)
{
_threadStatus = ThreadStatus.Join;
_joiningThreadPoolCount = _threadPool.Length;
Monitor.PulseAll(this);
}
lock (_joiningObject)
{
while (_joiningThreadPoolCount > 0)
Monitor.Wait(_joiningObject);
_threadStatus = ThreadStatus.Idle;
}
}
/// <summary>
/// Joins the and change.
/// </summary>
/// <param name="executor">The executor.</param>
public void JoinAndChange(Action<object, object> executor)
{
Join();
_executor = executor;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace TrueCraft.API
{
/// <summary>
/// Represents the location of an object in 3D space.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Vector3 : IEquatable<Vector3>
{
/// <summary>
/// The X component of this vector.
/// </summary>
[FieldOffset(0)]
public double X;
/// <summary>
/// The Y component of this vector.
/// </summary>
[FieldOffset(8)]
public double Y;
/// <summary>
/// The Z component of this vector.
/// </summary>
[FieldOffset(16)]
public double Z;
/// <summary>
/// Creates a new vector from the specified value.
/// </summary>
/// <param name="value">The value for the components of the vector.</param>
public Vector3(double value)
{
X = Y = Z = value;
}
/// <summary>
/// Creates a new vector from the specified values.
/// </summary>
/// <param name="x">The X component of the vector.</param>
/// <param name="y">The Y component of the vector.</param>
/// <param name="z">The Z component of the vector.</param>
public Vector3(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
/// <summary>
/// Creates a new vector from copying another.
/// </summary>
/// <param name="v">The vector to copy.</param>
public Vector3(Vector3 v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
}
/// <summary>
/// Converts this Vector3 to a string in the format <x,y,z>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("<{0},{1},{2}>", X, Y, Z);
}
#region Math
/// <summary>
/// Truncates the decimal component of each part of this Vector3.
/// </summary>
public Vector3 Floor()
{
return new Vector3(Math.Floor(X), Math.Floor(Y), Math.Floor(Z));
}
/// <summary>
/// Rounds the decimal component of each part of this Vector3.
/// </summary>
public Vector3 Round()
{
return new Vector3(Math.Round(X), Math.Round(Y), Math.Round(Z));
}
/// <summary>
/// Clamps the vector to within the specified value.
/// </summary>
/// <param name="value">Value.</param>
public void Clamp(double value)
{
if (Math.Abs(X) > value)
X = value * (X < 0 ? -1 : 1);
if (Math.Abs(Y) > value)
Y = value * (Y < 0 ? -1 : 1);
if (Math.Abs(Z) > value)
Z = value * (Z < 0 ? -1 : 1);
}
/// <summary>
/// Calculates the distance between two Vector3 objects.
/// </summary>
public double DistanceTo(Vector3 other)
{
return Math.Sqrt(Square(other.X - X) +
Square(other.Y - Y) +
Square(other.Z - Z));
}
public Vector3 Transform(Matrix matrix)
{
var x = (X * matrix.M11) + (Y * matrix.M21) + (Z * matrix.M31) + matrix.M41;
var y = (X * matrix.M12) + (Y * matrix.M22) + (Z * matrix.M32) + matrix.M42;
var z = (X * matrix.M13) + (Y * matrix.M23) + (Z * matrix.M33) + matrix.M43;
return new Vector3(x, y, z);
}
/// <summary>
/// Calculates the square of a num.
/// </summary>
private double Square(double num)
{
return num * num;
}
/// <summary>
/// Finds the distance of this vector from Vector3.Zero
/// </summary>
public double Distance
{
get
{
return DistanceTo(Zero);
}
}
/// <summary>
/// Returns the component-wise minumum of two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns></returns>
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z)
);
}
/// <summary>
/// Returns the component-wise maximum of two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns></returns>
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z)
);
}
/// <summary>
/// Calculates the dot product between two vectors.
/// </summary>
public static double Dot(Vector3 value1, Vector3 value2)
{
return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z;
}
/// <summary>
/// Computes the cross product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The cross product of two vectors.</returns>
public static Vector3 Cross(Vector3 vector1, Vector3 vector2)
{
Cross(ref vector1, ref vector2, out vector1);
return vector1;
}
/// <summary>
/// Computes the cross product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <param name="result">The cross product of two vectors as an output parameter.</param>
public static void Cross(ref Vector3 vector1, ref Vector3 vector2, out Vector3 result)
{
var x = vector1.Y * vector2.Z - vector2.Y * vector1.Z;
var y = -(vector1.X * vector2.Z - vector2.X * vector1.Z);
var z = vector1.X * vector2.Y - vector2.X * vector1.Y;
result.X = x;
result.Y = y;
result.Z = z;
}
#endregion
#region Operators
public static bool operator !=(Vector3 a, Vector3 b)
{
return !a.Equals(b);
}
public static bool operator ==(Vector3 a, Vector3 b)
{
return a.Equals(b);
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(
a.X + b.X,
a.Y + b.Y,
a.Z + b.Z);
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(
a.X - b.X,
a.Y - b.Y,
a.Z - b.Z);
}
public static Vector3 operator +(Vector3 a, Size b)
{
return new Vector3(
a.X + b.Width,
a.Y + b.Height,
a.Z + b.Depth);
}
public static Vector3 operator -(Vector3 a, Size b)
{
return new Vector3(
a.X - b.Width,
a.Y - b.Height,
a.Z - b.Depth);
}
public static Vector3 operator -(Vector3 a)
{
return new Vector3(
-a.X,
-a.Y,
-a.Z);
}
public static Vector3 operator *(Vector3 a, Vector3 b)
{
return new Vector3(
a.X * b.X,
a.Y * b.Y,
a.Z * b.Z);
}
public static Vector3 operator /(Vector3 a, Vector3 b)
{
return new Vector3(
a.X / b.X,
a.Y / b.Y,
a.Z / b.Z);
}
public static Vector3 operator %(Vector3 a, Vector3 b)
{
return new Vector3(a.X % b.X, a.Y % b.Y, a.Z % b.Z);
}
public static Vector3 operator +(Vector3 a, double b)
{
return new Vector3(
a.X + b,
a.Y + b,
a.Z + b);
}
public static Vector3 operator -(Vector3 a, double b)
{
return new Vector3(
a.X - b,
a.Y - b,
a.Z - b);
}
public static Vector3 operator *(Vector3 a, double b)
{
return new Vector3(
a.X * b,
a.Y * b,
a.Z * b);
}
public static Vector3 operator /(Vector3 a, double b)
{
return new Vector3(
a.X / b,
a.Y / b,
a.Z / b);
}
public static Vector3 operator %(Vector3 a, double b)
{
return new Vector3(a.X % b, a.Y % b, a.Y % b);
}
public static Vector3 operator +(double a, Vector3 b)
{
return new Vector3(
a + b.X,
a + b.Y,
a + b.Z);
}
public static Vector3 operator -(double a, Vector3 b)
{
return new Vector3(
a - b.X,
a - b.Y,
a - b.Z);
}
public static Vector3 operator *(double a, Vector3 b)
{
return new Vector3(
a * b.X,
a * b.Y,
a * b.Z);
}
public static Vector3 operator /(double a, Vector3 b)
{
return new Vector3(
a / b.X,
a / b.Y,
a / b.Z);
}
public static Vector3 operator %(double a, Vector3 b)
{
return new Vector3(a % b.X, a % b.Y, a % b.Y);
}
#endregion
#region Conversion operators
public static implicit operator Vector3(Coordinates3D a)
{
return new Vector3(a.X, a.Y, a.Z);
}
public static explicit operator Vector3(Coordinates2D c)
{
return new Vector3(c.X, 0, c.Z);
}
public static implicit operator Vector3(Size s)
{
return new Vector3(s.Width, s.Height, s.Depth);
}
#endregion
#region Constants
/// <summary>
/// A vector with its components set to 0.0.
/// </summary>
public static readonly Vector3 Zero = new Vector3(0);
/// <summary>
/// A vector with its components set to 1.0.
/// </summary>
public static readonly Vector3 One = new Vector3(1);
/// <summary>
/// A vector that points upward.
/// </summary>
public static readonly Vector3 Up = new Vector3(0, 1, 0);
/// <summary>
/// A vector that points downward.
/// </summary>
public static readonly Vector3 Down = new Vector3(0, -1, 0);
/// <summary>
/// A vector that points to the left.
/// </summary>
public static readonly Vector3 Left = new Vector3(-1, 0, 0);
/// <summary>
/// A vector that points to the right.
/// </summary>
public static readonly Vector3 Right = new Vector3(1, 0, 0);
/// <summary>
/// A vector that points backward.
/// </summary>
public static readonly Vector3 Backwards = new Vector3(0, 0, -1);
/// <summary>
/// A vector that points forward.
/// </summary>
public static readonly Vector3 Forwards = new Vector3(0, 0, 1);
/// <summary>
/// A vector that points to the east.
/// </summary>
public static readonly Vector3 East = new Vector3(1, 0, 0);
/// <summary>
/// A vector that points to the west.
/// </summary>
public static readonly Vector3 West = new Vector3(-1, 0, 0);
/// <summary>
/// A vector that points to the north.
/// </summary>
public static readonly Vector3 North = new Vector3(0, 0, -1);
/// <summary>
/// A vector that points to the south.
/// </summary>
public static readonly Vector3 South = new Vector3(0, 0, 1);
#endregion
/// <summary>
/// Determines whether this and another vector are equal.
/// </summary>
/// <param name="other">The other vector.</param>
/// <returns></returns>
public bool Equals(Vector3 other)
{
return other.X.Equals(X) && other.Y.Equals(Y) && other.Z.Equals(Z);
}
/// <summary>
/// Determines whether this and another object are equal.
/// </summary>
/// <param name="obj">The other object.</param>
/// <returns></returns>
public override bool Equals(object obj)
{
return obj is Vector3 && Equals((Vector3)obj);
}
/// <summary>
/// Gets the hash code for this vector.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
unchecked
{
int result = X.GetHashCode();
result = (result * 397) ^ Y.GetHashCode();
result = (result * 397) ^ Z.GetHashCode();
return result;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Maw.Domain;
using Maw.Domain.Videos;
namespace Maw.Data
{
public class VideoRepository
: Repository, IVideoRepository
{
public VideoRepository(string connectionString)
: base(connectionString)
{
}
public Task<IEnumerable<short>> GetYearsAsync(string[] roles)
{
return RunAsync(conn =>
conn.QueryAsync<short>(
"SELECT * FROM video.get_years(@roles);",
new { roles }
)
);
}
public Task<IEnumerable<Category>> GetAllCategoriesAsync(string[] roles)
{
return InternalGetCategoriesAsync(roles);
}
public Task<IEnumerable<Category>> GetCategoriesAsync(short year, string[] roles)
{
return InternalGetCategoriesAsync(roles, year);
}
public async Task<Category> GetCategoryAsync(short categoryId, string[] roles)
{
var result = await InternalGetCategoriesAsync(roles, categoryId: categoryId).ConfigureAwait(false);
return result.FirstOrDefault();
}
public Task<IEnumerable<Video>> GetVideosInCategoryAsync(short categoryId, string[] roles)
{
return InternalGetVideosAsync(roles, categoryId);
}
public async Task<Video> GetVideoAsync(short id, string[] roles)
{
var result = await InternalGetVideosAsync(roles, videoId: id).ConfigureAwait(false);
return result.FirstOrDefault();
}
public Task<IEnumerable<Comment>> GetCommentsAsync(short videoId, string[] roles)
{
return RunAsync(conn =>
conn.QueryAsync<Comment>(
"SELECT * FROM video.get_comments(@videoId, @roles);",
new
{
videoId,
roles
}
)
);
}
public Task<GpsDetail> GetGpsDetailAsync(int videoId, string[] roles)
{
return RunAsync(async conn =>
{
var result = await conn.QuerySingleOrDefaultAsync<GpsSourceOverride>(
"SELECT * FROM video.get_gps(@videoId, @roles);",
new
{
videoId,
roles
}
).ConfigureAwait(false);
if (result == null)
{
return null;
}
var detail = new GpsDetail();
if (result.SourceLatitude != null && result.SourceLongitude != null)
{
detail.Source = new GpsCoordinate()
{
Latitude = (float)result.SourceLatitude,
Longitude = (float)result.SourceLongitude
};
}
if (result.OverrideLatitude != null && result.OverrideLongitude != null)
{
detail.Override = new GpsCoordinate()
{
Latitude = (float)result.OverrideLatitude,
Longitude = (float)result.OverrideLongitude
};
}
return detail;
});
}
public Task<Rating> GetRatingsAsync(short videoId, string username, string[] roles)
{
return RunAsync(conn =>
conn.QuerySingleOrDefaultAsync<Rating>(
"SELECT * FROM video.get_ratings(@videoId, @username, @roles);",
new
{
videoId,
username = username?.ToLowerInvariant(),
roles
}
)
);
}
public Task<int> InsertCommentAsync(short videoId, string username, string comment, string[] roles)
{
return RunAsync(async conn =>
{
var result = await conn.QuerySingleOrDefaultAsync<int>(
"SELECT * FROM video.save_comment(@username, @videoId, @message, @entryDate, @roles);",
new
{
username = username.ToLowerInvariant(),
videoId,
message = comment,
entryDate = DateTime.Now,
roles
}
).ConfigureAwait(false);
if (result <= 0)
{
throw new Exception("Did not save video comment!");
}
return result;
});
}
public Task<float?> SaveRatingAsync(short videoId, string username, short rating, string[] roles)
{
return RunAsync(async conn =>
{
var result = await conn.QueryAsync<long>(
"SELECT * FROM video.save_rating(@videoId, @username, @score, @roles);",
new
{
videoId,
username = username.ToLowerInvariant(),
score = rating,
roles
}
).ConfigureAwait(false);
return (await GetRatingsAsync(videoId, username, roles).ConfigureAwait(false))?.AverageRating;
});
}
public Task<float?> RemoveRatingAsync(short videoId, string username, string[] roles)
{
return RunAsync(async conn =>
{
var result = await conn.QueryAsync<long>(
@"SELECT * FROM video.save_rating(@videoId, @username, @score, @roles);",
new
{
videoId,
username = username.ToLowerInvariant(),
score = 0,
roles
}
).ConfigureAwait(false);
return (await GetRatingsAsync(videoId, username, roles).ConfigureAwait(false))?.AverageRating;
});
}
public Task SetGpsOverrideAsync(int videoId, GpsCoordinate gps, string username)
{
return RunAsync(conn =>
conn.QueryAsync<long>(
"SELECT * FROM video.set_gps_override(@videoId, @latitude, @longitude, @username, @updateDate);",
new
{
videoId,
latitude = gps.Latitude,
longitude = gps.Longitude,
username = username.ToLowerInvariant(),
updateDate = DateTime.Now
}
)
);
}
public Task<long> SetCategoryTeaserAsync(short categoryId, int videoId)
{
return RunAsync(conn =>
conn.QueryFirstAsync<long>(
@"SELECT * FROM video.set_category_teaser(@categoryId, @videoId);",
new
{
categoryId,
videoId
}
)
);
}
Task<IEnumerable<Category>> InternalGetCategoriesAsync(string[] roles, short? year = null, short? categoryId = null)
{
return RunAsync(async conn =>
{
var rows = await conn.QueryAsync(
"SELECT * FROM video.get_categories(@roles, @year, @categoryId);",
new
{
roles,
year,
categoryId
}
).ConfigureAwait(false);
return rows.Select(BuildCategory);
});
}
Task<IEnumerable<Video>> InternalGetVideosAsync(string[] roles, short? categoryId = null, short? videoId = null)
{
return RunAsync(async conn =>
{
var rows = await conn.QueryAsync(
"SELECT * FROM video.get_videos(@roles, @categoryId, @videoId);",
new
{
roles,
categoryId,
videoId
}
).ConfigureAwait(false);
return rows.Select(BuildVideo);
});
}
Category BuildCategory(dynamic row)
{
var category = new Category();
category.Id = (short)row.id;
category.Name = (string)row.name;
category.Year = (short)row.year;
category.CreateDate = GetValueOrDefault<DateTime>(row.create_date);
category.Latitude = row.latitude;
category.Longitude = row.longitude;
category.VideoCount = GetValueOrDefault<int>(row.video_count);
category.TotalDuration = GetValueOrDefault<int>(row.total_duration);
category.TotalSizeThumbnail = GetValueOrDefault<long>(row.total_size_thumb);
category.TotalSizeThumbnailSq = GetValueOrDefault<long>(row.total_size_thumb_sq);
category.TotalSizeScaled = GetValueOrDefault<long>(row.total_size_scaled);
category.TotalSizeFull = GetValueOrDefault<long>(row.total_size_full);
category.TotalSizeRaw = GetValueOrDefault<long>(row.total_size_raw);
category.TotalSize = GetValueOrDefault<long>(row.total_size);
category.IsMissingGpsData = GetValueOrDefault<bool>(row.is_missing_gps_data);
category.TeaserImage = BuildMultimediaInfo(row.teaser_image_path, row.teaser_image_width, row.teaser_image_height, row.teaser_image_size);
category.TeaserImageSq = BuildMultimediaInfo(row.teaser_image_sq_path, row.teaser_image_sq_width, row.teaser_image_sq_height, row.teaser_image_sq_size);
return category;
}
Video BuildVideo(dynamic row)
{
var video = new Video();
video.Id = (int)row.id;
video.CategoryId = (short)row.category_id;
video.CreateDate = GetValueOrDefault<DateTime>(row.create_date);
video.Latitude = row.latitude;
video.Longitude = row.longitude;
video.Duration = GetValueOrDefault<short>(row.duration);
video.Thumbnail = BuildMultimediaInfo(row.thumb_path, row.thumb_width, row.thumb_height, row.thumb_size);
video.ThumbnailSq = BuildMultimediaInfo(row.thumb_sq_path, row.thumb_sq_width, row.thumb_sq_height, row.thumb_sq_size);
video.VideoScaled = BuildMultimediaInfo(row.scaled_path, row.scaled_width, row.scaled_height, row.scaled_size);
video.VideoFull = BuildMultimediaInfo(row.full_path, row.full_width, row.full_height, row.full_size);
video.VideoRaw = BuildMultimediaInfo(row.raw_path, row.raw_width, row.raw_height, row.raw_size);
return video;
}
}
}
| |
using System;
namespace NBitcoin.Altcoins.HashX11.Crypto.SHA3
{
internal class CubeHash224 : CubeHash
{
public CubeHash224()
: base(NBitcoin.Altcoins.HashX11.HashSize.HashSize224)
{
}
}
internal class CubeHash256 : CubeHash
{
public CubeHash256()
: base(NBitcoin.Altcoins.HashX11.HashSize.HashSize256)
{
}
}
internal class CubeHash384 : CubeHash
{
public CubeHash384()
: base(NBitcoin.Altcoins.HashX11.HashSize.HashSize384)
{
}
}
internal class CubeHash512 : CubeHash
{
public CubeHash512()
: base(NBitcoin.Altcoins.HashX11.HashSize.HashSize512)
{
}
}
internal abstract class CubeHash : BlockHash, ICryptoNotBuildIn
{
private const int ROUNDS = 16;
private readonly uint[] m_state = new uint[32];
private static uint[][] m_inits;
static CubeHash()
{
int[] hashes = new int[] { 28, 32, 48, 64 };
uint[][] inits = new uint[65][];
byte[] zeroes = new byte[32];
foreach (int hashsize in hashes)
{
CubeHash ch = (CubeHash)HashFactory.Crypto.SHA3.CreateCubeHash(NBitcoin.Altcoins.HashX11.HashSize.HashSize256);
ch.m_state[0] = (uint)hashsize;
ch.m_state[1] = 32;
ch.m_state[2] = 16;
for (int i = 0; i < 10; i++)
ch.TransformBlock(zeroes, 0);
inits[hashsize] = new uint[32];
Array.Copy(ch.m_state, inits[hashsize], 32);
}
m_inits = inits;
}
public CubeHash(NBitcoin.Altcoins.HashX11.HashSize a_hash_size)
: base((int)a_hash_size, 32)
{
Initialize();
}
protected override byte[] GetResult()
{
return Converters.ConvertUIntsToBytes(m_state, 0, HashSize / 4);
}
protected override void Finish()
{
byte[] pad = new byte[BlockSize + 1];
pad[0] = 0x80;
TransformBytes(pad, 0, BlockSize - m_buffer.Pos);
m_state[31] ^= 1;
for (int i = 0; i < 10; i++)
TransformBlock(pad, 1);
}
public override void Initialize()
{
if (m_inits != null)
Array.Copy(m_inits[HashSize], m_state, 32);
base.Initialize();
}
protected override void TransformBlock(byte[] a_data, int a_index)
{
uint[] temp = new uint[16];
uint[] state = new uint[32];
Array.Copy(m_state, state, 32);
uint[] data = Converters.ConvertBytesToUInts(a_data, a_index, BlockSize);
for (int i = 0; i < data.Length; i++)
state[i] ^= data[i];
for (int r = 0; r < ROUNDS; ++r)
{
state[16] += state[0];
state[17] += state[1];
state[18] += state[2];
state[19] += state[3];
state[20] += state[4];
state[21] += state[5];
state[22] += state[6];
state[23] += state[7];
state[24] += state[8];
state[25] += state[9];
state[26] += state[10];
state[27] += state[11];
state[28] += state[12];
state[29] += state[13];
state[30] += state[14];
state[31] += state[15];
temp[0 ^ 8] = state[0];
temp[1 ^ 8] = state[1];
temp[2 ^ 8] = state[2];
temp[3 ^ 8] = state[3];
temp[4 ^ 8] = state[4];
temp[5 ^ 8] = state[5];
temp[6 ^ 8] = state[6];
temp[7 ^ 8] = state[7];
temp[8 ^ 8] = state[8];
temp[9 ^ 8] = state[9];
temp[10 ^ 8] = state[10];
temp[11 ^ 8] = state[11];
temp[12 ^ 8] = state[12];
temp[13 ^ 8] = state[13];
temp[14 ^ 8] = state[14];
temp[15 ^ 8] = state[15];
for (int i = 0; i < 16; i++)
state[i] = (temp[i] << 7) | (temp[i] >> 25);
state[0] ^= state[16];
state[1] ^= state[17];
state[2] ^= state[18];
state[3] ^= state[19];
state[4] ^= state[20];
state[5] ^= state[21];
state[6] ^= state[22];
state[7] ^= state[23];
state[8] ^= state[24];
state[9] ^= state[25];
state[10] ^= state[26];
state[11] ^= state[27];
state[12] ^= state[28];
state[13] ^= state[29];
state[14] ^= state[30];
state[15] ^= state[31];
temp[0 ^ 2] = state[16];
temp[1 ^ 2] = state[17];
temp[2 ^ 2] = state[18];
temp[3 ^ 2] = state[19];
temp[4 ^ 2] = state[20];
temp[5 ^ 2] = state[21];
temp[6 ^ 2] = state[22];
temp[7 ^ 2] = state[23];
temp[8 ^ 2] = state[24];
temp[9 ^ 2] = state[25];
temp[10 ^ 2] = state[26];
temp[11 ^ 2] = state[27];
temp[12 ^ 2] = state[28];
temp[13 ^ 2] = state[29];
temp[14 ^ 2] = state[30];
temp[15 ^ 2] = state[31];
state[16] = temp[0];
state[17] = temp[1];
state[18] = temp[2];
state[19] = temp[3];
state[20] = temp[4];
state[21] = temp[5];
state[22] = temp[6];
state[23] = temp[7];
state[24] = temp[8];
state[25] = temp[9];
state[26] = temp[10];
state[27] = temp[11];
state[28] = temp[12];
state[29] = temp[13];
state[30] = temp[14];
state[31] = temp[15];
state[16] += state[0];
state[17] += state[1];
state[18] += state[2];
state[19] += state[3];
state[20] += state[4];
state[21] += state[5];
state[22] += state[6];
state[23] += state[7];
state[24] += state[8];
state[25] += state[9];
state[26] += state[10];
state[27] += state[11];
state[28] += state[12];
state[29] += state[13];
state[30] += state[14];
state[31] += state[15];
temp[0 ^ 4] = state[0];
temp[1 ^ 4] = state[1];
temp[2 ^ 4] = state[2];
temp[3 ^ 4] = state[3];
temp[4 ^ 4] = state[4];
temp[5 ^ 4] = state[5];
temp[6 ^ 4] = state[6];
temp[7 ^ 4] = state[7];
temp[8 ^ 4] = state[8];
temp[9 ^ 4] = state[9];
temp[10 ^ 4] = state[10];
temp[11 ^ 4] = state[11];
temp[12 ^ 4] = state[12];
temp[13 ^ 4] = state[13];
temp[14 ^ 4] = state[14];
temp[15 ^ 4] = state[15];
for (int i = 0; i < 16; i++)
state[i] = (temp[i] << 11) | (temp[i] >> 21);
state[0] ^= state[16];
state[1] ^= state[17];
state[2] ^= state[18];
state[3] ^= state[19];
state[4] ^= state[20];
state[5] ^= state[21];
state[6] ^= state[22];
state[7] ^= state[23];
state[8] ^= state[24];
state[9] ^= state[25];
state[10] ^= state[26];
state[11] ^= state[27];
state[12] ^= state[28];
state[13] ^= state[29];
state[14] ^= state[30];
state[15] ^= state[31];
temp[0 ^ 1] = state[16];
temp[1 ^ 1] = state[17];
temp[2 ^ 1] = state[18];
temp[3 ^ 1] = state[19];
temp[4 ^ 1] = state[20];
temp[5 ^ 1] = state[21];
temp[6 ^ 1] = state[22];
temp[7 ^ 1] = state[23];
temp[8 ^ 1] = state[24];
temp[9 ^ 1] = state[25];
temp[10 ^ 1] = state[26];
temp[11 ^ 1] = state[27];
temp[12 ^ 1] = state[28];
temp[13 ^ 1] = state[29];
temp[14 ^ 1] = state[30];
temp[15 ^ 1] = state[31];
state[16] = temp[0];
state[17] = temp[1];
state[18] = temp[2];
state[19] = temp[3];
state[20] = temp[4];
state[21] = temp[5];
state[22] = temp[6];
state[23] = temp[7];
state[24] = temp[8];
state[25] = temp[9];
state[26] = temp[10];
state[27] = temp[11];
state[28] = temp[12];
state[29] = temp[13];
state[30] = temp[14];
state[31] = temp[15];
}
Array.Copy(state, m_state, 32);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// BasicOperations operations.
/// </summary>
internal partial class BasicOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IBasicOperations
{
/// <summary>
/// Initializes a new instance of the BasicOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BasicOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex type {id: 2, name: 'abc', color: 'YELLOW'}
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </summary>
/// <param name='complexBody'>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
string apiVersion = "2016-02-29";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is invalid for the local strong type
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type whose properties are null
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type while the server doesn't provide a response
/// payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections;
namespace Knives.Chat3
{
public class DefaultLocal
{
public static ArrayList Load()
{
ArrayList list = new ArrayList();
list.Add("Friend");
list.Add("Views");
list.Add("Ignore");
list.Add("Remove Ignore");
list.Add("Grant Global");
list.Add("Revoke Global");
list.Add("Ban");
list.Add("Remove Ban");
list.Add("Global Ignore");
list.Add("Global Unignore");
list.Add("Listen");
list.Add("Remove Listen");
list.Add("Set your away message");
list.Add("Send Message");
list.Add("Become User");
list.Add("Client");
list.Add("Goto");
list.Add("Message Sound");
list.Add("Friend and Messaging Options");
list.Add("Online");
list.Add("Away");
list.Add("Busy");
list.Add("Hidden");
list.Add("You must unhide to see the player list");
list.Add("Only friends can send messages");
list.Add("Require friend requests");
list.Add("Global Messages");
list.Add("Sound on message receive");
list.Add("Default Message Sound");
list.Add("Friends speech shortcut");
list.Add("Friend online alert");
list.Add("Please select a channel to view");
list.Add("Friends");
list.Add("You are banned from chat");
list.Add("You must join the channel first");
list.Add("You are not in a chatting region");
list.Add("You are not in a guild");
list.Add("You are not in a faction");
list.Add("Channels");
list.Add("General Channel Options");
list.Add("Options");
list.Add("Channels speech shortcut");
list.Add("Commands");
list.Add("Global");
list.Add("Global Chat");
list.Add("Global World");
list.Add("View All");
list.Add("System Color");
list.Add("Staff Color");
list.Add("Color");
list.Add("Channel");
list.Add("Ignores");
list.Add("GIgnores");
list.Add("GListens");
list.Add("Bans");
list.Add("Display");
list.Add("Mail");
list.Add("Mail and Messaging Options");
list.Add("Auto delete week old messages");
list.Add("Mail speech shortcut");
list.Add("from");
list.Add("You must target a book");
list.Add("Message to");
list.Add("Recording. Press send when finished.");
list.Add("Recording stopped");
list.Add("Now recording. Everything you enter on the command line will appear in the message.");
list.Add("You must have a message to send");
list.Add("Message sent to");
list.Add("You are now ignoring");
list.Add("You delete the message");
list.Add("Speech command set to");
list.Add("Speech command cleared");
list.Add("is no longer on your friend list");
list.Add("is now on your friend list");
list.Add("You are no longer ignoring");
list.Add("now has global listening access");
list.Add("no longer has global access");
list.Add("You ban");
list.Add("You lift the ban from");
list.Add("You are no longer global ignoring");
list.Add("You are now global ignoring");
list.Add("You are no longer globally listening to");
list.Add("You are now globally listening to");
list.Add("is no longer online");
list.Add("Friend Request");
list.Add("Do you want to add this player as a friend?");
list.Add("You have sent a friend request to");
list.Add("has accepted your friend request");
list.Add("has denied your friend request");
list.Add("You deny");
list.Add("You are now banned from chat");
list.Add("Your chat ban has been lifted");
list.Add("You've been granted global access");
list.Add("Your global access has been revoked");
list.Add("Broadcast to all");
list.Add("Broadcast");
list.Add("You can send another request in");
list.Add("You must wait a few moments between messages");
list.Add("Enable IRC");
list.Add("Filter and Spam Options");
list.Add("IRC Options");
list.Add("Misc Options");
list.Add("The server is already attempting to connect");
list.Add("The server is already connected");
list.Add("IRC connection failed");
list.Add("Attempting to connect...");
list.Add("Connection could not be established");
list.Add("Connecting to IRC server...");
list.Add("Server is now connected to IRC channel");
list.Add("IRC names list updating");
list.Add("IRC connection down");
list.Add("Filter violation detected:");
list.Add("Too many search results, be more specific");
list.Add("No matching names found");
list.Add("Select a name");
list.Add("Auto Connect");
list.Add("Auto Reconnect");
list.Add("Nickname");
list.Add("Server");
list.Add("Room");
list.Add("Port");
list.Add("White");
list.Add("Black");
list.Add("Blue");
list.Add("Green");
list.Add("Light Red");
list.Add("Brown");
list.Add("Purple");
list.Add("Orange");
list.Add("Yellow");
list.Add("Light Green");
list.Add("Cyan");
list.Add("Light Cyan");
list.Add("Light Blue");
list.Add("Pink");
list.Add("Grey");
list.Add("Light Grey");
list.Add("Select a Color");
list.Add("Staff Color");
list.Add("Connect");
list.Add("Cancel Connect");
list.Add("Close Connection");
list.Add("Apply filter to world speech");
list.Add("Apply filter to private messages");
list.Add("Chat Spam");
list.Add("Pm Spam");
list.Add("Request Spam");
list.Add("Filter Ban");
list.Add("Add/Remove Filter");
list.Add("You remove the filter:");
list.Add("You add the filter:");
list.Add("Filters:");
list.Add("Show staff in channel lists");
list.Add("Max Mailbox Size");
list.Add("Filter Penalty");
list.Add("None");
list.Add("Ban");
list.Add("Jail");
list.Add("IRC connection is down");
list.Add("IRC Raw");
list.Add("Select Ban Time");
list.Add("30 minutes");
list.Add("1 hour");
list.Add("12 hours");
list.Add("1 day");
list.Add("1 week");
list.Add("1 month");
list.Add("1 year");
list.Add("Local file reloaded");
list.Add("Reload localized text file");
list.Add("days");
list.Add("hours");
list.Add("minutes");
list.Add("is now online");
list.Add("Error loading global options. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error saving global options. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error filtering text. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Channel Options");
list.Add("New Channel");
list.Add("Please select a channel");
list.Add("Name");
list.Add("Style");
list.Add("Global");
list.Add("Regional");
list.Add("Send Chat to IRC");
list.Add("Add/Remove Command");
list.Add("Error loading channel information. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error saving channel information. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Auto join new players");
list.Add("You have left the channel");
list.Add("You have joined the channel");
list.Add("You must be staff to chat here");
list.Add("Global Guild");
list.Add("Global Faction");
list.Add("The message needs a subject before you can begin recording");
list.Add("Quick Bar");
list.Add("Message Read Receipts");
list.Add("has read");
list.Add("Error loading gump information. Details on the RunUO Console. Please report to Knives at kmwill23@hotmail.com");
list.Add("Error saving gump information. Details on the RunUO Console. Please report to Knives at kmwill23@hotmail.com");
list.Add("Errors reported by either this chat system or other staff members! Administrators have the power to clear this list. All staff members can report an error using the [chaterrors <text> command.");
list.Add("Chat Error Log");
list.Add("Clear");
list.Add("Friends");
list.Add("Global Ignores");
list.Add("Global Listens");
list.Add("History");
list.Add("General");
list.Add("Filter");
list.Add("Spam");
list.Add("Irc");
list.Add("Delete Channel");
list.Add("Enable Channel");
list.Add("This channel is disabled");
list.Add("Filter Options");
list.Add("Spam Options");
list.Add("Colors");
list.Add("Mail Options");
list.Add("Your mailbox is full, please delete some messages so others may send to you.");
list.Add("Press the button above to select a channel. When adding commands, do not include the command prefix.");
list.Add("Delay");
list.Add("General Options");
list.Add("Debug");
list.Add("Show Staff");
list.Add("Viewing");
list.Add("You cannot send messages while under another user's identity.");
list.Add("Global Options");
list.Add("Error loading player options. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error saving player options. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error loading friends. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error saving friends. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error loading ignores. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error saving ignores. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error loading global listens. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error saving global listens. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error loading private messages. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Error saving private messages. Details on the RunUO Console. Please report this to Knives at kmwill23@hotmail.com");
list.Add("Logging");
list.Add("Log Chat");
list.Add("Log Pms");
list.Add("Chat save completed in");
list.Add("Chat information saving...");
list.Add("The background you set will now be forced on all players.");
list.Add("Players can now set their own backgrounds.");
list.Add("Clear");
list.Add("Submit");
list.Add("Signature updated");
list.Add("Your signature:");
list.Add("Reply");
list.Add("Delete");
list.Add("Accept");
list.Add("Deny");
list.Add("Send");
list.Add("Chat Karma:");
list.Add("Filter Warnings");
list.Add("You can't chat while squelched.");
list.Add("Broadcast to Staff");
list.Add("Staff");
list.Add("You have {0} of max {1} in your mailbox.");
list.Add("Auto-delete old when mailbox full");
list.Add("You are squelched and cannot chat.");
list.Add("Staff Announcement");
list.Add("To use help, simply enter a word in the search line and all topics matching will pop up here!");
list.Add("Your search returned no results.");
list.Add(" results");
list.Add(" result");
list.Add("Error reported in connecting IRC. More information is available on the console.");
list.Add("Error reported in handling IRC input. More information is available on the console.");
list.Add("Error reported in disconnecting IRC. More information is available on the console.");
list.Add("Notifications");
list.Add("New Notification");
list.Add("Automated System Message");
list.Add("Text");
list.Add("Gump");
list.Add("Set Recur Time");
list.Add("Anti-Macro check");
list.Add("You have been flagged for violating afk macroing rules.");
list.Add("Afk Macroing");
list.Add(" has been flagged for violating afk macroing rules.");
list.Add("You have been kicked for violating afk macroing rules.");
list.Add("Macro Penalty");
list.Add("Kick");
list.Add("Delay before penalty");
list.Add("Multi Server Chat");
list.Add("Run Multi Server");
list.Add("Multi Server");
list.Add("Start Server");
list.Add("Multi");
list.Add("Error connecting to master server.");
list.Add("Connected to master server.");
list.Add("Disconnecting from master server.");
list.Add(" has disconnected.");
list.Add(" has connected.");
list.Add("Reload Help Contents");
list.Add("Help contents reloaded");
return list;
}
}
}
| |
#region License
// Copyright (c) 2014 The Sentry Team and individual contributors.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// 3. Neither the name of the Sentry 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.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using SharpRaven.Data;
using SharpRaven.Logging;
using SharpRaven.Utilities;
namespace SharpRaven
{
/// <summary>
/// The Raven Client, responsible for capturing exceptions and sending them to Sentry.
/// </summary>
public partial class RavenClient : IRavenClient
{
private readonly CircularBuffer<Breadcrumb> breadcrumbs;
private readonly Dsn currentDsn;
private readonly IDictionary<string, string> defaultTags;
private readonly IJsonPacketFactory jsonPacketFactory;
private readonly ISentryRequestFactory sentryRequestFactory;
private readonly ISentryUserFactory sentryUserFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RavenClient" /> class. Sentry
/// Data Source Name will be read from sharpRaven section in your app.config or
/// web.config.
/// </summary>
/// <param name="jsonPacketFactory">The optional factory that will be used to create the <see cref="JsonPacket" /> that will be sent to Sentry.</param>
public RavenClient(IJsonPacketFactory jsonPacketFactory = null)
: this(new Dsn(Configuration.Settings.Dsn.Value), jsonPacketFactory)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RavenClient" /> class.
/// </summary>
/// <param name="dsn">The Data Source Name in Sentry.</param>
/// <param name="jsonPacketFactory">The optional factory that will be used to create the <see cref="JsonPacket" /> that will be sent to Sentry.</param>
/// <param name="sentryRequestFactory">The optional factory that will be used to create the <see cref="SentryRequest"/> that will be sent to Sentry.</param>
/// <param name="sentryUserFactory">The optional factory that will be used to create the <see cref="SentryUser"/> that will be sent to Sentry.</param>
public RavenClient(string dsn,
IJsonPacketFactory jsonPacketFactory = null,
ISentryRequestFactory sentryRequestFactory = null,
ISentryUserFactory sentryUserFactory = null)
: this(new Dsn(dsn), jsonPacketFactory, sentryRequestFactory, sentryUserFactory)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RavenClient" /> class.
/// </summary>
/// <param name="dsn">The Data Source Name in Sentry.</param>
/// <param name="jsonPacketFactory">The optional factory that will be used to create the <see cref="JsonPacket" /> that will be sent to Sentry.</param>
/// <param name="sentryRequestFactory">The optional factory that will be used to create the <see cref="SentryRequest"/> that will be sent to Sentry.</param>
/// <param name="sentryUserFactory">The optional factory that will be used to create the <see cref="SentryUser"/> that will be sent to Sentry.</param>
/// <exception cref="System.ArgumentNullException">dsn</exception>
public RavenClient(Dsn dsn,
IJsonPacketFactory jsonPacketFactory = null,
ISentryRequestFactory sentryRequestFactory = null,
ISentryUserFactory sentryUserFactory = null)
{
if (dsn == null)
throw new ArgumentNullException("dsn");
this.currentDsn = dsn;
this.jsonPacketFactory = jsonPacketFactory ?? new JsonPacketFactory();
this.sentryRequestFactory = sentryRequestFactory ?? new SentryRequestFactory();
this.sentryUserFactory = sentryUserFactory ?? new SentryUserFactory();
Logger = "root";
Timeout = TimeSpan.FromSeconds(5);
this.defaultTags = new Dictionary<string, string>();
this.breadcrumbs = new CircularBuffer<Breadcrumb>();
}
/// <summary>
/// Gets or sets the <see cref="Action"/> to execute to manipulate or extract data from
/// the <see cref="Requester"/> object before it is used in the <see cref="Send"/> method.
/// </summary>
/// <value>
/// The <see cref="Action"/> to execute to manipulate or extract data from the
/// <see cref="Requester"/> object before it is used in the <see cref="Send"/> method.
/// </value>
public Func<Requester, Requester> BeforeSend { get; set; }
/// <summary>
/// Gets or sets the <see cref="Action"/> to execute if an error occurs when executing
/// <see cref="Capture"/>.
/// </summary>
/// <value>
/// The <see cref="Action"/> to execute if an error occurs when executing <see cref="Capture"/>.
/// </value>
public Action<Exception> ErrorOnCapture { get; set; }
/// <summary>
/// Enable Gzip Compression?
/// Defaults to <c>false</c>.
/// </summary>
public bool Compression { get; set; }
/// <summary>
/// The Dsn currently being used to log exceptions.
/// </summary>
public Dsn CurrentDsn
{
get { return this.currentDsn; }
}
/// <summary>
/// Interface for providing a 'log scrubber' that removes
/// sensitive information from exceptions sent to sentry.
/// </summary>
public IScrubber LogScrubber { get; set; }
/// <summary>
/// The name of the logger. The default logger name is "root".
/// </summary>
public string Logger { get; set; }
/// <summary>
/// The version of the application.
/// </summary>
public string Release { get; set; }
/// <summary>
/// The environment (e.g. production)
/// </summary>
public string Environment { get; set; }
/// <summary>
/// Default tags sent on all events.
/// </summary>
public IDictionary<string, string> Tags
{
get { return this.defaultTags; }
}
/// <summary>
/// Gets or sets the timeout value in milliseconds for the HTTP communication with Sentry.
/// </summary>
/// <value>
/// The number of milliseconds to wait before the request times out. The default is 5,000 milliseconds (5 seconds).
/// </value>
public TimeSpan Timeout { get; set; }
/// <summary>
/// Not register the <see cref="Breadcrumb"/> for tracking.
/// </summary>
public bool IgnoreBreadcrumbs { get; set; }
/// <summary>
/// Captures the last 100 <see cref="Breadcrumb" />.
/// </summary>
/// <param name="breadcrumb">The <see cref="Breadcrumb" /> to capture.</param>
public void AddTrail(Breadcrumb breadcrumb)
{
if (IgnoreBreadcrumbs || breadcrumb == null)
return;
this.breadcrumbs.Add(breadcrumb);
}
/// <summary>
/// Restart the capture of the <see cref="Breadcrumb"/> for tracking.
/// </summary>
public void RestartTrails()
{
this.breadcrumbs.Clear();
}
/// <summary>Captures the specified <paramref name="event"/>.</summary>
/// <param name="event">The event to capture.</param>
/// <returns>
/// The <see cref="JsonPacket.EventID" /> of the successfully captured <paramref name="event" />, or <c>null</c> if it fails.
/// </returns>
public string Capture(SentryEvent @event)
{
if (@event == null)
throw new ArgumentNullException("event");
@event.Tags = MergeTags(@event.Tags);
if (!this.breadcrumbs.IsEmpty())
@event.Breadcrumbs = this.breadcrumbs.ToList();
var packet = this.jsonPacketFactory.Create(CurrentDsn.ProjectID, @event);
var eventId = Send(packet);
RestartTrails();
return eventId;
}
/// <summary>
/// Captures the event.
/// </summary>
/// <param name="e">The <see cref="Exception" /> to capture.</param>
/// <returns></returns>
[Obsolete("Use CaptureException() instead.", true)]
public string CaptureEvent(Exception e)
{
return CaptureException(e);
}
/// <summary>
/// Captures the event.
/// </summary>
/// <param name="e">The <see cref="Exception" /> to capture.</param>
/// <param name="tags">The tags to annotate the captured exception with.</param>
/// <returns></returns>
[Obsolete("Use CaptureException() instead.", true)]
public string CaptureEvent(Exception e, Dictionary<string, string> tags)
{
return CaptureException(e, tags : tags);
}
/// <summary>
/// Captures the <see cref="Exception" />.
/// </summary>
/// <param name="exception">The <see cref="Exception" /> to capture.</param>
/// <param name="message">The optional message to capture. Default: <see cref="Exception.Message" />.</param>
/// <param name="level">The <see cref="ErrorLevel" /> of the captured <paramref name="exception" />. Default: <see cref="ErrorLevel.Error"/>.</param>
/// <param name="tags">The tags to annotate the captured <paramref name="exception" /> with.</param>
/// <param name="fingerprint">The custom fingerprint to annotate the captured <paramref name="message" /> with.</param>
/// <param name="extra">The extra metadata to send with the captured <paramref name="exception" />.</param>
/// <returns>
/// The <see cref="JsonPacket.EventID" /> of the successfully captured <paramref name="exception" />, or <c>null</c> if it fails.
/// </returns>
[Obsolete("Use Capture(SentryEvent) instead")]
public string CaptureException(Exception exception,
SentryMessage message = null,
ErrorLevel level = ErrorLevel.Error,
IDictionary<string, string> tags = null,
string[] fingerprint = null,
object extra = null)
{
var @event = new SentryEvent(exception)
{
Message = message,
Level = level,
Extra = extra,
Tags = MergeTags(tags),
Fingerprint = fingerprint
};
return Capture(@event);
}
/// <summary>
/// Captures the message.
/// </summary>
/// <param name="message">The message to capture.</param>
/// <param name="level">The <see cref="ErrorLevel" /> of the captured <paramref name="message"/>. Default <see cref="ErrorLevel.Info"/>.</param>
/// <param name="tags">The tags to annotate the captured <paramref name="message"/> with.</param>
/// <param name="fingerprint">The custom fingerprint to annotate the captured <paramref name="message" /> with.</param>
/// <param name="extra">The extra metadata to send with the captured <paramref name="message"/>.</param>
/// <returns>
/// The <see cref="JsonPacket.EventID"/> of the successfully captured <paramref name="message"/>, or <c>null</c> if it fails.
/// </returns>
[Obsolete("Use Capture(SentryEvent) instead")]
public string CaptureMessage(SentryMessage message,
ErrorLevel level = ErrorLevel.Info,
IDictionary<string, string> tags = null,
string[] fingerprint = null,
object extra = null)
{
var @event = new SentryEvent(message)
{
Level = level,
Extra = extra,
Tags = MergeTags(tags),
Fingerprint = fingerprint
};
return Capture(@event);
}
/// <summary>
/// Performs <see cref="JsonPacket"/> post-processing prior to being sent to Sentry.
/// </summary>
/// <param name="packet">The prepared <see cref="JsonPacket"/> which has cleared the creation pipeline.</param>
/// <returns>The <see cref="JsonPacket"/> which should be sent to Sentry.</returns>
protected internal virtual JsonPacket PreparePacket(JsonPacket packet)
{
packet.Logger = string.IsNullOrWhiteSpace(packet.Logger)
|| (packet.Logger == "root" && !string.IsNullOrWhiteSpace(Logger))
? Logger
: packet.Logger;
packet.User = packet.User ?? this.sentryUserFactory.Create();
packet.Request = packet.Request ?? this.sentryRequestFactory.Create();
packet.Release = string.IsNullOrWhiteSpace(packet.Release) ? Release : packet.Release;
packet.Environment = string.IsNullOrWhiteSpace(packet.Environment) ? Environment : packet.Environment;
return packet;
}
/// <summary>Sends the specified packet to Sentry.</summary>
/// <param name="packet">The packet to send.</param>
/// <returns>
/// The <see cref="JsonPacket.EventID" /> of the successfully captured JSON packet, or <c>null</c> if it fails.
/// </returns>
protected virtual string Send(JsonPacket packet)
{
Requester requester = null;
try
{
requester = new Requester(packet, this);
if (BeforeSend != null)
requester = BeforeSend(requester);
return requester.Request();
}
catch (Exception exception)
{
return HandleException(exception, requester);
}
}
private string HandleException(Exception exception, Requester requester)
{
string id = null;
try
{
if (ErrorOnCapture != null)
{
ErrorOnCapture(exception);
return null;
}
if (exception != null)
SystemUtil.WriteError(exception);
if (requester != null)
{
if (requester.Data != null)
{
SystemUtil.WriteError("Request body (raw):", requester.Data.Raw);
SystemUtil.WriteError("Request body (scrubbed):", requester.Data.Scrubbed);
}
if (requester.WebRequest != null && requester.WebRequest.Headers != null && requester.WebRequest.Headers.Count > 0)
SystemUtil.WriteError("Request headers:", requester.WebRequest.Headers.ToString());
}
var webException = exception as WebException;
if (webException == null || webException.Response == null)
return null;
var response = webException.Response;
id = response.Headers["X-Sentry-ID"];
if (string.IsNullOrWhiteSpace(id))
id = null;
string messageBody;
using (var stream = response.GetResponseStream())
{
if (stream == null)
return id;
using (var sw = new StreamReader(stream))
{
messageBody = sw.ReadToEnd();
}
}
SystemUtil.WriteError("Response headers:", response.Headers.ToString());
SystemUtil.WriteError("Response body:", messageBody);
}
catch (Exception onErrorException)
{
SystemUtil.WriteError(onErrorException.ToString());
}
return id;
}
private IDictionary<string, string> MergeTags(IDictionary<string, string> tags = null)
{
if (tags == null)
return Tags;
return Tags
.Where(kv => !tags.Keys.Contains(kv.Key))
.Concat(tags)
.ToDictionary(kv => kv.Key, kv => kv.Value);
}
}
}
| |
#region Using directives
#define USE_TRACING
using System.Xml;
#endregion
// <summary>basenametable, holds common names for atom&rss parsing</summary>
namespace Google.GData.Client
{
/// <summary>BaseNameTable. An initialized nametable for faster XML processing
/// parses:
/// * opensearch:totalResults - the total number of search results available (not necessarily all present in the feed).
/// * opensearch:startIndex - the 1-based index of the first result.
/// * opensearch:itemsPerPage - the maximum number of items that appear on one page. This allows clients to generate direct links to any set of subsequent pages.
/// * gData:processed
/// </summary>
public class BaseNameTable
{
/// <summary>
/// namespace of the opensearch v1.0 elements
/// </summary>
public const string NSOpenSearchRss = "http://a9.com/-/spec/opensearchrss/1.0/";
/// <summary>
/// namespace of the opensearch v1.1 elements
/// </summary>
public const string NSOpenSearch11 = "http://a9.com/-/spec/opensearch/1.1/";
/// <summary>static namespace string declaration</summary>
public const string NSAtom = "http://www.w3.org/2005/Atom";
/// <summary>namespace for app publishing control, draft version</summary>
public const string NSAppPublishing = "http://purl.org/atom/app#";
/// <summary>namespace for app publishing control, final version</summary>
public const string NSAppPublishingFinal = "http://www.w3.org/2007/app";
/// <summary>xml namespace</summary>
public const string NSXml = "http://www.w3.org/XML/1998/namespace";
/// <summary>GD namespace</summary>
public const string gNamespace = "http://schemas.google.com/g/2005";
/// <summary>GData batch extension namespace</summary>
public const string gBatchNamespace = "http://schemas.google.com/gdata/batch";
/// <summary>GD namespace prefix</summary>
public const string gNamespacePrefix = gNamespace + "#";
/// <summary>the post definiton in the link collection</summary>
public const string ServicePost = gNamespacePrefix + "post";
/// <summary>the feed definition in the link collection</summary>
public const string ServiceFeed = gNamespacePrefix + "feed";
/// <summary>the batch URI definition in the link collection</summary>
public const string ServiceBatch = gNamespacePrefix + "batch";
/// <summary>GData Kind Scheme</summary>
public const string gKind = gNamespacePrefix + "kind";
/// <summary>label scheme</summary>
public const string gLabels = gNamespace + "/labels";
/// <summary>the edit definition in the link collection</summary>
public const string ServiceEdit = "edit";
/// <summary>the next chunk URI in the link collection</summary>
public const string ServiceNext = "next";
/// <summary>the previous chunk URI in the link collection</summary>
public const string ServicePrev = "previous";
/// <summary>the self URI in the link collection</summary>
public const string ServiceSelf = "self";
/// <summary>the alternate URI in the link collection</summary>
public const string ServiceAlternate = "alternate";
/// <summary>the alternate URI in the link collection</summary>
public const string ServiceMedia = "edit-media";
/// <summary>prefix for atom if writing</summary>
public const string AtomPrefix = "atom";
/// <summary>prefix for gNamespace if writing</summary>
public const string gDataPrefix = "gd";
/// <summary>prefix for gdata:batch if writing</summary>
public const string gBatchPrefix = "batch";
/// <summary>prefix for gd:errors</summary>
public const string gdErrors = "errors";
/// <summary>prefix for gd:error</summary>
public const string gdError = "error";
/// <summary>prefix for gd:domain</summary>
public const string gdDomain = "domain";
/// <summary>prefix for gd:code</summary>
public const string gdCode = "code";
/// <summary>prefix for gd:location</summary>
public const string gdLocation = "location";
/// <summary>prefix for gd:internalReason</summary>
public const string gdInternalReason = "internalReason";
// app publishing control strings
/// <summary>prefix for appPublishing if writing</summary>
public const string gAppPublishingPrefix = "app";
/// <summary>xmlelement for app:control</summary>
public const string XmlElementPubControl = "control";
/// <summary>xmlelement for app:draft</summary>
public const string XmlElementPubDraft = "draft";
/// <summary>xmlelement for app:draft</summary>
public const string XmlElementPubEdited = "edited";
/// <summary>
/// static string for parsing the etag attribute
/// </summary>
/// <returns></returns>
public const string XmlEtagAttribute = "etag";
// batch strings:
/// <summary>xmlelement for batch:id</summary>
public const string XmlElementBatchId = "id";
/// <summary>xmlelement for batch:operation</summary>
public const string XmlElementBatchOperation = "operation";
/// <summary>xmlelement for batch:status</summary>
public const string XmlElementBatchStatus = "status";
/// <summary>xmlelement for batch:interrupted</summary>
public const string XmlElementBatchInterrupt = "interrupted";
/// <summary>xmlattribute for batch:status@contentType</summary>
public const string XmlAttributeBatchContentType = "content-type";
/// <summary>xmlattribute for batch:status@code</summary>
public const string XmlAttributeBatchStatusCode = "code";
/// <summary>xmlattribute for batch:status@reason</summary>
public const string XmlAttributeBatchReason = "reason";
/// <summary>xmlelement for batch:status:errors</summary>
public const string XmlElementBatchErrors = "errors";
/// <summary>xmlelement for batch:status:errors:error</summary>
public const string XmlElementBatchError = "error";
/// <summary>xmlattribute for batch:interrupted@success</summary>
public const string XmlAttributeBatchSuccess = "success";
/// <summary>XmlAttribute for batch:interrupted@parsed</summary>
public const string XmlAttributeBatchParsed = "parsed";
/// <summary>XmlAttribute for batch:interrupted@field</summary>
public const string XmlAttributeBatchField = "field";
/// <summary>XmlAttribute for batch:interrupted@unprocessed</summary>
public const string XmlAttributeBatchUnprocessed = "unprocessed";
/// <summary>XmlConstant for value in enums</summary>
public const string XmlValue = "value";
/// <summary>XmlConstant for name in enums</summary>
public const string XmlName = "name";
/// <summary>XmlAttribute for type in enums</summary>
public const string XmlAttributeType = "type";
/// <summary>XmlAttribute for key in enums</summary>
public const string XmlAttributeKey = "key";
/// <summary>the nametable itself, based on XML core</summary>
private NameTable atomNameTable;
/// <summary>xml base</summary>
private object baseUri;
// batch extensions
/// <summary>opensearch:itemsPerPage</summary>
private object itemsPerPage;
/// <summary>xml language</summary>
private object language;
/// <summary>opensearch:startIndex</summary>
private object startIndex;
/// <summary>opensearch:totalResults</summary>
private object totalResults;
/// <summary>initializes the name table for use with atom parsing. This is the
/// only place where strings are defined for parsing</summary>
public virtual void InitAtomParserNameTable()
{
// create the nametable object
Tracing.TraceCall("Initializing basenametable support");
atomNameTable = new NameTable();
// <summary>add the keywords for the Feed
totalResults = atomNameTable.Add("totalResults");
startIndex = atomNameTable.Add("startIndex");
itemsPerPage = atomNameTable.Add("itemsPerPage");
baseUri = atomNameTable.Add("base");
language = atomNameTable.Add("lang");
// batch keywords
BatchId = atomNameTable.Add(XmlElementBatchId);
BatchOperation = atomNameTable.Add(XmlElementBatchOperation);
BatchStatus = atomNameTable.Add(XmlElementBatchStatus);
BatchInterrupt = atomNameTable.Add(XmlElementBatchInterrupt);
BatchContentType = atomNameTable.Add(XmlAttributeBatchContentType);
BatchStatusCode = atomNameTable.Add(XmlAttributeBatchStatusCode);
BatchReason = atomNameTable.Add(XmlAttributeBatchReason);
BatchErrors = atomNameTable.Add(XmlElementBatchErrors);
BatchError = atomNameTable.Add(XmlElementBatchError);
BatchSuccessCount = atomNameTable.Add(XmlAttributeBatchSuccess);
BatchFailureCount = BatchError;
BatchParsedCount = atomNameTable.Add(XmlAttributeBatchParsed);
BatchField = atomNameTable.Add(XmlAttributeBatchField);
BatchUnprocessed = atomNameTable.Add(XmlAttributeBatchUnprocessed);
Type = atomNameTable.Add(XmlAttributeType);
Value = atomNameTable.Add(XmlValue);
Name = atomNameTable.Add(XmlName);
ETag = atomNameTable.Add(XmlEtagAttribute);
}
/// <summary>
/// returns the correct opensearchnamespace to use based
/// on the version information passed in. All protocols with
/// version > 1 use opensearch1.1 where version 1 uses
/// opensearch 1.0
/// </summary>
/// <param name="v">The versioninformation</param>
/// <returns></returns>
public static string OpenSearchNamespace(IVersionAware v)
{
int major = VersionDefaults.Major;
if (v != null)
{
major = v.ProtocolMajor;
}
if (major == 1)
{
return NSOpenSearchRss;
}
return NSOpenSearch11;
}
/// <summary>
/// returns the correct app:publishing namespace to use based
/// on the version information passed in. All protocols with
/// version > 1 use the final version of the namespace, where
/// version 1 uses the draft version.
/// </summary>
/// <param name="v">The versioninformation</param>
/// <returns></returns>
public static string AppPublishingNamespace(IVersionAware v)
{
int major = VersionDefaults.Major;
if (v != null)
{
major = v.ProtocolMajor;
}
if (major == 1)
{
return NSAppPublishing;
}
return NSAppPublishingFinal;
}
#region Read only accessors 8/10/2005
/// <summary>Read only accessor for atomNameTable</summary>
internal NameTable Nametable
{
get { return atomNameTable; }
}
/// <summary>Read only accessor for BatchId</summary>
public object BatchId { get; private set; }
/// <summary>Read only accessor for BatchOperation</summary>
public object BatchOperation { get; private set; }
/// <summary>Read only accessor for BatchStatus</summary>
public object BatchStatus { get; private set; }
/// <summary>Read only accessor for BatchInterrupt</summary>
public object BatchInterrupt { get; private set; }
/// <summary>Read only accessor for BatchContentType</summary>
public object BatchContentType { get; private set; }
/// <summary>Read only accessor for BatchStatusCode</summary>
public object BatchStatusCode { get; private set; }
/// <summary>Read only accessor for BatchErrors</summary>
public object BatchErrors { get; private set; }
/// <summary>Read only accessor for BatchError</summary>
public object BatchError { get; private set; }
/// <summary>Read only accessor for BatchReason</summary>
public object BatchReason { get; private set; }
/// <summary>Read only accessor for BatchReason</summary>
public object BatchField { get; private set; }
/// <summary>Read only accessor for BatchUnprocessed</summary>
public object BatchUnprocessed { get; private set; }
/// <summary>Read only accessor for BatchSuccessCount</summary>
public object BatchSuccessCount { get; private set; }
/// <summary>Read only accessor for BatchFailureCount</summary>
public object BatchFailureCount { get; private set; }
/// <summary>Read only accessor for BatchParsedCount</summary>
public object BatchParsedCount { get; private set; }
/// <summary>Read only accessor for totalResults</summary>
public object TotalResults
{
get { return totalResults; }
}
/// <summary>Read only accessor for startIndex</summary>
public object StartIndex
{
get { return startIndex; }
}
/// <summary>Read only accessor for itemsPerPage</summary>
public object ItemsPerPage
{
get { return itemsPerPage; }
}
/// <summary>Read only accessor for parameter</summary>
public static string Parameter
{
get { return "parameter"; }
}
/// <summary>Read only accessor for baseUri</summary>
public object Base
{
get { return baseUri; }
}
/// <summary>Read only accessor for language</summary>
public object Language
{
get { return language; }
}
/// <summary>Read only accessor for value</summary>
public object Value { get; private set; }
/// <summary>Read only accessor for value</summary>
public object Type { get; private set; }
/// <summary>Read only accessor for name</summary>
public object Name { get; private set; }
/// <summary>Read only accessor for etag</summary>
public object ETag { get; private set; }
#endregion end of Read only accessors
}
}
| |
// <copyright file="Actions.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Drawing;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Interactions
{
/// <summary>
/// Provides values that indicate from where element offsets for MoveToElement
/// are calculated.
/// </summary>
public enum MoveToElementOffsetOrigin
{
/// <summary>
/// Offsets are calculated from the top-left corner of the element.
/// </summary>
TopLeft,
/// <summary>
/// Offsets are calcuated from the center of the element.
/// </summary>
Center
}
/// <summary>
/// Provides a mechanism for building advanced interactions with the browser.
/// </summary>
public class Actions : IAction
{
private readonly TimeSpan DefaultMouseMoveDuration = TimeSpan.FromMilliseconds(250);
private ActionBuilder actionBuilder = new ActionBuilder();
private PointerInputDevice defaultMouse = new PointerInputDevice(PointerKind.Mouse, "default mouse");
private KeyInputDevice defaultKeyboard = new KeyInputDevice("default keyboard");
private IActionExecutor actionExecutor;
/// <summary>
/// Initializes a new instance of the <see cref="Actions"/> class.
/// </summary>
/// <param name="driver">The <see cref="IWebDriver"/> object on which the actions built will be performed.</param>
public Actions(IWebDriver driver)
{
IActionExecutor actionExecutor = GetDriverAs<IActionExecutor>(driver);
if (actionExecutor == null)
{
throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IActionExecutor.", "driver");
}
this.actionExecutor = actionExecutor;
}
/// <summary>
/// Returns the <see cref="IActionExecutor"/> for the driver.
/// </summary>
protected IActionExecutor ActionExecutor
{
get { return this.actionExecutor; }
}
/// <summary>
/// Sends a modifier key down message to the browser.
/// </summary>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyDown(string theKey)
{
return this.KeyDown(null, theKey);
}
/// <summary>
/// Sends a modifier key down message to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the key command.</param>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyDown(IWebElement element, string theKey)
{
if (string.IsNullOrEmpty(theKey))
{
throw new ArgumentException("The key value must not be null or empty", "theKey");
}
ILocatable target = GetLocatableFromElement(element);
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(theKey[0]));
this.actionBuilder.AddAction(new PauseInteraction(this.defaultKeyboard, TimeSpan.FromMilliseconds(100)));
return this;
}
/// <summary>
/// Sends a modifier key up message to the browser.
/// </summary>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyUp(string theKey)
{
return this.KeyUp(null, theKey);
}
/// <summary>
/// Sends a modifier up down message to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the key command.</param>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyUp(IWebElement element, string theKey)
{
if (string.IsNullOrEmpty(theKey))
{
throw new ArgumentException("The key value must not be null or empty", "theKey");
}
ILocatable target = GetLocatableFromElement(element);
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(theKey[0]));
return this;
}
/// <summary>
/// Sends a sequence of keystrokes to the browser.
/// </summary>
/// <param name="keysToSend">The keystrokes to send to the browser.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions SendKeys(string keysToSend)
{
return this.SendKeys(null, keysToSend);
}
/// <summary>
/// Sends a sequence of keystrokes to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the keystrokes.</param>
/// <param name="keysToSend">The keystrokes to send to the browser.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions SendKeys(IWebElement element, string keysToSend)
{
if (string.IsNullOrEmpty(keysToSend))
{
throw new ArgumentException("The key value must not be null or empty", "keysToSend");
}
ILocatable target = GetLocatableFromElement(element);
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
foreach (char key in keysToSend)
{
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(key));
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(key));
}
return this;
}
/// <summary>
/// Clicks and holds the mouse button down on the specified element.
/// </summary>
/// <param name="onElement">The element on which to click and hold.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ClickAndHold(IWebElement onElement)
{
this.MoveToElement(onElement).ClickAndHold();
return this;
}
/// <summary>
/// Clicks and holds the mouse button at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ClickAndHold()
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
return this;
}
/// <summary>
/// Releases the mouse button on the specified element.
/// </summary>
/// <param name="onElement">The element on which to release the button.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Release(IWebElement onElement)
{
this.MoveToElement(onElement).Release();
return this;
}
/// <summary>
/// Releases the mouse button at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Release()
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Click(IWebElement onElement)
{
this.MoveToElement(onElement).Click();
return this;
}
/// <summary>
/// Clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Click()
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Double-clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to double-click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DoubleClick(IWebElement onElement)
{
this.MoveToElement(onElement).DoubleClick();
return this;
}
/// <summary>
/// Double-clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DoubleClick()
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Moves the mouse to the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement)
{
if (toElement == null)
{
throw new ArgumentException("MoveToElement cannot move to a null element with no offset.", "toElement");
}
ILocatable target = GetLocatableFromElement(toElement);
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, 0, 0, DefaultMouseMoveDuration));
return this;
}
/// <summary>
/// Moves the mouse to the specified offset of the top-left corner of the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement, int offsetX, int offsetY)
{
return this.MoveToElement(toElement, offsetX, offsetY, MoveToElementOffsetOrigin.TopLeft);
}
/// <summary>
/// Moves the mouse to the specified offset of the top-left corner of the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <param name="offsetOrigin">The <see cref="MoveToElementOffsetOrigin"/> value from which to calculate the offset.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement, int offsetX, int offsetY, MoveToElementOffsetOrigin offsetOrigin)
{
ILocatable target = GetLocatableFromElement(toElement);
Size elementSize = toElement.Size;
Point elementLocation = toElement.Location;
if (offsetOrigin == MoveToElementOffsetOrigin.TopLeft)
{
int modifiedOffsetX = offsetX - (elementSize.Width / 2);
int modifiedOffsetY = offsetY - (elementSize.Height / 2);
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, modifiedOffsetX, modifiedOffsetY, DefaultMouseMoveDuration));
}
else
{
int modifiedOffsetX = offsetX + (elementSize.Width / 2);
int modifiedOffsetY = offsetY + (elementSize.Height / 2);
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, offsetX, offsetY, DefaultMouseMoveDuration));
}
return this;
}
/// <summary>
/// Moves the mouse to the specified offset of the last known mouse coordinates.
/// </summary>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveByOffset(int offsetX, int offsetY)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(CoordinateOrigin.Pointer, offsetX, offsetY, DefaultMouseMoveDuration));
return this;
}
/// <summary>
/// Right-clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to right-click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ContextClick(IWebElement onElement)
{
this.MoveToElement(onElement).ContextClick();
return this;
}
/// <summary>
/// Right-clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ContextClick()
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Right));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Right));
return this;
}
/// <summary>
/// Performs a drag-and-drop operation from one element to another.
/// </summary>
/// <param name="source">The element on which the drag operation is started.</param>
/// <param name="target">The element on which the drop is performed.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DragAndDrop(IWebElement source, IWebElement target)
{
this.ClickAndHold(source).MoveToElement(target).Release(target);
return this;
}
/// <summary>
/// Performs a drag-and-drop operation on one element to a specified offset.
/// </summary>
/// <param name="source">The element on which the drag operation is started.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DragAndDropToOffset(IWebElement source, int offsetX, int offsetY)
{
this.ClickAndHold(source).MoveByOffset(offsetX, offsetY).Release();
return this;
}
/// <summary>
/// Builds the sequence of actions.
/// </summary>
/// <returns>A composite <see cref="IAction"/> which can be used to perform the actions.</returns>
public IAction Build()
{
return this;
}
/// <summary>
/// Performs the currently built action.
/// </summary>
public void Perform()
{
this.actionExecutor.PerformActions(this.actionBuilder.ToActionSequenceList());
}
public void Reset()
{
this.actionBuilder = new ActionBuilder();
}
/// <summary>
/// Gets the <see cref="ILocatable"/> instance of the specified <see cref="IWebElement"/>.
/// </summary>
/// <param name="element">The <see cref="IWebElement"/> to get the location of.</param>
/// <returns>The <see cref="ILocatable"/> of the <see cref="IWebElement"/>.</returns>
protected static ILocatable GetLocatableFromElement(IWebElement element)
{
if (element == null)
{
return null;
}
ILocatable target = null;
IWrapsElement wrapper = element as IWrapsElement;
while (wrapper != null)
{
target = wrapper.WrappedElement as ILocatable;
wrapper = wrapper.WrappedElement as IWrapsElement;
}
if (target == null)
{
target = element as ILocatable;
}
if (target == null)
{
throw new ArgumentException("The IWebElement object must implement or wrap an element that implements ILocatable.", "element");
}
return target;
}
private T GetDriverAs<T>(IWebDriver driver) where T : class
{
T driverAsType = driver as T;
if (driverAsType == null)
{
IWrapsDriver wrapper = driver as IWrapsDriver;
while (wrapper != null)
{
driverAsType = wrapper.WrappedDriver as T;
if (driverAsType != null)
{
driver = wrapper.WrappedDriver;
break;
}
wrapper = wrapper.WrappedDriver as IWrapsDriver;
}
}
return driverAsType;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type long with 2 columns and 2 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct lmat2 : IReadOnlyList<long>, IEquatable<lmat2>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public long m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public long m01;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public long m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public long m11;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public lmat2(long m00, long m01, long m10, long m11)
{
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
}
/// <summary>
/// Constructs this matrix from a lmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a lmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a lmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a lmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a lmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a lmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a lmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a lmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a lmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2(lvec2 c0, lvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public long[,] Values => new[,] { { m00, m01 }, { m10, m11 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public long[] Values1D => new[] { m00, m01, m10, m11 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public lvec2 Column0
{
get
{
return new lvec2(m00, m01);
}
set
{
m00 = value.x;
m01 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public lvec2 Column1
{
get
{
return new lvec2(m10, m11);
}
set
{
m10 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public lvec2 Row0
{
get
{
return new lvec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public lvec2 Row1
{
get
{
return new lvec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static lmat2 Zero { get; } = new lmat2(0, 0, 0, 0);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static lmat2 Ones { get; } = new lmat2(1, 1, 1, 1);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static lmat2 Identity { get; } = new lmat2(1, 0, 0, 1);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static lmat2 AllMaxValue { get; } = new lmat2(long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static lmat2 DiagonalMaxValue { get; } = new lmat2(long.MaxValue, 0, 0, long.MaxValue);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static lmat2 AllMinValue { get; } = new lmat2(long.MinValue, long.MinValue, long.MinValue, long.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static lmat2 DiagonalMinValue { get; } = new lmat2(long.MinValue, 0, 0, long.MinValue);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<long> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m10;
yield return m11;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 2 = 4).
/// </summary>
public int Count => 4;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public long this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m10;
case 3: return m11;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m10 = value; break;
case 3: this.m11 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public long this[int col, int row]
{
get
{
return this[col * 2 + row];
}
set
{
this[col * 2 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(lmat2 rhs) => ((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is lmat2 && Equals((lmat2) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(lmat2 lhs, lmat2 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(lmat2 lhs, lmat2 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public lmat2 Transposed => new lmat2(m00, m10, m01, m11);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public long MinElement => Math.Min(Math.Min(Math.Min(m00, m01), m10), m11);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public long MaxElement => Math.Max(Math.Max(Math.Max(m00, m01), m10), m11);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public double Length => (double)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11)));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public double LengthSqr => ((m00*m00 + m01*m01) + (m10*m10 + m11*m11));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public long Sum => ((m00 + m01) + (m10 + m11));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public double Norm => (double)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11)));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public double Norm1 => ((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m10) + Math.Abs(m11)));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public double Norm2 => (double)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11)));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public long NormMax => Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow(((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))), 1 / p);
/// <summary>
/// Returns determinant of this matrix.
/// </summary>
public long Determinant => m00 * m11 - m10 * m01;
/// <summary>
/// Returns the adjunct of this matrix.
/// </summary>
public lmat2 Adjugate => new lmat2(m11, -m01, -m10, m00);
/// <summary>
/// Returns the inverse of this matrix (use with caution).
/// </summary>
public lmat2 Inverse => Adjugate / Determinant;
/// <summary>
/// Executes a matrix-matrix-multiplication lmat2 * lmat2 -> lmat2.
/// </summary>
public static lmat2 operator*(lmat2 lhs, lmat2 rhs) => new lmat2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication lmat2 * lmat3x2 -> lmat3x2.
/// </summary>
public static lmat3x2 operator*(lmat2 lhs, lmat3x2 rhs) => new lmat3x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication lmat2 * lmat4x2 -> lmat4x2.
/// </summary>
public static lmat4x2 operator*(lmat2 lhs, lmat4x2 rhs) => new lmat4x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static lvec2 operator*(lmat2 m, lvec2 v) => new lvec2((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y));
/// <summary>
/// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution).
/// </summary>
public static lmat2 operator/(lmat2 A, lmat2 B) => A * B.Inverse;
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static lmat2 CompMul(lmat2 A, lmat2 B) => new lmat2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static lmat2 CompDiv(lmat2 A, lmat2 B) => new lmat2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static lmat2 CompAdd(lmat2 A, lmat2 B) => new lmat2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static lmat2 CompSub(lmat2 A, lmat2 B) => new lmat2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static lmat2 operator+(lmat2 lhs, lmat2 rhs) => new lmat2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static lmat2 operator+(lmat2 lhs, long rhs) => new lmat2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static lmat2 operator+(long lhs, lmat2 rhs) => new lmat2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static lmat2 operator-(lmat2 lhs, lmat2 rhs) => new lmat2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static lmat2 operator-(lmat2 lhs, long rhs) => new lmat2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static lmat2 operator-(long lhs, lmat2 rhs) => new lmat2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static lmat2 operator/(lmat2 lhs, long rhs) => new lmat2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static lmat2 operator/(long lhs, lmat2 rhs) => new lmat2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static lmat2 operator*(lmat2 lhs, long rhs) => new lmat2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static lmat2 operator*(long lhs, lmat2 rhs) => new lmat2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11);
/// <summary>
/// Executes a component-wise % (modulo).
/// </summary>
public static lmat2 operator%(lmat2 lhs, lmat2 rhs) => new lmat2(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11);
/// <summary>
/// Executes a component-wise % (modulo) with a scalar.
/// </summary>
public static lmat2 operator%(lmat2 lhs, long rhs) => new lmat2(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m10 % rhs, lhs.m11 % rhs);
/// <summary>
/// Executes a component-wise % (modulo) with a scalar.
/// </summary>
public static lmat2 operator%(long lhs, lmat2 rhs) => new lmat2(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m10, lhs % rhs.m11);
/// <summary>
/// Executes a component-wise ^ (xor).
/// </summary>
public static lmat2 operator^(lmat2 lhs, lmat2 rhs) => new lmat2(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11);
/// <summary>
/// Executes a component-wise ^ (xor) with a scalar.
/// </summary>
public static lmat2 operator^(lmat2 lhs, long rhs) => new lmat2(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs);
/// <summary>
/// Executes a component-wise ^ (xor) with a scalar.
/// </summary>
public static lmat2 operator^(long lhs, lmat2 rhs) => new lmat2(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m10, lhs ^ rhs.m11);
/// <summary>
/// Executes a component-wise | (bitwise-or).
/// </summary>
public static lmat2 operator|(lmat2 lhs, lmat2 rhs) => new lmat2(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11);
/// <summary>
/// Executes a component-wise | (bitwise-or) with a scalar.
/// </summary>
public static lmat2 operator|(lmat2 lhs, long rhs) => new lmat2(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m10 | rhs, lhs.m11 | rhs);
/// <summary>
/// Executes a component-wise | (bitwise-or) with a scalar.
/// </summary>
public static lmat2 operator|(long lhs, lmat2 rhs) => new lmat2(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m10, lhs | rhs.m11);
/// <summary>
/// Executes a component-wise & (bitwise-and).
/// </summary>
public static lmat2 operator&(lmat2 lhs, lmat2 rhs) => new lmat2(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11);
/// <summary>
/// Executes a component-wise & (bitwise-and) with a scalar.
/// </summary>
public static lmat2 operator&(lmat2 lhs, long rhs) => new lmat2(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m10 & rhs, lhs.m11 & rhs);
/// <summary>
/// Executes a component-wise & (bitwise-and) with a scalar.
/// </summary>
public static lmat2 operator&(long lhs, lmat2 rhs) => new lmat2(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m10, lhs & rhs.m11);
/// <summary>
/// Executes a component-wise left-shift with a scalar.
/// </summary>
public static lmat2 operator<<(lmat2 lhs, int rhs) => new lmat2(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m10 << rhs, lhs.m11 << rhs);
/// <summary>
/// Executes a component-wise right-shift with a scalar.
/// </summary>
public static lmat2 operator>>(lmat2 lhs, int rhs) => new lmat2(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2 operator<(lmat2 lhs, lmat2 rhs) => new bmat2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2 operator<(lmat2 lhs, long rhs) => new bmat2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2 operator<(long lhs, lmat2 rhs) => new bmat2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2 operator<=(lmat2 lhs, lmat2 rhs) => new bmat2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2 operator<=(lmat2 lhs, long rhs) => new bmat2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2 operator<=(long lhs, lmat2 rhs) => new bmat2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2 operator>(lmat2 lhs, lmat2 rhs) => new bmat2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2 operator>(lmat2 lhs, long rhs) => new bmat2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2 operator>(long lhs, lmat2 rhs) => new bmat2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2 operator>=(lmat2 lhs, lmat2 rhs) => new bmat2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2 operator>=(lmat2 lhs, long rhs) => new bmat2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2 operator>=(long lhs, lmat2 rhs) => new bmat2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11);
}
}
| |
/*
* 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.IO;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
namespace OpenSim.Region.CoreModules.World.Serialiser
{
public class SerialiserModule : ISharedRegionModule, IRegionSerialiserModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Commander m_commander = new Commander("export");
private List<Scene> m_regions = new List<Scene>();
private string m_savedir = "exports";
private List<IFileSerialiser> m_serialisers = new List<IFileSerialiser>();
#region ISharedRegionModule Members
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["Serialiser"];
if (config != null)
{
m_savedir = config.GetString("save_dir", m_savedir);
}
m_log.InfoFormat("[Serialiser] Enabled, using save dir \"{0}\"", m_savedir);
}
public void PostInitialise()
{
lock (m_serialisers)
{
m_serialisers.Add(new SerialiseTerrain());
m_serialisers.Add(new SerialiseObjects());
}
LoadCommanderCommands();
}
public void AddRegion(Scene scene)
{
scene.RegisterModuleCommander(m_commander);
scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
scene.RegisterModuleInterface<IRegionSerialiserModule>(this);
lock (m_regions)
{
m_regions.Add(scene);
}
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
lock (m_regions)
{
m_regions.Remove(scene);
}
}
public void Close()
{
m_regions.Clear();
}
public string Name
{
get { return "ExportSerialisationModule"; }
}
#endregion
#region IRegionSerialiser Members
public void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
SceneXmlLoader.LoadPrimsFromXml(scene, fileName, newIDS, loadOffset);
}
public void SavePrimsToXml(Scene scene, string fileName)
{
SceneXmlLoader.SavePrimsToXml(scene, fileName);
}
public void LoadPrimsFromXml2(Scene scene, string fileName)
{
SceneXmlLoader.LoadPrimsFromXml2(scene, fileName);
}
public void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
SceneXmlLoader.LoadPrimsFromXml2(scene, reader, startScripts);
}
public void SavePrimsToXml2(Scene scene, string fileName)
{
SceneXmlLoader.SavePrimsToXml2(scene, fileName);
}
public void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
SceneXmlLoader.SavePrimsToXml2(scene, stream, min, max);
}
public void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
SceneXmlLoader.SaveNamedPrimsToXml2(scene, primName, fileName);
}
public SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
return SceneXmlLoader.DeserializeGroupFromXml2(xmlString);
}
public string SerializeGroupToXml2(SceneObjectGroup grp, Dictionary<string, object> options)
{
return SceneXmlLoader.SaveGroupToXml2(grp, options);
}
public void SavePrimListToXml2(EntityBase[] entityList, string fileName)
{
SceneXmlLoader.SavePrimListToXml2(entityList, fileName);
}
public void SavePrimListToXml2(EntityBase[] entityList, TextWriter stream, Vector3 min, Vector3 max)
{
SceneXmlLoader.SavePrimListToXml2(entityList, stream, min, max);
}
public List<string> SerialiseRegion(Scene scene, string saveDir)
{
List<string> results = new List<string>();
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
lock (m_serialisers)
{
foreach (IFileSerialiser serialiser in m_serialisers)
{
results.Add(serialiser.WriteToFile(scene, saveDir));
}
}
TextWriter regionInfoWriter = new StreamWriter(Path.Combine(saveDir, "README.TXT"));
regionInfoWriter.WriteLine("Region Name: " + scene.RegionInfo.RegionName);
regionInfoWriter.WriteLine("Region ID: " + scene.RegionInfo.RegionID.ToString());
regionInfoWriter.WriteLine("Backup Time: UTC " + DateTime.UtcNow.ToString());
regionInfoWriter.WriteLine("Serialise Version: 0.1");
regionInfoWriter.Close();
TextWriter manifestWriter = new StreamWriter(Path.Combine(saveDir, "region.manifest"));
foreach (string line in results)
{
manifestWriter.WriteLine(line);
}
manifestWriter.Close();
return results;
}
#endregion
private void EventManager_OnPluginConsole(string[] args)
{
if (args[0] == "export")
{
string[] tmpArgs = new string[args.Length - 2];
int i = 0;
for (i = 2; i < args.Length; i++)
tmpArgs[i - 2] = args[i];
m_commander.ProcessConsoleCommand(args[1], tmpArgs);
}
}
private void InterfaceSaveRegion(Object[] args)
{
foreach (Scene region in m_regions)
{
if (region.RegionInfo.RegionName == (string) args[0])
{
// List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
SerialiseRegion(region, Path.Combine(m_savedir, region.RegionInfo.RegionID.ToString()));
}
}
}
private void InterfaceSaveAllRegions(Object[] args)
{
foreach (Scene region in m_regions)
{
// List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
SerialiseRegion(region, Path.Combine(m_savedir, region.RegionInfo.RegionID.ToString()));
}
}
private void LoadCommanderCommands()
{
Command serialiseSceneCommand = new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveRegion, "Saves the named region into the exports directory.");
serialiseSceneCommand.AddArgument("region-name", "The name of the region you wish to export", "String");
Command serialiseAllScenesCommand = new Command("save-all",CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveAllRegions, "Saves all regions into the exports directory.");
m_commander.RegisterCommand("save", serialiseSceneCommand);
m_commander.RegisterCommand("save-all", serialiseAllScenesCommand);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Screens;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input.Bindings;
using osu.Game.Online.API;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Screens.Ranking.Statistics;
using osuTK;
namespace osu.Game.Screens.Ranking
{
public abstract class ResultsScreen : ScreenWithBeatmapBackground, IKeyBindingHandler<GlobalAction>
{
protected const float BACKGROUND_BLUR = 20;
private static readonly float screen_height = 768 - TwoLayerButton.SIZE_EXTENDED.Y;
public override bool DisallowExternalBeatmapRulesetChanges => true;
// Temporary for now to stop dual transitions. Should respect the current toolbar mode, but there's no way to do so currently.
public override bool HideOverlaysOnEnter => true;
public readonly Bindable<ScoreInfo> SelectedScore = new Bindable<ScoreInfo>();
public readonly ScoreInfo Score;
protected ScorePanelList ScorePanelList { get; private set; }
protected VerticalScrollContainer VerticalScrollContent { get; private set; }
[Resolved(CanBeNull = true)]
private Player player { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
private StatisticsPanel statisticsPanel;
private Drawable bottomPanel;
private Container<ScorePanel> detachedPanelContainer;
private bool lastFetchCompleted;
private readonly bool allowRetry;
private readonly bool allowWatchingReplay;
protected ResultsScreen(ScoreInfo score, bool allowRetry, bool allowWatchingReplay = true)
{
Score = score;
this.allowRetry = allowRetry;
this.allowWatchingReplay = allowWatchingReplay;
SelectedScore.Value = score;
}
[BackgroundDependencyLoader]
private void load()
{
FillFlowContainer buttons;
InternalChild = new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
VerticalScrollContent = new VerticalScrollContainer
{
RelativeSizeAxes = Axes.Both,
ScrollbarVisible = false,
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
statisticsPanel = new StatisticsPanel
{
RelativeSizeAxes = Axes.Both,
Score = { BindTarget = SelectedScore }
},
ScorePanelList = new ScorePanelList
{
RelativeSizeAxes = Axes.Both,
SelectedScore = { BindTarget = SelectedScore },
PostExpandAction = () => statisticsPanel.ToggleVisibility()
},
detachedPanelContainer = new Container<ScorePanel>
{
RelativeSizeAxes = Axes.Both
},
}
}
},
},
new[]
{
bottomPanel = new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
RelativeSizeAxes = Axes.X,
Height = TwoLayerButton.SIZE_EXTENDED.Y,
Alpha = 0,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4Extensions.FromHex("#333")
},
buttons = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Spacing = new Vector2(5),
Direction = FillDirection.Horizontal
}
}
}
}
},
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize)
}
};
if (Score != null)
{
// only show flair / animation when arriving after watching a play that isn't autoplay.
bool shouldFlair = player != null && Score.Mods.All(m => m.UserPlayable);
ScorePanelList.AddScore(Score, shouldFlair);
}
if (allowWatchingReplay)
{
buttons.Add(new ReplayDownloadButton(null)
{
Score = { BindTarget = SelectedScore },
Width = 300
});
}
if (player != null && allowRetry)
{
buttons.Add(new RetryButton { Width = 300 });
AddInternal(new HotkeyRetryOverlay
{
Action = () =>
{
if (!this.IsCurrentScreen()) return;
player?.Restart();
},
});
}
}
protected override void LoadComplete()
{
base.LoadComplete();
var req = FetchScores(fetchScoresCallback);
if (req != null)
api.Queue(req);
statisticsPanel.State.BindValueChanged(onStatisticsStateChanged, true);
}
protected override void Update()
{
base.Update();
if (lastFetchCompleted)
{
APIRequest nextPageRequest = null;
if (ScorePanelList.IsScrolledToStart)
nextPageRequest = FetchNextPage(-1, fetchScoresCallback);
else if (ScorePanelList.IsScrolledToEnd)
nextPageRequest = FetchNextPage(1, fetchScoresCallback);
if (nextPageRequest != null)
{
lastFetchCompleted = false;
api.Queue(nextPageRequest);
}
}
}
/// <summary>
/// Performs a fetch/refresh of scores to be displayed.
/// </summary>
/// <param name="scoresCallback">A callback which should be called when fetching is completed. Scheduling is not required.</param>
/// <returns>An <see cref="APIRequest"/> responsible for the fetch operation. This will be queued and performed automatically.</returns>
protected virtual APIRequest FetchScores(Action<IEnumerable<ScoreInfo>> scoresCallback) => null;
/// <summary>
/// Performs a fetch of the next page of scores. This is invoked every frame until a non-null <see cref="APIRequest"/> is returned.
/// </summary>
/// <param name="direction">The fetch direction. -1 to fetch scores greater than the current start of the list, and 1 to fetch scores lower than the current end of the list.</param>
/// <param name="scoresCallback">A callback which should be called when fetching is completed. Scheduling is not required.</param>
/// <returns>An <see cref="APIRequest"/> responsible for the fetch operation. This will be queued and performed automatically.</returns>
protected virtual APIRequest FetchNextPage(int direction, Action<IEnumerable<ScoreInfo>> scoresCallback) => null;
private void fetchScoresCallback(IEnumerable<ScoreInfo> scores) => Schedule(() =>
{
foreach (var s in scores)
addScore(s);
lastFetchCompleted = true;
});
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
ApplyToBackground(b =>
{
b.BlurAmount.Value = BACKGROUND_BLUR;
b.FadeColour(OsuColour.Gray(0.5f), 250);
});
bottomPanel.FadeTo(1, 250);
}
public override bool OnExiting(IScreen next)
{
if (base.OnExiting(next))
return true;
this.FadeOut(100);
return false;
}
public override bool OnBackButton()
{
if (statisticsPanel.State.Value == Visibility.Visible)
{
statisticsPanel.Hide();
return true;
}
return false;
}
private void addScore(ScoreInfo score)
{
var panel = ScorePanelList.AddScore(score);
if (detachedPanel != null)
panel.Alpha = 0;
}
private ScorePanel detachedPanel;
private void onStatisticsStateChanged(ValueChangedEvent<Visibility> state)
{
if (state.NewValue == Visibility.Visible)
{
// Detach the panel in its original location, and move into the desired location in the local container.
var expandedPanel = ScorePanelList.GetPanelForScore(SelectedScore.Value);
var screenSpacePos = expandedPanel.ScreenSpaceDrawQuad.TopLeft;
// Detach and move into the local container.
ScorePanelList.Detach(expandedPanel);
detachedPanelContainer.Add(expandedPanel);
// Move into its original location in the local container first, then to the final location.
float origLocation = detachedPanelContainer.ToLocalSpace(screenSpacePos).X;
expandedPanel.MoveToX(origLocation)
.Then()
.MoveToX(StatisticsPanel.SIDE_PADDING, 150, Easing.OutQuint);
// Hide contracted panels.
foreach (var contracted in ScorePanelList.GetScorePanels().Where(p => p.State == PanelState.Contracted))
contracted.FadeOut(150, Easing.OutQuint);
ScorePanelList.HandleInput = false;
// Dim background.
ApplyToBackground(b => b.FadeColour(OsuColour.Gray(0.1f), 150));
detachedPanel = expandedPanel;
}
else if (detachedPanel != null)
{
var screenSpacePos = detachedPanel.ScreenSpaceDrawQuad.TopLeft;
// Remove from the local container and re-attach.
detachedPanelContainer.Remove(detachedPanel);
ScorePanelList.Attach(detachedPanel);
// Move into its original location in the attached container first, then to the final location.
float origLocation = detachedPanel.Parent.ToLocalSpace(screenSpacePos).X;
detachedPanel.MoveToX(origLocation)
.Then()
.MoveToX(0, 150, Easing.OutQuint);
// Show contracted panels.
foreach (var contracted in ScorePanelList.GetScorePanels().Where(p => p.State == PanelState.Contracted))
contracted.FadeIn(150, Easing.OutQuint);
ScorePanelList.HandleInput = true;
// Un-dim background.
ApplyToBackground(b => b.FadeColour(OsuColour.Gray(0.5f), 150));
detachedPanel = null;
}
}
public bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
if (e.Repeat)
return false;
switch (e.Action)
{
case GlobalAction.Select:
statisticsPanel.ToggleVisibility();
return true;
}
return false;
}
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
}
protected class VerticalScrollContainer : OsuScrollContainer
{
protected override Container<Drawable> Content => content;
private readonly Container content;
public VerticalScrollContainer()
{
Masking = false;
base.Content.Add(content = new Container { RelativeSizeAxes = Axes.X });
}
protected override void Update()
{
base.Update();
content.Height = Math.Max(screen_height, DrawHeight);
}
}
}
}
| |
//
// 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.
//
#if !UNITY3D_WEB
using System.Security;
namespace NLog.Internal.FileAppenders
{
using System;
using System.IO;
using System.Runtime.InteropServices;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Time;
/// <summary>
/// Base class for optimized file appenders.
/// </summary>
[SecuritySafeCritical]
internal abstract class BaseFileAppender : IDisposable
{
private readonly Random random = new Random();
/// <summary>
/// Initializes a new instance of the <see cref="BaseFileAppender" /> class.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="createParameters">The create parameters.</param>
public BaseFileAppender(string fileName, ICreateFileParameters createParameters)
{
this.CreateFileParameters = createParameters;
this.FileName = fileName;
this.OpenTime = TimeSource.Current.Time.ToLocalTime();
this.LastWriteTime = DateTime.MinValue;
}
/// <summary>
/// Gets the name of the file.
/// </summary>
/// <value>The name of the file.</value>
public string FileName { get; private set; }
/// <summary>
/// Gets the last write time.
/// </summary>
/// <value>The last write time.</value>
public DateTime LastWriteTime { get; private set; }
/// <summary>
/// Gets the open time of the file.
/// </summary>
/// <value>The open time.</value>
public DateTime OpenTime { get; private set; }
/// <summary>
/// Gets the file creation parameters.
/// </summary>
/// <value>The file creation parameters.</value>
public ICreateFileParameters CreateFileParameters { get; private set; }
/// <summary>
/// Writes the specified bytes.
/// </summary>
/// <param name="bytes">The bytes.</param>
public abstract void Write(byte[] bytes);
/// <summary>
/// Flushes this instance.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this instance.
/// </summary>
public abstract void Close();
/// <summary>
/// Gets the file info.
/// </summary>
/// <param name="lastWriteTime">The last write time.</param>
/// <param name="fileLength">Length of the file.</param>
/// <returns>True if the operation succeeded, false otherwise.</returns>
public abstract bool GetFileInfo(out DateTime lastWriteTime, out long fileLength);
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.Close();
}
}
/// <summary>
/// Records the last write time for a file.
/// </summary>
protected void FileTouched()
{
this.LastWriteTime = TimeSource.Current.Time.ToLocalTime();
}
/// <summary>
/// Records the last write time for a file to be specific date.
/// </summary>
/// <param name="dateTime">Date and time when the last write occurred.</param>
protected void FileTouched(DateTime dateTime)
{
this.LastWriteTime = dateTime;
}
/// <summary>
/// Creates the file stream.
/// </summary>
/// <param name="allowConcurrentWrite">If set to <c>true</c> allow concurrent writes.</param>
/// <returns>A <see cref="FileStream"/> object which can be used to write to the file.</returns>
protected FileStream CreateFileStream(bool allowConcurrentWrite)
{
int currentDelay = this.CreateFileParameters.ConcurrentWriteAttemptDelay;
InternalLogger.Trace("Opening {0} with concurrentWrite={1}", this.FileName, allowConcurrentWrite);
for (int i = 0; i < this.CreateFileParameters.ConcurrentWriteAttempts; ++i)
{
try
{
try
{
return this.TryCreateFileStream(allowConcurrentWrite);
}
catch (DirectoryNotFoundException)
{
if (!this.CreateFileParameters.CreateDirs)
{
throw;
}
Directory.CreateDirectory(Path.GetDirectoryName(this.FileName));
return this.TryCreateFileStream(allowConcurrentWrite);
}
}
catch (IOException)
{
if (!this.CreateFileParameters.ConcurrentWrites || !allowConcurrentWrite || i + 1 == this.CreateFileParameters.ConcurrentWriteAttempts)
{
throw; // rethrow
}
int actualDelay = this.random.Next(currentDelay);
InternalLogger.Warn("Attempt #{0} to open {1} failed. Sleeping for {2}ms", i, this.FileName, actualDelay);
currentDelay *= 2;
System.Threading.Thread.Sleep(actualDelay);
}
}
throw new InvalidOperationException("Should not be reached.");
}
#if !SILVERLIGHT && !MONO
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Objects are disposed elsewhere")]
private FileStream WindowsCreateFile(string fileName, bool allowConcurrentWrite)
{
int fileShare = Win32FileNativeMethods.FILE_SHARE_READ;
if (allowConcurrentWrite)
{
fileShare |= Win32FileNativeMethods.FILE_SHARE_WRITE;
}
if (this.CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows)
{
fileShare |= Win32FileNativeMethods.FILE_SHARE_DELETE;
}
IntPtr handle = Win32FileNativeMethods.CreateFile(
fileName,
Win32FileNativeMethods.FileAccess.GenericWrite,
fileShare,
IntPtr.Zero,
Win32FileNativeMethods.CreationDisposition.OpenAlways,
this.CreateFileParameters.FileAttributes,
IntPtr.Zero);
if (handle.ToInt32() == -1)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
var safeHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(handle, true);
var returnValue = new FileStream(safeHandle, FileAccess.Write, this.CreateFileParameters.BufferSize);
returnValue.Seek(0, SeekOrigin.End);
return returnValue;
}
#endif
private FileStream TryCreateFileStream(bool allowConcurrentWrite)
{
FileShare fileShare = FileShare.Read;
if (allowConcurrentWrite)
{
fileShare = FileShare.ReadWrite;
}
if (this.CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows)
{
fileShare |= FileShare.Delete;
}
#if !SILVERLIGHT && !MONO
try
{
if (!this.CreateFileParameters.ForceManaged && PlatformDetector.IsDesktopWin32)
{
return this.WindowsCreateFile(this.FileName, allowConcurrentWrite);
}
}
catch (SecurityException)
{
InternalLogger.Debug("Could not use native Windows create file, falling back to managed filestream");
}
#endif
return new FileStream(
this.FileName,
FileMode.Append,
FileAccess.Write,
fileShare,
this.CreateFileParameters.BufferSize);
}
}
}
#endif
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Threading;
using System.Runtime.CompilerServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
//[ExtendClass(typeof(System.Threading.Thread), PlatformFilter = "ARM")]
[ExtendClass(typeof(System.Threading.Thread))]
public class ThreadImpl
{
//
// State
//
[TS.WellKnownField( "ThreadImpl_s_currentThread" )]
private static ThreadImpl s_currentThread;
private static int s_managedThreadId;
//--//
private int m_managedThreadId;
private bool m_fBackground;
[TS.WellKnownField( "ThreadImpl_m_currentException" )]
private Exception m_currentException;
private ThreadPriority m_priority;
private readonly ThreadStart m_start;
private uint[] m_stack;
private readonly Processor.Context m_swappedOutContext;
private readonly Processor.Context m_throwContext;
private volatile ThreadState m_state;
private readonly KernelNode< ThreadImpl > m_registrationLink;
private readonly KernelNode< ThreadImpl > m_schedulingLink;
private ManualResetEvent m_joinEvent;
private readonly KernelList< Synchronization.WaitableObject > m_ownedObjects;
private readonly KernelList< Synchronization.WaitingRecord > m_pendingObjects;
private KernelPerformanceCounter m_activeTime;
//
// HACK: We have a bug in the liveness of multi-pointer structure. We have to use a class instead.
//
internal Synchronization.WaitingRecord.Holder m_holder = new Synchronization.WaitingRecord.Holder();
//
// Constructor Methods
//
[DiscardTargetImplementation]
public ThreadImpl( System.Threading.ThreadStart start ) : this( start, new uint[1024] )
{
}
[DiscardTargetImplementation]
public ThreadImpl( System.Threading.ThreadStart start ,
uint[] stack )
{
m_managedThreadId = s_managedThreadId++;
m_start = start;
m_stack = stack;
m_swappedOutContext = Processor.Instance.AllocateProcessorContext();
m_throwContext = Processor.Instance.AllocateProcessorContext();
m_state = ThreadState.Unstarted;
m_registrationLink = new KernelNode< ThreadImpl >( this );
m_schedulingLink = new KernelNode< ThreadImpl >( this );
m_ownedObjects = new KernelList< Synchronization.WaitableObject >();
m_pendingObjects = new KernelList< Synchronization.WaitingRecord >();
m_priority = ThreadPriority.Normal;
ThreadStart entrypoint = Entrypoint;
m_swappedOutContext.PopulateFromDelegate( entrypoint, m_stack );
}
//--//
//
// Helper Methods
//
public void Start()
{
if((m_state & ThreadState.Unstarted) == 0)
{
#if EXCEPTION_STRINGS
throw new ThreadStateException( "Thread already started" );
#else
throw new ThreadStateException();
#endif
}
m_state &= ~ThreadState.Unstarted;
ThreadManager.Instance.AddThread( this );
}
public void Join()
{
Join( Timeout.Infinite );
}
public bool Join( int timeout )
{
return Join( TimeSpan.FromMilliseconds( timeout ) );
}
public bool Join( TimeSpan timeout )
{
if((m_state & ThreadState.Unstarted) != 0)
{
#if EXCEPTION_STRINGS
throw new ThreadStateException( "Thread not started" );
#else
throw new ThreadStateException();
#endif
}
if((m_state & ThreadState.Stopped) != 0)
{
return true;
}
ManualResetEvent joinEvent = m_joinEvent;
if(joinEvent == null)
{
joinEvent = new ManualResetEvent( false );
ManualResetEvent joinEventOld = Interlocked.CompareExchange( ref m_joinEvent, joinEvent, null );
if(joinEventOld != null)
{
joinEvent = joinEventOld;
}
}
//
// Recheck after the creation of the event, in case of a race condition.
//
if((m_state & ThreadState.Stopped) != 0)
{
return true;
}
return joinEvent.WaitOne( timeout, false );
}
public static void Sleep( int millisecondsTimeout )
{
ThreadManager.Instance.Sleep( (SchedulerTime)millisecondsTimeout );
}
public static void Sleep( TimeSpan timeout )
{
ThreadManager.Instance.Sleep( (SchedulerTime)timeout );
}
public static void BeginCriticalRegion()
{
}
public static void EndCriticalRegion()
{
}
//--//
public void SetupForExceptionHandling( uint mode )
{
m_swappedOutContext.SetupForExceptionHandling( mode );
}
[BottomOfCallStack()]
private void Entrypoint()
{
try
{
m_start();
}
catch
{
}
m_state |= ThreadState.StopRequested;
ThreadManager.Instance.RemoveThread( this );
}
//--//
public void ReleasedProcessor()
{
BugCheck.AssertInterruptsOff();
m_activeTime.Stop();
if((m_state & ThreadState.StopRequested) != 0)
{
Stop();
}
}
public void AcquiredProcessor()
{
BugCheck.AssertInterruptsOff();
m_activeTime.Start();
}
//--//
public void Yield()
{
ThreadManager.Instance.Yield();
}
public void RegisterWait( KernelNode< Synchronization.WaitingRecord > node )
{
BugCheck.AssertInterruptsOff();
SchedulerTime timeout = node.Target.Timeout;
if(timeout == SchedulerTime.MaxValue)
{
//
// No timeout, add at end.
//
m_pendingObjects.InsertAtTail( node );
}
else
{
//
// Insert in order.
//
KernelNode< Synchronization.WaitingRecord > node2 = m_pendingObjects.StartOfForwardWalk;
bool fInvalidateTimer = true;
while(node2.IsValidForForwardMove)
{
if(node2.Target.Timeout > timeout)
{
break;
}
node2 = node2.Next;
fInvalidateTimer = false;
}
node.InsertBefore( node2 );
if(fInvalidateTimer)
{
ThreadManager.Instance.InvalidateNextWaitTimer();
}
}
}
public void UnregisterWait( KernelNode< Synchronization.WaitingRecord > node )
{
BugCheck.AssertInterruptsOff();
node.RemoveFromList();
SchedulerTime timeout = node.Target.Timeout;
if(timeout != SchedulerTime.MaxValue)
{
ThreadManager.Instance.InvalidateNextWaitTimer();
}
}
public SchedulerTime GetFirstTimeout()
{
BugCheck.AssertInterruptsOff();
Synchronization.WaitingRecord wr = m_pendingObjects.FirstTarget();
return wr != null ? wr.Timeout : SchedulerTime.MaxValue;
}
public void ProcessWaitExpiration( SchedulerTime currentTime )
{
BugCheck.AssertInterruptsOff();
KernelNode< Synchronization.WaitingRecord > node = m_pendingObjects.StartOfForwardWalk;
bool fWakeup = false;
while(node.IsValidForForwardMove)
{
Synchronization.WaitingRecord wr = node.Target;
//
// The items are kept sorted, so we can stop at the first failure.
//
if(wr.Timeout > currentTime)
{
break;
}
else
{
KernelNode< Synchronization.WaitingRecord > nodeNext = node.Next;
wr.RequestFulfilled = false;
fWakeup = true;
node = nodeNext;
}
}
if(fWakeup)
{
Wakeup();
}
}
public void Wakeup()
{
ThreadManager.Instance.Wakeup( this );
}
//--//
public void AcquiredWaitableObject( Synchronization.WaitableObject waitableObject )
{
using(SmartHandles.InterruptState.Disable())
{
m_ownedObjects.InsertAtTail( waitableObject.OwnershipLink );
}
}
public void ReleasedWaitableObject( Synchronization.WaitableObject waitableObject )
{
using(SmartHandles.InterruptState.Disable())
{
waitableObject.OwnershipLink.RemoveFromList();
}
}
//--//
public void Stop()
{
ThreadManager.Instance.RetireThread( this );
m_state |= ThreadState.Stopped;
if(m_joinEvent != null)
{
m_joinEvent.Set();
}
}
public void Detach()
{
using(SmartHandles.InterruptState.Disable())
{
while(true)
{
Synchronization.WaitingRecord wr = m_pendingObjects.FirstTarget();
if(wr == null)
{
break;
}
wr.RequestFulfilled = false;
}
while(true)
{
Synchronization.WaitableObject wo = m_ownedObjects.FirstTarget();
if(wo == null)
{
break;
}
wo.Release();
}
m_schedulingLink .RemoveFromList();
m_registrationLink.RemoveFromList();
}
}
//--//
public bool IsAtSafePoint( Processor.Context ctx )
{
if(m_start == null)
{
//
// Interrupt threads don't have an entry point. They are always at a safe point with regard to the garbage collector.
//
return true;
}
if((m_state & ThreadState.Unstarted) != 0)
{
return true;
}
if((m_state & ThreadState.StopRequested) != 0)
{
return false;
}
ctx.Populate( this.SwappedOutContext );
while(true)
{
TS.CodeMap cm = TS.CodeMap.ResolveAddressToCodeMap( ctx.ProgramCounter );
BugCheck.Assert( cm != null, BugCheck.StopCode.UnwindFailure );
//
// TODO: Check to see if the method is marked as a NoGC one.
//
if(ctx.Unwind() == false)
{
return true;
}
}
}
//--//
[Inline]
public static SmartHandles.SwapCurrentThread SwapCurrentThread( ThreadImpl newThread )
{
return new SmartHandles.SwapCurrentThread( newThread );
}
[Inline]
public static SmartHandles.SwapCurrentThreadUnderInterrupt SwapCurrentThreadUnderInterrupt( ThreadImpl newThread )
{
return new SmartHandles.SwapCurrentThreadUnderInterrupt( newThread );
}
//--//
[NoInline]
[TS.WellKnownMethod( "ThreadImpl_GetCurrentException" )]
public static Exception GetCurrentException()
{
return ThreadImpl.CurrentThread.CurrentException;
}
//--//
[NoInline]
[TS.WellKnownMethod( "ThreadImpl_ThrowNullException" )]
internal static void ThrowNullException()
{
throw new NullReferenceException();
}
[NoInline]
[TS.WellKnownMethod( "ThreadImpl_ThrowIndexOutOfRangeException" )]
internal static void ThrowIndexOutOfRangeException()
{
throw new IndexOutOfRangeException();
}
[NoInline]
[TS.WellKnownMethod( "ThreadImpl_ThrowOverflowException" )]
internal static void ThrowOverflowException()
{
throw new OverflowException();
}
[NoInline]
[TS.WellKnownMethod( "ThreadImpl_ThrowNotImplementedException" )]
internal static void ThrowNotImplementedException()
{
throw new NotImplementedException();
}
//--//
//
// Access Methods
//
public int ManagedThreadId
{
get
{
return m_managedThreadId;
}
}
public bool IsBackground
{
get
{
return m_fBackground;
}
set
{
m_fBackground = value;
}
}
public ThreadPriority Priority
{
get
{
return m_priority;
}
set
{
m_priority = value;
}
}
public bool IsAlive
{
get
{
if((m_state & ThreadState.Unstarted) != 0)
{
return false;
}
if((m_state & ThreadState.Stopped) != 0)
{
return false;
}
return true;
}
}
public Processor.Context SwappedOutContext
{
get
{
return m_swappedOutContext;
}
}
public Processor.Context ThrowContext
{
get
{
return m_throwContext;
}
}
public KernelNode< ThreadImpl > RegistrationLink
{
get
{
return m_registrationLink;
}
}
public KernelNode< ThreadImpl > SchedulingLink
{
get
{
return m_schedulingLink;
}
}
public ThreadState State
{
get
{
return m_state;
}
set
{
m_state = value;
}
}
public bool IsWaiting
{
[Inline]
get
{
return (m_state & ThreadState.WaitSleepJoin) != 0;
}
}
public Exception CurrentException
{
get
{
return m_currentException;
}
set
{
m_currentException = value;
}
}
public KernelPerformanceCounter ActiveTime
{
get
{
return m_activeTime;
}
}
public static ThreadImpl CurrentThread
{
[Inline]
[TS.WellKnownMethod( "ThreadImpl_get_CurrentThread" )]
get
{
return s_currentThread;
}
[Inline]
set
{
s_currentThread = value;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
** Purpose: An array implementation of a generic stack.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
[DebuggerTypeProxy(typeof(StackDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Stack<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array; // Storage for stack elements. Do not rename (binary serialization)
private int _size; // Number of items in the stack. Do not rename (binary serialization)
private int _version; // Used to keep enumerator in sync w/ collection. Do not rename (binary serialization)
[NonSerialized]
private object _syncRoot;
private const int DefaultCapacity = 4;
public Stack()
{
_array = Array.Empty<T>();
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
public Stack(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
public Stack(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
_array = EnumerableHelpers.ToArray(collection, out _size);
}
public int Count
{
get { return _size; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the Stack.
public void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
}
_size = 0;
_version++;
}
public bool Contains(T item)
{
// Compare items using the default equality comparer
// PERF: Internally Array.LastIndexOf calls
// EqualityComparer<T>.Default.LastIndexOf, which
// is specialized for different types. This
// boosts performance since instead of making a
// virtual method call each iteration of the loop,
// via EqualityComparer<T>.Default.Equals, we
// only make one virtual call to EqualityComparer.LastIndexOf.
return _size != 0 && Array.LastIndexOf(_array, item, _size - 1) != -1;
}
// Copies the stack into an array.
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Debug.Assert(array != _array);
int srcIndex = 0;
int dstIndex = arrayIndex + _size;
while(srcIndex < _size)
{
array[--dstIndex] = _array[srcIndex++];
}
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
try
{
Array.Copy(_array, 0, array, arrayIndex, _size);
Array.Reverse(array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Returns an IEnumerator for this Stack.
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
Array.Resize(ref _array, _size);
_version++;
}
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
public T Peek()
{
if (_size == 0)
{
ThrowForEmptyStack();
}
return _array[_size - 1];
}
public bool TryPeek(out T result)
{
if (_size == 0)
{
result = default(T);
return false;
}
result = _array[_size - 1];
return true;
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
public T Pop()
{
if (_size == 0)
{
ThrowForEmptyStack();
}
_version++;
T item = _array[--_size];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
_array[_size] = default(T); // Free memory quicker.
}
return item;
}
public bool TryPop(out T result)
{
if (_size == 0)
{
result = default(T);
return false;
}
_version++;
result = _array[--_size];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
_array[_size] = default(T); // Free memory quicker.
}
return true;
}
// Pushes an item to the top of the stack.
public void Push(T item)
{
if (_size == _array.Length)
{
Array.Resize(ref _array, (_array.Length == 0) ? DefaultCapacity : 2 * _array.Length);
}
_array[_size++] = item;
_version++;
}
// Copies the Stack to an array, in the same order Pop would return the items.
public T[] ToArray()
{
if (_size == 0)
return Array.Empty<T>();
T[] objArray = new T[_size];
int i = 0;
while (i < _size)
{
objArray[i] = _array[_size - i - 1];
i++;
}
return objArray;
}
private void ThrowForEmptyStack()
{
Debug.Assert(_size == 0);
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private readonly Stack<T> _stack;
private readonly int _version;
private int _index;
private T _currentElement;
internal Enumerator(Stack<T> stack)
{
_stack = stack;
_version = stack._version;
_index = -2;
_currentElement = default(T);
}
public void Dispose()
{
_index = -1;
}
public bool MoveNext()
{
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
{ // First call to enumerator.
_index = _stack._size - 1;
retval = (_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
return retval;
}
if (_index == -1)
{ // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
else
_currentElement = default(T);
return retval;
}
public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement;
}
}
private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -2 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -2;
_currentElement = default(T);
}
}
}
}
| |
namespace android.telephony
{
[global::MonoJavaBridge.JavaClass()]
public partial class PhoneNumberUtils : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected PhoneNumberUtils(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static bool compare(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m0.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m0 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "compare", "(Ljava/lang/String;Ljava/lang/String;)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m1;
public static bool compare(android.content.Context arg0, java.lang.String arg1, java.lang.String arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m1.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m1 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "compare", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m2;
public static bool isISODigit(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m2.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m2 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isISODigit", "(C)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public static bool is12Key(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m3.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m3 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "is12Key", "(C)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public static bool isDialable(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m4.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m4 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isDialable", "(C)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public static bool isReallyDialable(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m5.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m5 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isReallyDialable", "(C)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public static bool isNonSeparator(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m6.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m6 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isNonSeparator", "(C)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public static bool isStartsPostDial(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m7.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m7 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isStartsPostDial", "(C)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
public static global::java.lang.String getNumberFromIntent(android.content.Intent arg0, android.content.Context arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m8.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m8 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "getNumberFromIntent", "(Landroid/content/Intent;Landroid/content/Context;)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m9;
public static global::java.lang.String extractNetworkPortion(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m9.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m9 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "extractNetworkPortion", "(Ljava/lang/String;)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m10;
public static global::java.lang.String stripSeparators(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m10.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m10 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "stripSeparators", "(Ljava/lang/String;)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m11;
public static global::java.lang.String extractPostDialPortion(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m11.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m11 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "extractPostDialPortion", "(Ljava/lang/String;)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m12;
public static global::java.lang.String toCallerIDMinMatch(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m12.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m12 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "toCallerIDMinMatch", "(Ljava/lang/String;)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m13;
public static global::java.lang.String getStrippedReversed(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m13.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m13 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "getStrippedReversed", "(Ljava/lang/String;)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m14;
public static global::java.lang.String stringFromStringAndTOA(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m14.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m14 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "stringFromStringAndTOA", "(Ljava/lang/String;I)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m15;
public static int toaFromString(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m15.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m15 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "toaFromString", "(Ljava/lang/String;)I");
return @__env.CallStaticIntMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
public static global::java.lang.String calledPartyBCDToString(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m16.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m16 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "calledPartyBCDToString", "([BII)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m17;
public static global::java.lang.String calledPartyBCDFragmentToString(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m17.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m17 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "calledPartyBCDFragmentToString", "([BII)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m18;
public static bool isWellFormedSmsAddress(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m18.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m18 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isWellFormedSmsAddress", "(Ljava/lang/String;)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m19;
public static bool isGlobalPhoneNumber(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m19.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m19 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isGlobalPhoneNumber", "(Ljava/lang/String;)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m20;
public static byte[] networkPortionToCalledPartyBCD(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m20.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m20 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "networkPortionToCalledPartyBCD", "(Ljava/lang/String;)[B");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[];
}
private static global::MonoJavaBridge.MethodId _m21;
public static byte[] networkPortionToCalledPartyBCDWithLength(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m21.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m21 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "networkPortionToCalledPartyBCDWithLength", "(Ljava/lang/String;)[B");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[];
}
private static global::MonoJavaBridge.MethodId _m22;
public static byte[] numberToCalledPartyBCD(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m22.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m22 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "numberToCalledPartyBCD", "(Ljava/lang/String;)[B");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[];
}
private static global::MonoJavaBridge.MethodId _m23;
public static global::java.lang.String formatNumber(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m23.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m23 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "formatNumber", "(Ljava/lang/String;)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m24;
public static void formatNumber(android.text.Editable arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m24.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m24 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "formatNumber", "(Landroid/text/Editable;I)V");
@__env.CallStaticVoidMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m25;
public static int getFormatTypeForLocale(java.util.Locale arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m25.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m25 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "getFormatTypeForLocale", "(Ljava/util/Locale;)I");
return @__env.CallStaticIntMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public static void formatNanpNumber(android.text.Editable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m26.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m26 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "formatNanpNumber", "(Landroid/text/Editable;)V");
@__env.CallStaticVoidMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m27;
public static void formatJapaneseNumber(android.text.Editable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m27.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m27 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "formatJapaneseNumber", "(Landroid/text/Editable;)V");
@__env.CallStaticVoidMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m28;
public static bool isEmergencyNumber(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m28.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m28 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isEmergencyNumber", "(Ljava/lang/String;)Z");
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
public static global::java.lang.String convertKeypadLettersToDigits(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m29.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m29 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "convertKeypadLettersToDigits", "(Ljava/lang/String;)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m30;
public PhoneNumberUtils() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.PhoneNumberUtils._m30.native == global::System.IntPtr.Zero)
global::android.telephony.PhoneNumberUtils._m30 = @__env.GetMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._m30);
Init(@__env, handle);
}
public static char PAUSE
{
get
{
return ',';
}
}
public static char WAIT
{
get
{
return ';';
}
}
public static char WILD
{
get
{
return 'N';
}
}
public static int TOA_International
{
get
{
return 145;
}
}
public static int TOA_Unknown
{
get
{
return 129;
}
}
public static int FORMAT_UNKNOWN
{
get
{
return 0;
}
}
public static int FORMAT_NANP
{
get
{
return 1;
}
}
public static int FORMAT_JAPAN
{
get
{
return 2;
}
}
static PhoneNumberUtils()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.telephony.PhoneNumberUtils.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/PhoneNumberUtils"));
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OrganizationService.cs">
// Copyright (c) 2014-present Andrea Di Giorgi
//
// 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>
// <author>Andrea Di Giorgi</author>
// <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Liferay.SDK.Service.V62.Organization
{
public class OrganizationService : ServiceBase
{
public OrganizationService(ISession session)
: base(session)
{
}
public async Task AddGroupOrganizationsAsync(long groupId, IEnumerable<long> organizationIds)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("organizationIds", organizationIds);
var _command = new JsonObject()
{
{ "/organization/add-group-organizations", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> AddOrganizationAsync(long parentOrganizationId, string name, string type, bool recursable, long regionId, long countryId, int statusId, string comments, bool site, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("name", name);
_parameters.Add("type", type);
_parameters.Add("recursable", recursable);
_parameters.Add("regionId", regionId);
_parameters.Add("countryId", countryId);
_parameters.Add("statusId", statusId);
_parameters.Add("comments", comments);
_parameters.Add("site", site);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/organization/add-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddOrganizationAsync(long parentOrganizationId, string name, string type, long regionId, long countryId, int statusId, string comments, bool site, IEnumerable<object> addresses, IEnumerable<object> emailAddresses, IEnumerable<object> orgLabors, IEnumerable<object> phones, IEnumerable<object> websites, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("name", name);
_parameters.Add("type", type);
_parameters.Add("regionId", regionId);
_parameters.Add("countryId", countryId);
_parameters.Add("statusId", statusId);
_parameters.Add("comments", comments);
_parameters.Add("site", site);
_parameters.Add("addresses", addresses);
_parameters.Add("emailAddresses", emailAddresses);
_parameters.Add("orgLabors", orgLabors);
_parameters.Add("phones", phones);
_parameters.Add("websites", websites);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/organization/add-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddOrganizationAsync(long parentOrganizationId, string name, string type, bool recursable, long regionId, long countryId, int statusId, string comments, bool site, IEnumerable<object> addresses, IEnumerable<object> emailAddresses, IEnumerable<object> orgLabors, IEnumerable<object> phones, IEnumerable<object> websites, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("name", name);
_parameters.Add("type", type);
_parameters.Add("recursable", recursable);
_parameters.Add("regionId", regionId);
_parameters.Add("countryId", countryId);
_parameters.Add("statusId", statusId);
_parameters.Add("comments", comments);
_parameters.Add("site", site);
_parameters.Add("addresses", addresses);
_parameters.Add("emailAddresses", emailAddresses);
_parameters.Add("orgLabors", orgLabors);
_parameters.Add("phones", phones);
_parameters.Add("websites", websites);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/organization/add-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddOrganizationAsync(long parentOrganizationId, string name, string type, long regionId, long countryId, int statusId, string comments, bool site, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("name", name);
_parameters.Add("type", type);
_parameters.Add("regionId", regionId);
_parameters.Add("countryId", countryId);
_parameters.Add("statusId", statusId);
_parameters.Add("comments", comments);
_parameters.Add("site", site);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/organization/add-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task AddPasswordPolicyOrganizationsAsync(long passwordPolicyId, IEnumerable<long> organizationIds)
{
var _parameters = new JsonObject();
_parameters.Add("passwordPolicyId", passwordPolicyId);
_parameters.Add("organizationIds", organizationIds);
var _command = new JsonObject()
{
{ "/organization/add-password-policy-organizations", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteLogoAsync(long organizationId)
{
var _parameters = new JsonObject();
_parameters.Add("organizationId", organizationId);
var _command = new JsonObject()
{
{ "/organization/delete-logo", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteOrganizationAsync(long organizationId)
{
var _parameters = new JsonObject();
_parameters.Add("organizationId", organizationId);
var _command = new JsonObject()
{
{ "/organization/delete-organization", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<IEnumerable<dynamic>> GetManageableOrganizationsAsync(string actionId, int max)
{
var _parameters = new JsonObject();
_parameters.Add("actionId", actionId);
_parameters.Add("max", max);
var _command = new JsonObject()
{
{ "/organization/get-manageable-organizations", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<dynamic> GetOrganizationAsync(long organizationId)
{
var _parameters = new JsonObject();
_parameters.Add("organizationId", organizationId);
var _command = new JsonObject()
{
{ "/organization/get-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<long> GetOrganizationIdAsync(long companyId, string name)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("name", name);
var _command = new JsonObject()
{
{ "/organization/get-organization-id", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<IEnumerable<dynamic>> GetOrganizationsAsync(long companyId, long parentOrganizationId)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("parentOrganizationId", parentOrganizationId);
var _command = new JsonObject()
{
{ "/organization/get-organizations", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetOrganizationsAsync(long companyId, long parentOrganizationId, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/organization/get-organizations", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> GetOrganizationsCountAsync(long companyId, long parentOrganizationId)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("parentOrganizationId", parentOrganizationId);
var _command = new JsonObject()
{
{ "/organization/get-organizations-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<IEnumerable<dynamic>> GetUserOrganizationsAsync(long userId)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
var _command = new JsonObject()
{
{ "/organization/get-user-organizations", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task SetGroupOrganizationsAsync(long groupId, IEnumerable<long> organizationIds)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("organizationIds", organizationIds);
var _command = new JsonObject()
{
{ "/organization/set-group-organizations", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnsetGroupOrganizationsAsync(long groupId, IEnumerable<long> organizationIds)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("organizationIds", organizationIds);
var _command = new JsonObject()
{
{ "/organization/unset-group-organizations", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnsetPasswordPolicyOrganizationsAsync(long passwordPolicyId, IEnumerable<long> organizationIds)
{
var _parameters = new JsonObject();
_parameters.Add("passwordPolicyId", passwordPolicyId);
_parameters.Add("organizationIds", organizationIds);
var _command = new JsonObject()
{
{ "/organization/unset-password-policy-organizations", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> UpdateOrganizationAsync(long organizationId, long parentOrganizationId, string name, string type, long regionId, long countryId, int statusId, string comments, bool site, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("organizationId", organizationId);
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("name", name);
_parameters.Add("type", type);
_parameters.Add("regionId", regionId);
_parameters.Add("countryId", countryId);
_parameters.Add("statusId", statusId);
_parameters.Add("comments", comments);
_parameters.Add("site", site);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/organization/update-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateOrganizationAsync(long organizationId, long parentOrganizationId, string name, string type, bool recursable, long regionId, long countryId, int statusId, string comments, bool site, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("organizationId", organizationId);
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("name", name);
_parameters.Add("type", type);
_parameters.Add("recursable", recursable);
_parameters.Add("regionId", regionId);
_parameters.Add("countryId", countryId);
_parameters.Add("statusId", statusId);
_parameters.Add("comments", comments);
_parameters.Add("site", site);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/organization/update-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateOrganizationAsync(long organizationId, long parentOrganizationId, string name, string type, long regionId, long countryId, int statusId, string comments, bool site, IEnumerable<object> addresses, IEnumerable<object> emailAddresses, IEnumerable<object> orgLabors, IEnumerable<object> phones, IEnumerable<object> websites, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("organizationId", organizationId);
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("name", name);
_parameters.Add("type", type);
_parameters.Add("regionId", regionId);
_parameters.Add("countryId", countryId);
_parameters.Add("statusId", statusId);
_parameters.Add("comments", comments);
_parameters.Add("site", site);
_parameters.Add("addresses", addresses);
_parameters.Add("emailAddresses", emailAddresses);
_parameters.Add("orgLabors", orgLabors);
_parameters.Add("phones", phones);
_parameters.Add("websites", websites);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/organization/update-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateOrganizationAsync(long organizationId, long parentOrganizationId, string name, string type, bool recursable, long regionId, long countryId, int statusId, string comments, bool site, IEnumerable<object> addresses, IEnumerable<object> emailAddresses, IEnumerable<object> orgLabors, IEnumerable<object> phones, IEnumerable<object> websites, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("organizationId", organizationId);
_parameters.Add("parentOrganizationId", parentOrganizationId);
_parameters.Add("name", name);
_parameters.Add("type", type);
_parameters.Add("recursable", recursable);
_parameters.Add("regionId", regionId);
_parameters.Add("countryId", countryId);
_parameters.Add("statusId", statusId);
_parameters.Add("comments", comments);
_parameters.Add("site", site);
_parameters.Add("addresses", addresses);
_parameters.Add("emailAddresses", emailAddresses);
_parameters.Add("orgLabors", orgLabors);
_parameters.Add("phones", phones);
_parameters.Add("websites", websites);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/organization/update-organization", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput;
using ChecksumIndexOutput = Lucene.Net.Store.ChecksumIndexOutput;
using Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using NoSuchDirectoryException = Lucene.Net.Store.NoSuchDirectoryException;
namespace Lucene.Net.Index
{
/// <summary> A collection of segmentInfo objects with methods for operating on
/// those segments in relation to the file system.
///
/// <p/><b>NOTE:</b> This API is new and still experimental
/// (subject to change suddenly in the next release)<p/>
/// </summary>
[Serializable]
public sealed class SegmentInfos:System.Collections.ArrayList
{
private class AnonymousClassFindSegmentsFile:FindSegmentsFile
{
private void InitBlock(SegmentInfos enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private SegmentInfos enclosingInstance;
public SegmentInfos Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal AnonymousClassFindSegmentsFile(SegmentInfos enclosingInstance, Lucene.Net.Store.Directory Param1):base(Param1)
{
InitBlock(enclosingInstance);
}
public /*protected internal*/ override System.Object DoBody(System.String segmentFileName)
{
Enclosing_Instance.Read(directory, segmentFileName);
return null;
}
}
/// <summary>The file format version, a negative number. </summary>
/* Works since counter, the old 1st entry, is always >= 0 */
public const int FORMAT = - 1;
/// <summary>This format adds details used for lockless commits. It differs
/// slightly from the previous format in that file names
/// are never re-used (write once). Instead, each file is
/// written to the next generation. For example,
/// segments_1, segments_2, etc. This allows us to not use
/// a commit lock. See <a
/// href="http://lucene.apache.org/java/docs/fileformats.html">file
/// formats</a> for details.
/// </summary>
public const int FORMAT_LOCKLESS = - 2;
/// <summary>This format adds a "hasSingleNormFile" flag into each segment info.
/// See <a href="http://issues.apache.org/jira/browse/LUCENE-756">LUCENE-756</a>
/// for details.
/// </summary>
public const int FORMAT_SINGLE_NORM_FILE = - 3;
/// <summary>This format allows multiple segments to share a single
/// vectors and stored fields file.
/// </summary>
public const int FORMAT_SHARED_DOC_STORE = - 4;
/// <summary>This format adds a checksum at the end of the file to
/// ensure all bytes were successfully written.
/// </summary>
public const int FORMAT_CHECKSUM = - 5;
/// <summary>This format adds the deletion count for each segment.
/// This way IndexWriter can efficiently report numDocs().
/// </summary>
public const int FORMAT_DEL_COUNT = - 6;
/// <summary>This format adds the boolean hasProx to record if any
/// fields in the segment store prox information (ie, have
/// omitTermFreqAndPositions==false)
/// </summary>
public const int FORMAT_HAS_PROX = - 7;
/// <summary>This format adds optional commit userData (String) storage. </summary>
public const int FORMAT_USER_DATA = - 8;
/// <summary>This format adds optional per-segment String
/// dianostics storage, and switches userData to Map
/// </summary>
public const int FORMAT_DIAGNOSTICS = - 9;
/* This must always point to the most recent file format. */
internal static readonly int CURRENT_FORMAT = FORMAT_DIAGNOSTICS;
public int counter = 0; // used to name new segments
/// <summary> counts how often the index has been changed by adding or deleting docs.
/// starting with the current time in milliseconds forces to create unique version numbers.
/// </summary>
private long version = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
private long generation = 0; // generation of the "segments_N" for the next commit
private long lastGeneration = 0; // generation of the "segments_N" file we last successfully read
// or wrote; this is normally the same as generation except if
// there was an IOException that had interrupted a commit
private System.Collections.Generic.IDictionary<string, string> userData = new System.Collections.Generic.Dictionary<string, string>(); // Opaque Map<String, String> that user can specify during IndexWriter.commit
/// <summary> If non-null, information about loading segments_N files</summary>
/// <seealso cref="setInfoStream">
/// </seealso>
private static System.IO.StreamWriter infoStream;
public SegmentInfo Info(int i)
{
return (SegmentInfo) this[i];
}
/// <summary> Get the generation (N) of the current segments_N file
/// from a list of files.
///
/// </summary>
/// <param name="files">-- array of file names to check
/// </param>
public static long GetCurrentSegmentGeneration(System.String[] files)
{
if (files == null)
{
return - 1;
}
long max = - 1;
for (int i = 0; i < files.Length; i++)
{
System.String file = files[i];
if (file.StartsWith(IndexFileNames.SEGMENTS) && !file.Equals(IndexFileNames.SEGMENTS_GEN))
{
long gen = GenerationFromSegmentsFileName(file);
if (gen > max)
{
max = gen;
}
}
}
return max;
}
/// <summary> Get the generation (N) of the current segments_N file
/// in the directory.
///
/// </summary>
/// <param name="directory">-- directory to search for the latest segments_N file
/// </param>
public static long GetCurrentSegmentGeneration(Directory directory)
{
try
{
return GetCurrentSegmentGeneration(directory.ListAll());
}
catch (NoSuchDirectoryException nsde)
{
return - 1;
}
}
/// <summary> Get the filename of the current segments_N file
/// from a list of files.
///
/// </summary>
/// <param name="files">-- array of file names to check
/// </param>
public static System.String GetCurrentSegmentFileName(System.String[] files)
{
return IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", GetCurrentSegmentGeneration(files));
}
/// <summary> Get the filename of the current segments_N file
/// in the directory.
///
/// </summary>
/// <param name="directory">-- directory to search for the latest segments_N file
/// </param>
public static System.String GetCurrentSegmentFileName(Directory directory)
{
return IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", GetCurrentSegmentGeneration(directory));
}
/// <summary> Get the segments_N filename in use by this segment infos.</summary>
public System.String GetCurrentSegmentFileName()
{
return IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", lastGeneration);
}
/// <summary> Parse the generation off the segments file name and
/// return it.
/// </summary>
public static long GenerationFromSegmentsFileName(System.String fileName)
{
if (fileName.Equals(IndexFileNames.SEGMENTS))
{
return 0;
}
else if (fileName.StartsWith(IndexFileNames.SEGMENTS))
{
return SupportClass.Number.ToInt64(fileName.Substring(1 + IndexFileNames.SEGMENTS.Length));
}
else
{
throw new System.ArgumentException("fileName \"" + fileName + "\" is not a segments file");
}
}
/// <summary> Get the next segments_N filename that will be written.</summary>
public System.String GetNextSegmentFileName()
{
long nextGeneration;
if (generation == - 1)
{
nextGeneration = 1;
}
else
{
nextGeneration = generation + 1;
}
return IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", nextGeneration);
}
/// <summary> Read a particular segmentFileName. Note that this may
/// throw an IOException if a commit is in process.
///
/// </summary>
/// <param name="directory">-- directory containing the segments file
/// </param>
/// <param name="segmentFileName">-- segment file to load
/// </param>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
public void Read(Directory directory, System.String segmentFileName)
{
bool success = false;
// Clear any previous segments:
Clear();
ChecksumIndexInput input = new ChecksumIndexInput(directory.OpenInput(segmentFileName));
generation = GenerationFromSegmentsFileName(segmentFileName);
lastGeneration = generation;
try
{
int format = input.ReadInt();
if (format < 0)
{
// file contains explicit format info
// check that it is a format we can understand
if (format < CURRENT_FORMAT)
throw new CorruptIndexException("Unknown format version: " + format);
version = input.ReadLong(); // read version
counter = input.ReadInt(); // read counter
}
else
{
// file is in old format without explicit format info
counter = format;
}
for (int i = input.ReadInt(); i > 0; i--)
{
// read segmentInfos
Add(new SegmentInfo(directory, format, input));
}
if (format >= 0)
{
// in old format the version number may be at the end of the file
if (input.GetFilePointer() >= input.Length())
version = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
// old file format without version number
else
version = input.ReadLong(); // read version
}
if (format <= FORMAT_USER_DATA)
{
if (format <= FORMAT_DIAGNOSTICS)
{
userData = input.ReadStringStringMap();
}
else if (0 != input.ReadByte())
{
userData = new System.Collections.Generic.Dictionary<string,string>();
userData.Add("userData", input.ReadString());
}
else
{
userData = new System.Collections.Generic.Dictionary<string, string>();
}
}
else
{
userData = new System.Collections.Generic.Dictionary<string, string>();
}
if (format <= FORMAT_CHECKSUM)
{
long checksumNow = input.GetChecksum();
long checksumThen = input.ReadLong();
if (checksumNow != checksumThen)
throw new CorruptIndexException("checksum mismatch in segments file");
}
success = true;
}
finally
{
input.Close();
if (!success)
{
// Clear any segment infos we had loaded so we
// have a clean slate on retry:
Clear();
}
}
}
/// <summary> This version of read uses the retry logic (for lock-less
/// commits) to find the right segments file to load.
/// </summary>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
public void Read(Directory directory)
{
generation = lastGeneration = - 1;
new AnonymousClassFindSegmentsFile(this, directory).Run();
}
// Only non-null after prepareCommit has been called and
// before finishCommit is called
internal ChecksumIndexOutput pendingSegnOutput;
private void Write(Directory directory)
{
System.String segmentFileName = GetNextSegmentFileName();
// Always advance the generation on write:
if (generation == - 1)
{
generation = 1;
}
else
{
generation++;
}
ChecksumIndexOutput segnOutput = new ChecksumIndexOutput(directory.CreateOutput(segmentFileName));
bool success = false;
try
{
segnOutput.WriteInt(CURRENT_FORMAT); // write FORMAT
segnOutput.WriteLong(++version); // every write changes
// the index
segnOutput.WriteInt(counter); // write counter
segnOutput.WriteInt(Count); // write infos
for (int i = 0; i < Count; i++)
{
Info(i).Write(segnOutput);
}
segnOutput.WriteStringStringMap(userData);
segnOutput.PrepareCommit();
success = true;
pendingSegnOutput = segnOutput;
}
finally
{
if (!success)
{
// We hit an exception above; try to close the file
// but suppress any exception:
try
{
segnOutput.Close();
}
catch (System.Exception t)
{
// Suppress so we keep throwing the original exception
}
try
{
// Try not to leave a truncated segments_N file in
// the index:
directory.DeleteFile(segmentFileName);
}
catch (System.Exception t)
{
// Suppress so we keep throwing the original exception
}
}
}
}
/// <summary> Returns a copy of this instance, also copying each
/// SegmentInfo.
/// </summary>
public override System.Object Clone()
{
SegmentInfos sis = new SegmentInfos();
for (int i = 0; i < this.Count; i++)
{
sis.Add(((SegmentInfo) this[i]).Clone());
}
sis.counter = this.counter;
sis.generation = this.generation;
sis.lastGeneration = this.lastGeneration;
// sis.pendingSegnOutput = this.pendingSegnOutput; // {{Aroush-2.9}} needed?
sis.userData = new System.Collections.Generic.Dictionary<string, string>(userData);
sis.version = this.version;
return sis;
}
/// <summary> version number when this SegmentInfos was generated.</summary>
public long GetVersion()
{
return version;
}
public long GetGeneration()
{
return generation;
}
public long GetLastGeneration()
{
return lastGeneration;
}
/// <summary> Current version number from segments file.</summary>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
public static long ReadCurrentVersion(Directory directory)
{
// Fully read the segments file: this ensures that it's
// completely written so that if
// IndexWriter.prepareCommit has been called (but not
// yet commit), then the reader will still see itself as
// current:
SegmentInfos sis = new SegmentInfos();
sis.Read(directory);
return sis.version;
//return (long) ((System.Int64) new AnonymousClassFindSegmentsFile1(directory).Run());
//DIGY: AnonymousClassFindSegmentsFile1 can safely be deleted
}
/// <summary> Returns userData from latest segments file</summary>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
public static System.Collections.Generic.IDictionary<string, string> ReadCurrentUserData(Directory directory)
{
SegmentInfos sis = new SegmentInfos();
sis.Read(directory);
return sis.GetUserData();
}
/// <summary>If non-null, information about retries when loading
/// the segments file will be printed to this.
/// </summary>
public static void SetInfoStream(System.IO.StreamWriter infoStream)
{
SegmentInfos.infoStream = infoStream;
}
/* Advanced configuration of retry logic in loading
segments_N file */
private static int defaultGenFileRetryCount = 10;
private static int defaultGenFileRetryPauseMsec = 50;
private static int defaultGenLookaheadCount = 10;
/// <summary> Advanced: set how many times to try loading the
/// segments.gen file contents to determine current segment
/// generation. This file is only referenced when the
/// primary method (listing the directory) fails.
/// </summary>
public static void SetDefaultGenFileRetryCount(int count)
{
defaultGenFileRetryCount = count;
}
/// <seealso cref="setDefaultGenFileRetryCount">
/// </seealso>
public static int GetDefaultGenFileRetryCount()
{
return defaultGenFileRetryCount;
}
/// <summary> Advanced: set how many milliseconds to pause in between
/// attempts to load the segments.gen file.
/// </summary>
public static void SetDefaultGenFileRetryPauseMsec(int msec)
{
defaultGenFileRetryPauseMsec = msec;
}
/// <seealso cref="setDefaultGenFileRetryPauseMsec">
/// </seealso>
public static int GetDefaultGenFileRetryPauseMsec()
{
return defaultGenFileRetryPauseMsec;
}
/// <summary> Advanced: set how many times to try incrementing the
/// gen when loading the segments file. This only runs if
/// the primary (listing directory) and secondary (opening
/// segments.gen file) methods fail to find the segments
/// file.
/// </summary>
public static void SetDefaultGenLookaheadCount(int count)
{
defaultGenLookaheadCount = count;
}
/// <seealso cref="setDefaultGenLookaheadCount">
/// </seealso>
public static int GetDefaultGenLookahedCount()
{
return defaultGenLookaheadCount;
}
/// <seealso cref="setInfoStream">
/// </seealso>
public static System.IO.StreamWriter GetInfoStream()
{
return infoStream;
}
private static void Message(System.String message)
{
if (infoStream != null)
{
infoStream.WriteLine("SIS [" + SupportClass.ThreadClass.Current().Name + "]: " + message);
}
}
/// <summary> Utility class for executing code that needs to do
/// something with the current segments file. This is
/// necessary with lock-less commits because from the time
/// you locate the current segments file name, until you
/// actually open it, read its contents, or check modified
/// time, etc., it could have been deleted due to a writer
/// commit finishing.
/// </summary>
public abstract class FindSegmentsFile
{
internal Directory directory;
public FindSegmentsFile(Directory directory)
{
this.directory = directory;
}
public System.Object Run()
{
return Run(null);
}
public System.Object Run(IndexCommit commit)
{
if (commit != null)
{
if (directory != commit.GetDirectory())
throw new System.IO.IOException("the specified commit does not match the specified Directory");
return DoBody(commit.GetSegmentsFileName());
}
System.String segmentFileName = null;
long lastGen = - 1;
long gen = 0;
int genLookaheadCount = 0;
System.IO.IOException exc = null;
bool retry = false;
int method = 0;
// Loop until we succeed in calling doBody() without
// hitting an IOException. An IOException most likely
// means a commit was in process and has finished, in
// the time it took us to load the now-old infos files
// (and segments files). It's also possible it's a
// true error (corrupt index). To distinguish these,
// on each retry we must see "forward progress" on
// which generation we are trying to load. If we
// don't, then the original error is real and we throw
// it.
// We have three methods for determining the current
// generation. We try the first two in parallel, and
// fall back to the third when necessary.
while (true)
{
if (0 == method)
{
// Method 1: list the directory and use the highest
// segments_N file. This method works well as long
// as there is no stale caching on the directory
// contents (NOTE: NFS clients often have such stale
// caching):
System.String[] files = null;
long genA = - 1;
files = directory.ListAll();
if (files != null)
genA = Lucene.Net.Index.SegmentInfos.GetCurrentSegmentGeneration(files);
Lucene.Net.Index.SegmentInfos.Message("directory listing genA=" + genA);
// Method 2: open segments.gen and read its
// contents. Then we take the larger of the two
// gens. This way, if either approach is hitting
// a stale cache (NFS) we have a better chance of
// getting the right generation.
long genB = - 1;
for (int i = 0; i < Lucene.Net.Index.SegmentInfos.defaultGenFileRetryCount; i++)
{
IndexInput genInput = null;
try
{
genInput = directory.OpenInput(IndexFileNames.SEGMENTS_GEN);
}
catch (System.IO.FileNotFoundException e)
{
Lucene.Net.Index.SegmentInfos.Message("segments.gen open: FileNotFoundException " + e);
break;
}
catch (System.IO.IOException e)
{
Lucene.Net.Index.SegmentInfos.Message("segments.gen open: IOException " + e);
}
if (genInput != null)
{
try
{
int version = genInput.ReadInt();
if (version == Lucene.Net.Index.SegmentInfos.FORMAT_LOCKLESS)
{
long gen0 = genInput.ReadLong();
long gen1 = genInput.ReadLong();
Lucene.Net.Index.SegmentInfos.Message("fallback check: " + gen0 + "; " + gen1);
if (gen0 == gen1)
{
// The file is consistent.
genB = gen0;
break;
}
}
}
catch (System.IO.IOException err2)
{
// will retry
}
finally
{
genInput.Close();
}
}
try
{
System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * Lucene.Net.Index.SegmentInfos.defaultGenFileRetryPauseMsec));
}
catch (System.Threading.ThreadInterruptedException ie)
{
// In 3.0 we will change this to throw
// InterruptedException instead
SupportClass.ThreadClass.Current().Interrupt();
throw new System.SystemException(ie.Message, ie);
}
}
Lucene.Net.Index.SegmentInfos.Message(IndexFileNames.SEGMENTS_GEN + " check: genB=" + genB);
// Pick the larger of the two gen's:
if (genA > genB)
gen = genA;
else
gen = genB;
if (gen == - 1)
{
// Neither approach found a generation
System.String s;
if (files != null)
{
s = "";
for (int i = 0; i < files.Length; i++)
s += (" " + files[i]);
}
else
s = " null";
throw new System.IO.FileNotFoundException("no segments* file found in " + directory + ": files:" + s);
}
}
// Third method (fallback if first & second methods
// are not reliable): since both directory cache and
// file contents cache seem to be stale, just
// advance the generation.
if (1 == method || (0 == method && lastGen == gen && retry))
{
method = 1;
if (genLookaheadCount < Lucene.Net.Index.SegmentInfos.defaultGenLookaheadCount)
{
gen++;
genLookaheadCount++;
Lucene.Net.Index.SegmentInfos.Message("look ahead increment gen to " + gen);
}
}
if (lastGen == gen)
{
// This means we're about to try the same
// segments_N last tried. This is allowed,
// exactly once, because writer could have been in
// the process of writing segments_N last time.
if (retry)
{
// OK, we've tried the same segments_N file
// twice in a row, so this must be a real
// error. We throw the original exception we
// got.
throw exc;
}
else
{
retry = true;
}
}
else if (0 == method)
{
// Segment file has advanced since our last loop, so
// reset retry:
retry = false;
}
lastGen = gen;
segmentFileName = IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen);
try
{
System.Object v = DoBody(segmentFileName);
Lucene.Net.Index.SegmentInfos.Message("success on " + segmentFileName);
return v;
}
catch (System.IO.IOException err)
{
// Save the original root cause:
if (exc == null)
{
exc = err;
}
Lucene.Net.Index.SegmentInfos.Message("primary Exception on '" + segmentFileName + "': " + err + "'; will retry: retry=" + retry + "; gen = " + gen);
if (!retry && gen > 1)
{
// This is our first time trying this segments
// file (because retry is false), and, there is
// possibly a segments_(N-1) (because gen > 1).
// So, check if the segments_(N-1) exists and
// try it if so:
System.String prevSegmentFileName = IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen - 1);
bool prevExists;
prevExists = directory.FileExists(prevSegmentFileName);
if (prevExists)
{
Lucene.Net.Index.SegmentInfos.Message("fallback to prior segment file '" + prevSegmentFileName + "'");
try
{
System.Object v = DoBody(prevSegmentFileName);
if (exc != null)
{
Lucene.Net.Index.SegmentInfos.Message("success on fallback " + prevSegmentFileName);
}
return v;
}
catch (System.IO.IOException err2)
{
Lucene.Net.Index.SegmentInfos.Message("secondary Exception on '" + prevSegmentFileName + "': " + err2 + "'; will retry");
}
}
}
}
}
}
/// <summary> Subclass must implement this. The assumption is an
/// IOException will be thrown if something goes wrong
/// during the processing that could have been caused by
/// a writer committing.
/// </summary>
public /*internal*/ abstract System.Object DoBody(System.String segmentFileName);
}
/// <summary> Returns a new SegmentInfos containg the SegmentInfo
/// instances in the specified range first (inclusive) to
/// last (exclusive), so total number of segments returned
/// is last-first.
/// </summary>
public SegmentInfos Range(int first, int last)
{
SegmentInfos infos = new SegmentInfos();
infos.AddRange((System.Collections.IList) ((System.Collections.ArrayList) this).GetRange(first, last - first));
return infos;
}
// Carry over generation numbers from another SegmentInfos
internal void UpdateGeneration(SegmentInfos other)
{
lastGeneration = other.lastGeneration;
generation = other.generation;
version = other.version;
}
internal void RollbackCommit(Directory dir)
{
if (pendingSegnOutput != null)
{
try
{
pendingSegnOutput.Close();
}
catch (System.Exception t)
{
// Suppress so we keep throwing the original exception
// in our caller
}
// Must carefully compute fileName from "generation"
// since lastGeneration isn't incremented:
try
{
System.String segmentFileName = IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", generation);
dir.DeleteFile(segmentFileName);
}
catch (System.Exception t)
{
// Suppress so we keep throwing the original exception
// in our caller
}
pendingSegnOutput = null;
}
}
/// <summary>Call this to start a commit. This writes the new
/// segments file, but writes an invalid checksum at the
/// end, so that it is not visible to readers. Once this
/// is called you must call {@link #finishCommit} to complete
/// the commit or {@link #rollbackCommit} to abort it.
/// </summary>
internal void PrepareCommit(Directory dir)
{
if (pendingSegnOutput != null)
throw new System.SystemException("prepareCommit was already called");
Write(dir);
}
/// <summary>Returns all file names referenced by SegmentInfo
/// instances matching the provided Directory (ie files
/// associated with any "external" segments are skipped).
/// The returned collection is recomputed on each
/// invocation.
/// </summary>
public System.Collections.Generic.ICollection<string> Files(Directory dir, bool includeSegmentsFile)
{
System.Collections.Generic.Dictionary<string, string> files = new System.Collections.Generic.Dictionary<string, string>();
if (includeSegmentsFile)
{
string tmp = GetCurrentSegmentFileName();
files.Add(tmp, tmp);
}
int size = Count;
for (int i = 0; i < size; i++)
{
SegmentInfo info = Info(i);
if (info.dir == dir)
{
SupportClass.CollectionsHelper.AddAllIfNotContains(files, Info(i).Files());
}
}
return files.Keys;
}
internal void FinishCommit(Directory dir)
{
if (pendingSegnOutput == null)
throw new System.SystemException("prepareCommit was not called");
bool success = false;
try
{
pendingSegnOutput.FinishCommit();
pendingSegnOutput.Close();
pendingSegnOutput = null;
success = true;
}
finally
{
if (!success)
RollbackCommit(dir);
}
// NOTE: if we crash here, we have left a segments_N
// file in the directory in a possibly corrupt state (if
// some bytes made it to stable storage and others
// didn't). But, the segments_N file includes checksum
// at the end, which should catch this case. So when a
// reader tries to read it, it will throw a
// CorruptIndexException, which should cause the retry
// logic in SegmentInfos to kick in and load the last
// good (previous) segments_N-1 file.
System.String fileName = IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", generation);
success = false;
try
{
dir.Sync(fileName);
success = true;
}
finally
{
if (!success)
{
try
{
dir.DeleteFile(fileName);
}
catch (System.Exception t)
{
// Suppress so we keep throwing the original exception
}
}
}
lastGeneration = generation;
try
{
IndexOutput genOutput = dir.CreateOutput(IndexFileNames.SEGMENTS_GEN);
try
{
genOutput.WriteInt(FORMAT_LOCKLESS);
genOutput.WriteLong(generation);
genOutput.WriteLong(generation);
}
finally
{
genOutput.Close();
}
}
catch (System.Exception t)
{
// It's OK if we fail to write this file since it's
// used only as one of the retry fallbacks.
}
}
/// <summary>Writes & syncs to the Directory dir, taking care to
/// remove the segments file on exception
/// </summary>
public /*internal*/ void Commit(Directory dir)
{
PrepareCommit(dir);
FinishCommit(dir);
}
public System.String SegString(Directory directory)
{
lock (this)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
int count = Count;
for (int i = 0; i < count; i++)
{
if (i > 0)
{
buffer.Append(' ');
}
SegmentInfo info = Info(i);
buffer.Append(info.SegString(directory));
if (info.dir != directory)
buffer.Append("**");
}
return buffer.ToString();
}
}
public System.Collections.Generic.IDictionary<string,string> GetUserData()
{
return userData;
}
internal void SetUserData(System.Collections.Generic.IDictionary<string, string> data)
{
if (data == null)
{
userData = new System.Collections.Generic.Dictionary<string,string>();
}
else
{
userData = data;
}
}
/// <summary>Replaces all segments in this instance, but keeps
/// generation, version, counter so that future commits
/// remain write once.
/// </summary>
internal void Replace(SegmentInfos other)
{
Clear();
AddRange(other);
lastGeneration = other.lastGeneration;
}
// Used only for testing
public bool HasExternalSegments(Directory dir)
{
int numSegments = Count;
for (int i = 0; i < numSegments; i++)
if (Info(i).dir != dir)
return true;
return false;
}
#region Lucene.NET (Equals & GetHashCode )
/// <summary>
/// Simple brute force implementation.
/// If size is equal, compare items one by one.
/// </summary>
/// <param name="obj">SegmentInfos object to check equality for</param>
/// <returns>true if lists are equal, false otherwise</returns>
public override bool Equals(object obj)
{
if (obj == null) return false;
SegmentInfos objToCompare = obj as SegmentInfos;
if (objToCompare == null) return false;
if (this.Count != objToCompare.Count) return false;
for (int idx = 0; idx < this.Count; idx++)
{
if (!this[idx].Equals(objToCompare[idx])) return false;
}
return true;
}
/// <summary>
/// Calculate hash code of SegmentInfos
/// </summary>
/// <returns>hash code as in java version of ArrayList</returns>
public override int GetHashCode()
{
int h = 1;
for (int i = 0; i < this.Count; i++)
{
SegmentInfo si = (this[i] as SegmentInfo);
h = 31 * h + (si == null ? 0 : si.GetHashCode());
}
return h;
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using HappyMapper.AutoMapper.ConfigurationAPI.Configuration;
using HappyMapper.AutoMapper.ConfigurationAPI.Configuration.Conventions;
using HappyMapper.AutoMapper.ConfigurationAPI.Mappers;
namespace HappyMapper.AutoMapper.ConfigurationAPI
{
using IMemberConfiguration = Configuration.Conventions.IMemberConfiguration;
/// <summary>
/// Provides a named configuration for maps. Naming conventions become scoped per profile.
/// </summary>
public abstract class Profile : IProfileExpression, IProfileConfiguration
{
private readonly ConditionalObjectMapper _mapMissingTypes = new ConditionalObjectMapper {Conventions = {tp => true}};
private readonly List<string> _globalIgnore = new List<string>();
private readonly List<Action<TypeMap, IMappingExpression>> _allTypeMapActions = new List<Action<TypeMap, IMappingExpression>>();
private readonly List<Action<PropertyMap, IMemberConfigurationExpression>> _allPropertyMapActions = new List<Action<PropertyMap, IMemberConfigurationExpression>>();
private readonly List<ITypeMapConfiguration> _typeMapConfigs = new List<ITypeMapConfiguration>();
private readonly List<ITypeMapConfiguration> _openTypeMapConfigs = new List<ITypeMapConfiguration>();
private readonly TypeMapFactory _typeMapFactory = new TypeMapFactory();
private readonly List<MethodInfo> _sourceExtensionMethods = new List<MethodInfo>();
private readonly IList<IMemberConfiguration> _memberConfigurations = new List<IMemberConfiguration>();
private readonly ConcurrentDictionary<Type, TypeDetails> _typeDetails = new ConcurrentDictionary<Type, TypeDetails>();
protected Profile(string profileName)
:this()
{
ProfileName = profileName;
}
protected Profile()
{
ProfileName = GetType().FullName;
IncludeSourceExtensionMethods(typeof(Enumerable));
_memberConfigurations.Add(new MemberConfiguration().AddMember<NameSplitMember>().AddName<PrePostfixName>(_ => _.AddStrings(p => p.Prefixes, "Get")));
}
[Obsolete("Create a constructor and configure inside of your profile's constructor instead. Will be removed in 6.0")]
protected virtual void Configure() { }
#pragma warning disable 618
internal void Initialize() => Configure();
#pragma warning restore 618
public virtual string ProfileName { get; }
public void DisableConstructorMapping()
{
ConstructorMappingEnabled = false;
}
public bool AllowNullDestinationValues { get; set; } = true;
public bool AllowNullCollections { get; set; }
public IEnumerable<string> GlobalIgnores => _globalIgnore;
public IEnumerable<string> Prefixes { get; private set; } = new string[0];
public IEnumerable<string> Postfixes { get; private set; } = new string[0];
public INamingConvention SourceMemberNamingConvention
{
get
{
INamingConvention convention = null;
DefaultMemberConfig.AddMember<NameSplitMember>(_ => convention = _.SourceMemberNamingConvention);
return convention;
}
set { DefaultMemberConfig.AddMember<NameSplitMember>(_ => _.SourceMemberNamingConvention = value); }
}
public INamingConvention DestinationMemberNamingConvention
{
get
{
INamingConvention convention = null;
DefaultMemberConfig.AddMember<NameSplitMember>(_ => convention = _.DestinationMemberNamingConvention);
return convention;
}
set { DefaultMemberConfig.AddMember<NameSplitMember>(_ => _.DestinationMemberNamingConvention = value); }
}
public bool CreateMissingTypeMaps
{
get
{
return _createMissingTypeMaps;
}
set
{
_createMissingTypeMaps = value;
if (value)
_typeConfigurations.Add(_mapMissingTypes);
else
_typeConfigurations.Remove(_mapMissingTypes);
}
}
public IEnumerable<Action<TypeMap, IMappingExpression>> AllTypeMapActions => _allTypeMapActions;
public IEnumerable<Action<PropertyMap, IMemberConfigurationExpression>> AllPropertyMapActions => _allPropertyMapActions;
public void ForAllMaps(Action<TypeMap, IMappingExpression> configuration)
{
_allTypeMapActions.Add(configuration);
}
public void ForAllPropertyMaps(Func<PropertyMap, bool> condition, Action<PropertyMap, IMemberConfigurationExpression> configuration)
{
_allPropertyMapActions.Add((pm, cfg) =>
{
if (condition(pm)) configuration(pm, cfg);
});
}
public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>()
where TSource : class, new() where TDestination : class, new()
{
return CreateMap<TSource, TDestination>(MemberList.Destination);
}
public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(MemberList memberList)
{
return CreateMappingExpression<TSource, TDestination>(memberList);
}
public IMappingExpression CreateMap(Type sourceType, Type destinationType)
{
return CreateMap(sourceType, destinationType, MemberList.Destination);
}
public IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList)
{
var map = new MappingExpression(new TypePair(sourceType, destinationType), memberList);
_typeMapConfigs.Add(map);
if (sourceType.IsGenericTypeDefinition() || destinationType.IsGenericTypeDefinition())
_openTypeMapConfigs.Add(map);
return map;
}
private IMappingExpression<TSource, TDestination> CreateMappingExpression<TSource, TDestination>(MemberList memberList)
{
var mappingExp = new MappingExpression<TSource, TDestination>(memberList);
_typeMapConfigs.Add(mappingExp);
return mappingExp;
}
public void ClearPrefixes()
{
DefaultMemberConfig.AddName<PrePostfixName>(_ => _.Prefixes.Clear());
}
public void RecognizeAlias(string original, string alias)
{
DefaultMemberConfig.AddName<ReplaceName>(_ => _.AddReplace(original, alias));
}
public void ReplaceMemberName(string original, string newValue)
{
DefaultMemberConfig.AddName<ReplaceName>(_ => _.AddReplace(original, newValue));
}
public void RecognizePrefixes(params string[] prefixes)
{
DefaultMemberConfig.AddName<PrePostfixName>(_ => _.AddStrings(p => p.Prefixes, prefixes));
}
public void RecognizePostfixes(params string[] postfixes)
{
DefaultMemberConfig.AddName<PrePostfixName>(_ => _.AddStrings(p => p.Postfixes, postfixes));
}
public void RecognizeDestinationPrefixes(params string[] prefixes)
{
DefaultMemberConfig.AddName<PrePostfixName>(_ => _.AddStrings(p => p.DestinationPrefixes, prefixes));
}
public void RecognizeDestinationPostfixes(params string[] postfixes)
{
DefaultMemberConfig.AddName<PrePostfixName>(_ => _.AddStrings(p => p.DestinationPostfixes, postfixes));
}
public void AddGlobalIgnore(string propertyNameStartingWith)
{
_globalIgnore.Add(propertyNameStartingWith);
}
public IMemberConfiguration DefaultMemberConfig => _memberConfigurations.First();
public IEnumerable<IMemberConfiguration> MemberConfigurations => _memberConfigurations;
public IMemberConfiguration AddMemberConfiguration()
{
var condition = new MemberConfiguration();
_memberConfigurations.Add(condition);
return condition;
}
private readonly IList<ConditionalObjectMapper> _typeConfigurations = new List<ConditionalObjectMapper>();
private bool _createMissingTypeMaps;
public IEnumerable<IConditionalObjectMapper> TypeConfigurations => _typeConfigurations;
public IConditionalObjectMapper AddConditionalObjectMapper()
{
var condition = new ConditionalObjectMapper();
_typeConfigurations.Add(condition);
return condition;
}
public bool ConstructorMappingEnabled { get; private set; } = true;
public IEnumerable<MethodInfo> SourceExtensionMethods => _sourceExtensionMethods;
public Func<PropertyInfo, bool> ShouldMapProperty { get; set; } = p => p.IsPublic();
public Func<FieldInfo, bool> ShouldMapField { get; set; } = f => f.IsPublic();
public void IncludeSourceExtensionMethods(Type type)
{
_sourceExtensionMethods.AddRange(type.GetDeclaredMethods().Where(m => m.IsStatic && m.IsDefined(typeof(ExtensionAttribute), false) && m.GetParameters().Length == 1));
}
void IProfileConfiguration.Register(TypeMapRegistry typeMapRegistry)
{
Prefixes =
MemberConfigurations
.Select(m => m.NameMapper)
.SelectMany(m => m.NamedMappers)
.OfType<PrePostfixName>()
.SelectMany(m => m.Prefixes)
.ToArray();
Postfixes =
MemberConfigurations
.Select(m => m.NameMapper)
.SelectMany(m => m.NamedMappers)
.OfType<PrePostfixName>()
.SelectMany(m => m.Postfixes)
.ToArray();
foreach (var config in _typeMapConfigs.Where(c => !c.IsOpenGeneric))
{
BuildTypeMap(typeMapRegistry, config);
if (config.ReverseTypeMap != null)
{
BuildTypeMap(typeMapRegistry, config.ReverseTypeMap);
}
}
}
void IProfileConfiguration.Configure(TypeMapRegistry typeMapRegistry)
{
foreach (var typeMap in _typeMapConfigs.Where(c => !c.IsOpenGeneric).Select(config => typeMapRegistry.GetTypeMap(config.Types)))
{
Configure(typeMapRegistry, typeMap);
}
}
TypeMap IProfileConfiguration.ConfigureConventionTypeMap(TypeMapRegistry typeMapRegistry, TypePair types)
{
if (! TypeConfigurations.Any(c => c.IsMatch(types)))
return null;
var typeMap = _typeMapFactory.CreateTypeMap(types.SourceType, types.DestinationType, this, MemberList.Destination);
var config = new MappingExpression(typeMap.TypePair, typeMap.ConfiguredMemberList);
config.Configure(this, typeMap);
Configure(typeMapRegistry, typeMap);
return typeMap;
}
TypeDetails IProfileConfiguration.CreateTypeDetails(Type type)
{
return _typeDetails.GetOrAdd(type, t => new TypeDetails(t, this));
}
TypeMap IProfileConfiguration.ConfigureClosedGenericTypeMap(TypeMapRegistry typeMapRegistry, TypePair closedTypes, TypePair requestedTypes)
{
var openMapConfig = _openTypeMapConfigs
//.Where(tm => tm.IsOpenGeneric)
.Where(tm =>
tm.Types.SourceType.GetGenericTypeDefinitionIfGeneric() == closedTypes.SourceType.GetGenericTypeDefinitionIfGeneric() &&
tm.Types.DestinationType.GetGenericTypeDefinitionIfGeneric() == closedTypes.DestinationType.GetGenericTypeDefinitionIfGeneric())
.OrderByDescending(tm => tm.DestinationType == closedTypes.DestinationType) // Favor more specific destination matches,
.ThenByDescending(tm => tm.SourceType == closedTypes.SourceType) // then more specific source matches
.FirstOrDefault();
if (openMapConfig == null)
return null;
var closedMap = _typeMapFactory.CreateTypeMap(requestedTypes.SourceType, requestedTypes.DestinationType, this, openMapConfig.MemberList);
openMapConfig.Configure(this, closedMap);
Configure(typeMapRegistry, closedMap);
if(closedMap.TypeConverterType != null)
{
var typeParams =
(openMapConfig.SourceType.IsGenericTypeDefinition() ? closedTypes.SourceType.GetGenericArguments() : new Type[0])
.Concat
(openMapConfig.DestinationType.IsGenericTypeDefinition() ? closedTypes.DestinationType.GetGenericArguments() : new Type[0]);
var neededParameters = closedMap.TypeConverterType.GetGenericParameters().Length;
closedMap.TypeConverterType = closedMap.TypeConverterType.MakeGenericType(typeParams.Take(neededParameters).ToArray());
}
if(closedMap.DestinationTypeOverride?.IsGenericTypeDefinition() == true)
{
var neededParameters = closedMap.DestinationTypeOverride.GetGenericParameters().Length;
closedMap.DestinationTypeOverride = closedMap.DestinationTypeOverride.MakeGenericType(closedTypes.DestinationType.GetGenericArguments().Take(neededParameters).ToArray());
}
return closedMap;
}
private void Configure(TypeMapRegistry typeMapRegistry, TypeMap typeMap)
{
foreach(var action in _allTypeMapActions)
{
var expression = new MappingExpression(typeMap.TypePair, typeMap.ConfiguredMemberList);
action(typeMap, expression);
expression.Configure(this, typeMap);
}
foreach (var action in _allPropertyMapActions)
{
foreach (var propertyMap in typeMap.GetPropertyMaps())
{
var memberExpression = new MappingExpression.MemberConfigurationExpression(propertyMap.DestMember, typeMap.SourceType);
action(propertyMap, memberExpression);
memberExpression.Configure(typeMap);
}
}
ApplyBaseMaps(typeMapRegistry, typeMap, typeMap);
ApplyDerivedMaps(typeMapRegistry, typeMap, typeMap);
}
private static void ApplyBaseMaps(TypeMapRegistry typeMapRegistry, TypeMap derivedMap, TypeMap currentMap)
{
foreach(var baseMap in currentMap.IncludedBaseTypes.Select(typeMapRegistry.GetTypeMap).Where(baseMap => baseMap != null))
{
baseMap.IncludeDerivedTypes(currentMap.SourceType, currentMap.DestinationType);
derivedMap.ApplyInheritedMap(baseMap);
ApplyBaseMaps(typeMapRegistry, derivedMap, baseMap);
}
}
private void ApplyDerivedMaps(TypeMapRegistry typeMapRegistry, TypeMap baseMap, TypeMap typeMap)
{
foreach (var inheritedTypeMap in typeMap.IncludedDerivedTypes.Select(typeMapRegistry.GetTypeMap).Where(map => map != null))
{
inheritedTypeMap.ApplyInheritedMap(baseMap);
ApplyDerivedMaps(typeMapRegistry, baseMap, inheritedTypeMap);
}
}
private void BuildTypeMap(TypeMapRegistry typeMapRegistry, ITypeMapConfiguration config)
{
var typeMap = _typeMapFactory.CreateTypeMap(config.SourceType, config.DestinationType, this, config.MemberList);
config.Configure(this, typeMap);
typeMapRegistry.RegisterTypeMap(typeMap);
}
}
}
| |
// 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.ServiceModel.Description;
using System.Globalization;
using System.Text;
namespace System.ServiceModel.Channels
{
internal struct ChannelRequirements
{
public bool usesInput;
public bool usesReply;
public bool usesOutput;
public bool usesRequest;
public SessionMode sessionMode;
public static void ComputeContractRequirements(ContractDescription contractDescription,
out ChannelRequirements requirements)
{
requirements = new ChannelRequirements();
requirements.usesInput = false;
requirements.usesReply = false;
requirements.usesOutput = false;
requirements.usesRequest = false;
requirements.sessionMode = contractDescription.SessionMode;
for (int i = 0; i < contractDescription.Operations.Count; i++)
{
OperationDescription operation = contractDescription.Operations[i];
bool oneWay = (operation.IsOneWay);
if (!operation.IsServerInitiated())
{
if (oneWay)
{
requirements.usesInput = true;
}
else
{
requirements.usesReply = true;
}
}
else
{
if (oneWay)
{
requirements.usesOutput = true;
}
else
{
requirements.usesRequest = true;
}
}
}
}
public static Type[] ComputeRequiredChannels(ref ChannelRequirements requirements)
{
if (requirements.usesOutput || requirements.usesRequest)
{
switch (requirements.sessionMode)
{
case SessionMode.Allowed:
return new Type[] {
typeof(IDuplexChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.Required:
return new Type[] {
typeof(IDuplexSessionChannel),
};
case SessionMode.NotAllowed:
return new Type[] {
typeof(IDuplexChannel),
};
}
}
else if (requirements.usesInput && requirements.usesReply)
{
switch (requirements.sessionMode)
{
case SessionMode.Allowed:
return new Type[] {
typeof(IRequestChannel),
typeof(IRequestSessionChannel),
typeof(IDuplexChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.Required:
return new Type[] {
typeof(IRequestSessionChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.NotAllowed:
return new Type[] {
typeof(IRequestChannel),
};
}
}
else if (requirements.usesInput)
{
switch (requirements.sessionMode)
{
case SessionMode.Allowed:
return new Type[] {
typeof(IOutputChannel),
typeof(IOutputSessionChannel),
typeof(IRequestChannel),
typeof(IRequestSessionChannel),
typeof(IDuplexChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.Required:
return new Type[] {
typeof(IOutputSessionChannel),
typeof(IRequestSessionChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.NotAllowed:
return new Type[] {
typeof(IOutputChannel),
typeof(IRequestChannel),
typeof(IDuplexChannel),
};
}
}
else if (requirements.usesReply)
{
switch (requirements.sessionMode)
{
case SessionMode.Allowed:
return new Type[] {
typeof(IRequestChannel),
typeof(IRequestSessionChannel),
typeof(IDuplexChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.Required:
return new Type[] {
typeof(IRequestSessionChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.NotAllowed:
return new Type[] {
typeof(IRequestChannel),
typeof(IDuplexChannel),
};
}
}
else
{
switch (requirements.sessionMode)
{
case SessionMode.Allowed:
return new Type[] {
typeof(IOutputSessionChannel),
typeof(IOutputChannel),
typeof(IRequestSessionChannel),
typeof(IRequestChannel),
typeof(IDuplexChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.Required:
return new Type[] {
typeof(IOutputSessionChannel),
typeof(IRequestSessionChannel),
typeof(IDuplexSessionChannel),
};
case SessionMode.NotAllowed:
return new Type[] {
typeof(IOutputChannel),
typeof(IRequestChannel),
typeof(IDuplexChannel),
};
}
}
return null;
}
public static bool IsSessionful(Type channelType)
{
return (channelType == typeof(IDuplexSessionChannel) ||
channelType == typeof(IOutputSessionChannel) ||
channelType == typeof(IInputSessionChannel) ||
channelType == typeof(IReplySessionChannel) ||
channelType == typeof(IRequestSessionChannel));
}
public static bool IsOneWay(Type channelType)
{
return (channelType == typeof(IOutputChannel) ||
channelType == typeof(IInputChannel) ||
channelType == typeof(IInputSessionChannel) ||
channelType == typeof(IOutputSessionChannel));
}
public static bool IsRequestReply(Type channelType)
{
return (channelType == typeof(IRequestChannel) ||
channelType == typeof(IReplyChannel) ||
channelType == typeof(IReplySessionChannel) ||
channelType == typeof(IRequestSessionChannel));
}
public static bool IsDuplex(Type channelType)
{
return (channelType == typeof(IDuplexChannel) ||
channelType == typeof(IDuplexSessionChannel));
}
public static Exception CantCreateListenerException(IEnumerable<Type> supportedChannels, IEnumerable<Type> requiredChannels, string bindingName)
{
string contractChannelTypesString = "";
string bindingChannelTypesString = "";
Exception exception = ChannelRequirements.BindingContractMismatchException(supportedChannels, requiredChannels, bindingName,
ref contractChannelTypesString, ref bindingChannelTypesString);
if (exception == null)
{
// none of the obvious speculations about the failure holds, so we fall back to the generic error message
exception = new InvalidOperationException(SR.Format(SR.EndpointListenerRequirementsCannotBeMetBy3,
bindingName, contractChannelTypesString, bindingChannelTypesString));
}
return exception;
}
public static Exception CantCreateChannelException(IEnumerable<Type> supportedChannels, IEnumerable<Type> requiredChannels, string bindingName)
{
string contractChannelTypesString = "";
string bindingChannelTypesString = "";
Exception exception = ChannelRequirements.BindingContractMismatchException(supportedChannels, requiredChannels, bindingName,
ref contractChannelTypesString, ref bindingChannelTypesString);
if (exception == null)
{
// none of the obvious speculations about the failure holds, so we fall back to the generic error message
exception = new InvalidOperationException(SR.Format(SR.CouldnTCreateChannelForType2, bindingName, contractChannelTypesString));
}
return exception;
}
public static Exception BindingContractMismatchException(IEnumerable<Type> supportedChannels, IEnumerable<Type> requiredChannels,
string bindingName, ref string contractChannelTypesString, ref string bindingChannelTypesString)
{
StringBuilder contractChannelTypes = new StringBuilder();
bool contractRequiresOneWay = true;
bool contractRequiresRequestReply = true;
bool contractRequiresDuplex = true;
bool contractRequiresTwoWay = true; // request-reply or duplex
bool contractRequiresSession = true;
bool contractRequiresDatagram = true;
foreach (Type channelType in requiredChannels)
{
if (contractChannelTypes.Length > 0)
{
contractChannelTypes.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator);
contractChannelTypes.Append(" ");
}
string typeString = channelType.ToString();
contractChannelTypes.Append(typeString.Substring(typeString.LastIndexOf('.') + 1));
if (!ChannelRequirements.IsOneWay(channelType))
{
contractRequiresOneWay = false;
}
if (!ChannelRequirements.IsRequestReply(channelType))
{
contractRequiresRequestReply = false;
}
if (!ChannelRequirements.IsDuplex(channelType))
{
contractRequiresDuplex = false;
}
if (!(ChannelRequirements.IsRequestReply(channelType) || ChannelRequirements.IsDuplex(channelType)))
{
contractRequiresTwoWay = false;
}
if (!ChannelRequirements.IsSessionful(channelType))
{
contractRequiresSession = false;
}
else
{
contractRequiresDatagram = false;
}
}
StringBuilder bindingChannelTypes = new StringBuilder();
bool bindingSupportsOneWay = false;
bool bindingSupportsRequestReply = false;
bool bindingSupportsDuplex = false;
bool bindingSupportsSession = false;
bool bindingSupportsDatagram = false;
bool bindingSupportsAtLeastOneChannelType = false;
foreach (Type channelType in supportedChannels)
{
bindingSupportsAtLeastOneChannelType = true;
if (bindingChannelTypes.Length > 0)
{
bindingChannelTypes.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator);
bindingChannelTypes.Append(" ");
}
string typeString = channelType.ToString();
bindingChannelTypes.Append(typeString.Substring(typeString.LastIndexOf('.') + 1));
if (ChannelRequirements.IsOneWay(channelType))
{
bindingSupportsOneWay = true;
}
if (ChannelRequirements.IsRequestReply(channelType))
{
bindingSupportsRequestReply = true;
}
if (ChannelRequirements.IsDuplex(channelType))
{
bindingSupportsDuplex = true;
}
if (ChannelRequirements.IsSessionful(channelType))
{
bindingSupportsSession = true;
}
else
{
bindingSupportsDatagram = true;
}
}
bool bindingSupportsTwoWay = bindingSupportsRequestReply || bindingSupportsDuplex;
if (!bindingSupportsAtLeastOneChannelType)
{
return new InvalidOperationException(SR.Format(SR.BindingDoesnTSupportAnyChannelTypes1, bindingName));
}
if (contractRequiresSession && !bindingSupportsSession)
{
return new InvalidOperationException(SR.Format(SR.BindingDoesnTSupportSessionButContractRequires1, bindingName));
}
if (contractRequiresDatagram && !bindingSupportsDatagram)
{
return new InvalidOperationException(SR.Format(SR.BindingDoesntSupportDatagramButContractRequires, bindingName));
}
if (contractRequiresDuplex && !bindingSupportsDuplex)
{
return new InvalidOperationException(SR.Format(SR.BindingDoesnTSupportDuplexButContractRequires1, bindingName));
}
if (contractRequiresRequestReply && !bindingSupportsRequestReply)
{
return new InvalidOperationException(SR.Format(SR.BindingDoesnTSupportRequestReplyButContract1, bindingName));
}
if (contractRequiresOneWay && !bindingSupportsOneWay)
{
return new InvalidOperationException(SR.Format(SR.BindingDoesnTSupportOneWayButContractRequires1, bindingName));
}
if (contractRequiresTwoWay && !bindingSupportsTwoWay)
{
return new InvalidOperationException(SR.Format(SR.BindingDoesnTSupportTwoWayButContractRequires1, bindingName));
}
contractChannelTypesString = contractChannelTypes.ToString();
bindingChannelTypesString = bindingChannelTypes.ToString();
return null;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Runtime.Serialization;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Xml;
using System.ServiceModel;
using System.Collections;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Runtime.CompilerServices;
[TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
public sealed class DataContractJsonSerializer : XmlObjectSerializer
{
internal IList<Type> knownTypeList;
internal DataContractDictionary knownDataContracts;
EmitTypeInformation emitTypeInformation;
IDataContractSurrogate dataContractSurrogate;
bool ignoreExtensionDataObject;
ReadOnlyCollection<Type> knownTypeCollection;
int maxItemsInObjectGraph;
DataContract rootContract; // post-surrogate
XmlDictionaryString rootName;
bool rootNameRequiresMapping;
Type rootType;
bool serializeReadOnlyTypes;
DateTimeFormat dateTimeFormat;
bool useSimpleDictionaryFormat;
public DataContractJsonSerializer(Type type)
: this(type, (IEnumerable<Type>)null)
{
}
public DataContractJsonSerializer(Type type, string rootName)
: this(type, rootName, null)
{
}
public DataContractJsonSerializer(Type type, XmlDictionaryString rootName)
: this(type, rootName, null)
{
}
public DataContractJsonSerializer(Type type, IEnumerable<Type> knownTypes)
: this(type, knownTypes, int.MaxValue, false, null, false)
{
}
public DataContractJsonSerializer(Type type, string rootName, IEnumerable<Type> knownTypes)
: this(type, rootName, knownTypes, int.MaxValue, false, null, false)
{
}
public DataContractJsonSerializer(Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes)
: this(type, rootName, knownTypes, int.MaxValue, false, null, false)
{
}
public DataContractJsonSerializer(Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
IDataContractSurrogate dataContractSurrogate,
bool alwaysEmitTypeInformation)
{
EmitTypeInformation emitTypeInformation = alwaysEmitTypeInformation ? EmitTypeInformation.Always : EmitTypeInformation.AsNeeded;
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, emitTypeInformation, false, null, false);
}
public DataContractJsonSerializer(Type type, string rootName,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
IDataContractSurrogate dataContractSurrogate,
bool alwaysEmitTypeInformation)
{
EmitTypeInformation emitTypeInformation = alwaysEmitTypeInformation ? EmitTypeInformation.Always : EmitTypeInformation.AsNeeded;
XmlDictionary dictionary = new XmlDictionary(2);
Initialize(type, dictionary.Add(rootName), knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, emitTypeInformation, false, null, false);
}
public DataContractJsonSerializer(Type type, XmlDictionaryString rootName,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
IDataContractSurrogate dataContractSurrogate,
bool alwaysEmitTypeInformation)
{
EmitTypeInformation emitTypeInformation = alwaysEmitTypeInformation ? EmitTypeInformation.Always : EmitTypeInformation.AsNeeded;
Initialize(type, rootName, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, emitTypeInformation, false, null, false);
}
public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings)
{
if (settings == null)
{
settings = new DataContractJsonSerializerSettings();
}
XmlDictionaryString rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName);
Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.DataContractSurrogate,
settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat);
}
public IDataContractSurrogate DataContractSurrogate
{
get { return dataContractSurrogate; }
}
public bool IgnoreExtensionDataObject
{
get { return ignoreExtensionDataObject; }
}
public ReadOnlyCollection<Type> KnownTypes
{
get
{
if (knownTypeCollection == null)
{
if (knownTypeList != null)
{
knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList);
}
else
{
knownTypeCollection = new ReadOnlyCollection<Type>(Globals.EmptyTypeArray);
}
}
return knownTypeCollection;
}
}
internal override DataContractDictionary KnownDataContracts
{
get
{
if (this.knownDataContracts == null && this.knownTypeList != null)
{
// This assignment may be performed concurrently and thus is a race condition.
// It's safe, however, because at worse a new (and identical) dictionary of
// data contracts will be created and re-assigned to this field. Introduction
// of a lock here could lead to deadlocks.
this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList);
}
return this.knownDataContracts;
}
}
public int MaxItemsInObjectGraph
{
get { return maxItemsInObjectGraph; }
}
internal bool AlwaysEmitTypeInformation
{
get
{
return emitTypeInformation == EmitTypeInformation.Always;
}
}
public EmitTypeInformation EmitTypeInformation
{
get
{
return emitTypeInformation;
}
}
public bool SerializeReadOnlyTypes
{
get
{
return serializeReadOnlyTypes;
}
}
public DateTimeFormat DateTimeFormat
{
get
{
return dateTimeFormat;
}
}
public bool UseSimpleDictionaryFormat
{
get
{
return useSimpleDictionaryFormat;
}
}
DataContract RootContract
{
get
{
if (rootContract == null)
{
rootContract = DataContract.GetDataContract(((dataContractSurrogate == null) ? rootType :
DataContractSerializer.GetSurrogatedType(dataContractSurrogate, rootType)));
CheckIfTypeIsReference(rootContract);
}
return rootContract;
}
}
XmlDictionaryString RootName
{
get
{
return rootName ?? JsonGlobals.rootDictionaryString;
}
}
public override bool IsStartObject(XmlReader reader)
{
// No need to pass in DateTimeFormat to JsonReaderDelegator: no DateTimes will be read in IsStartObject
return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader));
}
public override bool IsStartObject(XmlDictionaryReader reader)
{
// No need to pass in DateTimeFormat to JsonReaderDelegator: no DateTimes will be read in IsStartObject
return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader));
}
public override object ReadObject(Stream stream)
{
CheckNull(stream, "stream");
return ReadObject(JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max));
}
public override object ReadObject(XmlReader reader)
{
return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true);
}
public override object ReadObject(XmlReader reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName);
}
public override object ReadObject(XmlDictionaryReader reader)
{
return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true); // verifyObjectName
}
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName);
}
public override void WriteEndObject(XmlWriter writer)
{
// No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in end object
WriteEndObjectHandleExceptions(new JsonWriterDelegator(writer));
}
public override void WriteEndObject(XmlDictionaryWriter writer)
{
// No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in end object
WriteEndObjectHandleExceptions(new JsonWriterDelegator(writer));
}
public override void WriteObject(Stream stream, object graph)
{
CheckNull(stream, "stream");
XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, false); // ownsStream
WriteObject(jsonWriter, graph);
jsonWriter.Flush();
}
public override void WriteObject(XmlWriter writer, object graph)
{
WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph);
}
public override void WriteObject(XmlDictionaryWriter writer, object graph)
{
WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph);
}
public override void WriteObjectContent(XmlWriter writer, object graph)
{
WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph);
}
public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph);
}
public override void WriteStartObject(XmlWriter writer, object graph)
{
// No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object
WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph);
}
public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
{
// No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object
WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph);
}
internal static bool CheckIfJsonNameRequiresMapping(string jsonName)
{
if (jsonName != null)
{
if (!DataContract.IsValidNCName(jsonName))
{
return true;
}
for (int i = 0; i < jsonName.Length; i++)
{
if (XmlJsonWriter.CharacterNeedsEscaping(jsonName[i]))
{
return true;
}
}
}
return false;
}
internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName)
{
return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value);
}
internal static bool CheckIfXmlNameRequiresMapping(string xmlName)
{
return (xmlName == null) ? false : CheckIfJsonNameRequiresMapping(ConvertXmlNameToJsonName(xmlName));
}
internal static bool CheckIfXmlNameRequiresMapping(XmlDictionaryString xmlName)
{
return (xmlName == null) ? false : CheckIfXmlNameRequiresMapping(xmlName.Value);
}
internal static string ConvertXmlNameToJsonName(string xmlName)
{
return XmlConvert.DecodeName(xmlName);
}
internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName)
{
return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value));
}
internal static bool IsJsonLocalName(XmlReaderDelegator reader, string elementName)
{
string name;
if (XmlObjectSerializerReadContextComplexJson.TryGetJsonLocalName(reader, out name))
{
return (elementName == name);
}
return false;
}
internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
{
return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context);
}
internal static void WriteJsonNull(XmlWriterDelegator writer)
{
writer.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.nullString); // prefix // namespace
}
internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
contract.WriteJsonValue(writer, graph, context, declaredTypeHandle);
}
internal override Type GetDeserializeType()
{
return rootType;
}
internal override Type GetSerializeType(object graph)
{
return (graph == null) ? rootType : graph.GetType();
}
internal override bool InternalIsStartObject(XmlReaderDelegator reader)
{
if (IsRootElement(reader, RootContract, RootName, XmlDictionaryString.Empty))
{
return true;
}
return IsJsonLocalName(reader, RootName.Value);
}
internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName)
{
if (MaxItemsInObjectGraph == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
}
if (verifyObjectName)
{
if (!InternalIsStartObject(xmlReader))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.ExpectingElement, XmlDictionaryString.Empty, RootName), xmlReader));
}
}
else if (!IsStartElement(xmlReader))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader));
}
DataContract contract = RootContract;
if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, rootType))// handle Nullable<T> differently
{
return DataContractJsonSerializer.ReadJsonValue(contract, xmlReader, null);
}
XmlObjectSerializerReadContextComplexJson context = XmlObjectSerializerReadContextComplexJson.CreateContext(this, contract);
return context.InternalDeserialize(xmlReader, rootType, contract, null, null);
}
internal override void InternalWriteEndObject(XmlWriterDelegator writer)
{
writer.WriteEndElement();
}
internal override void InternalWriteObject(XmlWriterDelegator writer, object graph)
{
InternalWriteStartObject(writer, graph);
InternalWriteObjectContent(writer, graph);
InternalWriteEndObject(writer);
}
internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
{
if (MaxItemsInObjectGraph == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
}
DataContract contract = RootContract;
Type declaredType = contract.UnderlyingType;
Type graphType = (graph == null) ? declaredType : graph.GetType();
if (dataContractSurrogate != null)
{
graph = DataContractSerializer.SurrogateToDataContractType(dataContractSurrogate, graph, declaredType, ref graphType);
}
if (graph == null)
{
WriteJsonNull(writer);
}
else
{
if (declaredType == graphType)
{
if (contract.CanContainReferences)
{
XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, contract);
context.OnHandleReference(writer, graph, true); // canContainReferences
context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
}
else
{
DataContractJsonSerializer.WriteJsonValue(JsonDataContract.GetJsonDataContract(contract), writer, graph, null, declaredType.TypeHandle); // XmlObjectSerializerWriteContextComplexJson
}
}
else
{
XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, RootContract);
contract = DataContractJsonSerializer.GetDataContract(contract, declaredType, graphType);
if (contract.CanContainReferences)
{
context.OnHandleReference(writer, graph, true); // canContainCyclicReference
context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType);
}
else
{
context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
}
}
}
}
internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph)
{
if (this.rootNameRequiresMapping)
{
writer.WriteStartElement("a", JsonGlobals.itemString, JsonGlobals.itemString);
writer.WriteAttributeString(null, JsonGlobals.itemString, null, RootName.Value);
}
else
{
writer.WriteStartElement(RootName, XmlDictionaryString.Empty);
}
}
void AddCollectionItemTypeToKnownTypes(Type knownType)
{
Type itemType;
Type typeToCheck = knownType;
while (CollectionDataContract.IsCollection(typeToCheck, out itemType))
{
if (itemType.IsGenericType && (itemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue))
{
itemType = Globals.TypeOfKeyValuePair.MakeGenericType(itemType.GetGenericArguments());
}
this.knownTypeList.Add(itemType);
typeToCheck = itemType;
}
}
void Initialize(Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
IDataContractSurrogate dataContractSurrogate,
EmitTypeInformation emitTypeInformation,
bool serializeReadOnlyTypes,
DateTimeFormat dateTimeFormat,
bool useSimpleDictionaryFormat)
{
CheckNull(type, "type");
this.rootType = type;
if (knownTypes != null)
{
this.knownTypeList = new List<Type>();
foreach (Type knownType in knownTypes)
{
this.knownTypeList.Add(knownType);
if (knownType != null)
{
AddCollectionItemTypeToKnownTypes(knownType);
}
}
}
if (maxItemsInObjectGraph < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.ValueMustBeNonNegative)));
}
this.maxItemsInObjectGraph = maxItemsInObjectGraph;
this.ignoreExtensionDataObject = ignoreExtensionDataObject;
this.dataContractSurrogate = dataContractSurrogate;
this.emitTypeInformation = emitTypeInformation;
this.serializeReadOnlyTypes = serializeReadOnlyTypes;
this.dateTimeFormat = dateTimeFormat;
this.useSimpleDictionaryFormat = useSimpleDictionaryFormat;
}
void Initialize(Type type,
XmlDictionaryString rootName,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
IDataContractSurrogate dataContractSurrogate,
EmitTypeInformation emitTypeInformation,
bool serializeReadOnlyTypes,
DateTimeFormat dateTimeFormat,
bool useSimpleDictionaryFormat)
{
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, emitTypeInformation, serializeReadOnlyTypes, dateTimeFormat, useSimpleDictionaryFormat);
this.rootName = ConvertXmlNameToJsonName(rootName);
this.rootNameRequiresMapping = CheckIfJsonNameRequiresMapping(this.rootName);
}
internal static void CheckIfTypeIsReference(DataContract dataContract)
{
if (dataContract.IsReference)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
XmlObjectSerializer.CreateSerializationException(SR.GetString(
SR.JsonUnsupportedForIsReference,
DataContract.GetClrTypeFullName(dataContract.UnderlyingType),
dataContract.IsReference)));
}
}
internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType)
{
DataContract contract = DataContractSerializer.GetDataContract(declaredTypeContract, declaredType, objectType);
CheckIfTypeIsReference(contract);
return contract;
}
}
}
| |
// 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.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.GoToDefinition;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices
{
[Export(typeof(VisualStudioWorkspace))]
[Export(typeof(VisualStudioWorkspaceImpl))]
internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl
{
private readonly IEnumerable<Lazy<INavigableItemsPresenter>> _navigableItemsPresenters;
private readonly IEnumerable<Lazy<IReferencedSymbolsPresenter>> _referencedSymbolsPresenters;
[ImportingConstructor]
private RoslynVisualStudioWorkspace(
SVsServiceProvider serviceProvider,
SaveEventsService saveEventsService,
[ImportMany] IEnumerable<Lazy<INavigableItemsPresenter>> navigableItemsPresenters,
[ImportMany] IEnumerable<Lazy<IReferencedSymbolsPresenter>> referencedSymbolsPresenters)
: base(
serviceProvider,
backgroundWork: WorkspaceBackgroundWork.ParseAndCompile)
{
PrimaryWorkspace.Register(this);
InitializeStandardVisualStudioWorkspace(serviceProvider, saveEventsService);
_navigableItemsPresenters = navigableItemsPresenters;
_referencedSymbolsPresenters = referencedSymbolsPresenters;
}
public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
var project = ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
throw new ArgumentException(ServicesVSResources.DocumentIdNotFromWorkspace, "documentId");
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
throw new ArgumentException(ServicesVSResources.DocumentIdNotFromWorkspace, "documentId");
}
var provider = project as IProjectCodeModelProvider;
if (provider != null)
{
var projectCodeModel = provider.ProjectCodeModel;
if (projectCodeModel.CanCreateFileCodeModelThroughProject(document.FilePath))
{
return (EnvDTE.FileCodeModel)projectCodeModel.CreateFileCodeModelThroughProject(document.FilePath);
}
}
return null;
}
internal override bool RenameFileCodeModelInstance(DocumentId documentId, string newFilePath)
{
if (documentId == null)
{
return false;
}
var project = ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
return false;
}
var codeModelProvider = project as IProjectCodeModelProvider;
if (codeModelProvider == null)
{
return false;
}
var codeModelCache = codeModelProvider.ProjectCodeModel.GetCodeModelCache();
if (codeModelCache == null)
{
return false;
}
codeModelCache.OnSourceFileRenaming(document.FilePath, newFilePath);
return true;
}
internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
return OpenInvisibleEditor(hostDocument);
}
internal override IInvisibleEditor OpenInvisibleEditor(IVisualStudioHostDocument hostDocument)
{
// We need to ensure the file is saved, only if a global undo transaction is open
var globalUndoService = this.Services.GetService<IGlobalUndoService>();
var needsSave = globalUndoService.IsGlobalTransactionOpen(this);
var needsUndoDisabled = false;
if (needsSave)
{
if (this.CurrentSolution.ContainsDocument(hostDocument.Id))
{
// Disable undo on generated documents
needsUndoDisabled = this.Services.GetService<IGeneratedCodeRecognitionService>().IsGeneratedCode(this.CurrentSolution.GetDocument(hostDocument.Id));
}
else
{
// Enable undo on "additional documents" or if no document can be found.
needsUndoDisabled = false;
}
}
return new InvisibleEditor(ServiceProvider, hostDocument.FilePath, needsSave, needsUndoDisabled);
}
private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject)
{
resolvedSymbol = null;
resolvedProject = null;
var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id);
if (currentProject == null)
{
return false;
}
var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolId = SymbolKey.Create(symbol, originalCompilation, cancellationToken);
var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken);
if (symbolInfo.Symbol == null)
{
return false;
}
resolvedSymbol = symbolInfo.Symbol;
resolvedProject = currentProject;
return true;
}
public override bool TryGoToDefinition(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_navigableItemsPresenters.Any())
{
return false;
}
ISymbol searchSymbol;
Project searchProject;
if (!TryResolveSymbol(symbol, project, cancellationToken, out searchSymbol, out searchProject))
{
return false;
}
return GoToDefinitionHelpers.TryGoToDefinition(
searchSymbol, searchProject, _navigableItemsPresenters, cancellationToken: cancellationToken);
}
public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_referencedSymbolsPresenters.Any())
{
return false;
}
ISymbol searchSymbol;
Project searchProject;
if (!TryResolveSymbol(symbol, project, cancellationToken, out searchSymbol, out searchProject))
{
return false;
}
var searchSolution = searchProject.Solution;
var result = SymbolFinder
.FindReferencesAsync(searchSymbol, searchSolution, cancellationToken)
.WaitAndGetResult(cancellationToken).ToList();
if (result != null)
{
DisplayReferencedSymbols(searchSolution, result);
return true;
}
return false;
}
public override void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols)
{
foreach (var presenter in _referencedSymbolsPresenters)
{
presenter.Value.DisplayResult(solution, referencedSymbols);
}
}
internal override object GetBrowseObject(SymbolListItem symbolListItem)
{
var compilation = symbolListItem.GetCompilation(this);
if (compilation == null)
{
return null;
}
var symbol = symbolListItem.ResolveSymbol(compilation);
var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault();
if (sourceLocation == null)
{
return null;
}
var projectId = symbolListItem.ProjectId;
if (projectId == null)
{
return null;
}
var project = this.CurrentSolution.GetProject(projectId);
if (project == null)
{
return null;
}
var codeModelService = project.LanguageServices.GetService<ICodeModelService>();
if (codeModelService == null)
{
return null;
}
var tree = sourceLocation.SourceTree;
var document = project.GetDocument(tree);
var vsFileCodeModel = this.GetFileCodeModel(document.Id);
var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel);
if (fileCodeModel != null)
{
var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan);
while (syntaxNode != null)
{
if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty)
{
break;
}
syntaxNode = syntaxNode.Parent;
}
if (syntaxNode != null)
{
var codeElement = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(syntaxNode);
if (codeElement != null)
{
return codeElement;
}
}
}
return null;
}
}
}
| |
/*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PartPreviewWindow;
using MatterHackers.MatterControl.PluginSystem;
using MatterHackers.MatterControl.PrinterCommunication;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.VectorMath;
namespace MatterHackers.MatterControl
{
public class MatterControlApplication : SystemWindow
{
string[] commandLineArgs = null;
bool firstDraw = true;
bool ShowMemoryUsed = false;
bool DoCGCollectEveryDraw = false;
public bool RestartOnClose = false;
public MatterControlApplication(double width, double height)
: base(width, height)
{
CrashTracker.Reset();
this.commandLineArgs = Environment.GetCommandLineArgs();
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
foreach(string command in commandLineArgs)
{
string commandUpper = command.ToUpper();
switch (commandUpper)
{
case "TEST":
Testing.TestingDispatch testDispatch = new Testing.TestingDispatch();
testDispatch.RunTests();
return;
case "CLEAR_CACHE":
AboutPage.DeleteCacheData();
break;
case "SHOW_MEMORY":
ShowMemoryUsed = true;
break;
case "DO_GC_COLLECT_EVERY_DRAW":
ShowMemoryUsed = true;
DoCGCollectEveryDraw = true;
break;
}
}
//WriteTestGCodeFile();
#if !DEBUG
if (File.Exists("RunUnitTests.txt"))
#endif
{
#if IS_WINDOWS_FORMS
Clipboard.SetSystemClipboardFunctions(System.Windows.Forms.Clipboard.GetText, System.Windows.Forms.Clipboard.SetText, System.Windows.Forms.Clipboard.ContainsText);
#endif
MatterHackers.PolygonMesh.UnitTests.UnitTests.Run();
MatterHackers.RayTracer.UnitTests.Run();
MatterHackers.Agg.Tests.UnitTests.Run();
MatterHackers.VectorMath.Tests.UnitTests.Run();
MatterHackers.Agg.UI.Tests.UnitTests.Run();
// you can turn this on to debug some bounds issues
//GuiWidget.DebugBoundsUnderMouse = true;
}
GuiWidget.DefaultEnforceIntegerBounds = true;
//TextWidget.GlobalPointSizeScaleRatio = 1.63;
this.AddChild(ApplicationWidget.Instance);
this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off
#if false // this is to test freeing gcodefile memory
Button test = new Button("test");
test.Click += (sender, e) =>
{
//MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile();
//gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode");
SystemWindow window = new SystemWindow(100, 100);
window.ShowAsSystemWindow();
};
allControls.AddChild(test);
#endif
this.AnchorAll();
UseOpenGL = true;
string version = "1.1";
Title = "MatterControl {0}".FormatWith(version);
if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
{
Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra);
}
UiThread.RunOnIdle(CheckOnPrinter);
MinimumSize = new Vector2(590, 630);
string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition");
if (desktopPosition != null && desktopPosition != "")
{
string[] sizes = desktopPosition.Split(',');
//If the desktop position is less than -10,-10, override
int xpos = Math.Max(int.Parse(sizes[0]), -10);
int ypos = Math.Max(int.Parse(sizes[1]), -10);
DesktopPosition = new Point2D(xpos, ypos);
}
ShowAsSystemWindow();
}
private static void WriteMove(StringBuilder gcodeStringBuilder, Vector2 center)
{
gcodeStringBuilder.AppendLine("G1 X" + center.x.ToString() + " Y" + center.y.ToString());
}
public static void WriteTestGCodeFile()
{
StringBuilder gcodeStringBuilder = new StringBuilder();
int loops = 15;
int steps = 20;
double radius = 90;
Vector2 center = new Vector2(0, 0);
gcodeStringBuilder.AppendLine("G28 ; home all axes");
gcodeStringBuilder.AppendLine("G90 ; use absolute coordinates");
gcodeStringBuilder.AppendLine("G21 ; set units to millimeters");
gcodeStringBuilder.AppendLine("G92 E0");
gcodeStringBuilder.AppendLine("G1 F7800.000");
//gcodeStringBuilder.AppendLine("G1 Z" + (30).ToString());
WriteMove(gcodeStringBuilder, center);
for (int loop = 0; loop < loops; loop++)
{
for (int step = 0; step < steps; step++)
{
Vector2 nextPosition = new Vector2(radius, 0);
nextPosition.Rotate(MathHelper.Tau / steps * step);
WriteMove(gcodeStringBuilder, center + nextPosition);
}
}
gcodeStringBuilder.AppendLine("M84 ; disable motors");
System.IO.File.WriteAllText("PerformanceTest.gcode", gcodeStringBuilder.ToString());
}
void CheckOnPrinter(object state)
{
PrinterConnectionAndCommunication.Instance.OnIdle();
UiThread.RunOnIdle(CheckOnPrinter);
}
public override void OnParentChanged(EventArgs e)
{
if (File.Exists("RunUnitTests.txt"))
{
//DiagnosticWidget diagnosticView = new DiagnosticWidget(this);
}
base.OnParentChanged(e);
// now that we are all set up lets load our plugins and allow them their chance to set things up
FindAndInstantiatePlugins();
}
private void FindAndInstantiatePlugins()
{
#if false
string pluginDirectory = Path.Combine("..", "..", "..", "MatterControlPlugins", "bin");
#if DEBUG
pluginDirectory = Path.Combine(pluginDirectory, "Debug");
#else
pluginDirectory = Path.Combine(pluginDirectory, "Release");
#endif
if (!Directory.Exists(pluginDirectory))
{
string dataPath = DataStorage.ApplicationDataStorage.Instance.ApplicationUserDataPath;
pluginDirectory = Path.Combine(dataPath, "Plugins");
}
// TODO: this should look in a plugin folder rather than just the application directory (we probably want it in the user folder).
PluginFinder<MatterControlPlugin> pulginFinder = new PluginFinder<MatterControlPlugin>(pluginDirectory);
#else
PluginFinder<MatterControlPlugin> pulginFinder = new PluginFinder<MatterControlPlugin>();
#endif
string oemName = ApplicationSettings.Instance.GetOEMName();
foreach (MatterControlPlugin plugin in pulginFinder.Plugins)
{
string pluginInfo = plugin.GetPluginInfoJSon();
Dictionary<string, string> nameValuePairs = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(pluginInfo);
if (nameValuePairs != null && nameValuePairs.ContainsKey("OEM"))
{
if (nameValuePairs["OEM"] == oemName)
{
plugin.Initialize(this);
}
}
else
{
plugin.Initialize(this);
}
}
}
Stopwatch totalDrawTime = new Stopwatch();
int drawCount = 0;
Gaming.Game.DataViewGraph msGraph = new Gaming.Game.DataViewGraph(new Vector2(20, 500), 50, 50, 0, 200);
public override void OnDraw(Graphics2D graphics2D)
{
totalDrawTime.Restart();
GuiWidget.DrawCount = 0;
base.OnDraw(graphics2D);
totalDrawTime.Stop();
if (ShowMemoryUsed)
{
long memory = GC.GetTotalMemory(false);
this.Title = "Allocated = {0:n0} : {1}ms, d{2} Size = {3}x{4}, onIdle = {5}, drawCount = {6}".FormatWith(memory, totalDrawTime.ElapsedMilliseconds, drawCount++, this.Width, this.Height, UiThread.Count, GuiWidget.DrawCount);
if (DoCGCollectEveryDraw)
{
GC.Collect();
}
}
if (firstDraw)
{
UiThread.RunOnIdle(DoAutoConnectIfRequired);
firstDraw = false;
foreach (string arg in commandLineArgs)
{
if (Path.GetExtension(arg).ToUpper() == ".STL")
{
QueueData.Instance.AddItem(new PrintItemWrapper(new DataStorage.PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
}
}
}
//msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds);
//msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D);
}
public void DoAutoConnectIfRequired(object state)
{
ActivePrinterProfile.CheckForAndDoAutoConnect();
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
if (GuiWidget.DebugBoundsUnderMouse)
{
Invalidate();
}
base.OnMouseMove(mouseEvent);
}
[STAThread]
public static void Main()
{
// Make sure we have the right woring directory as we assume everything relative to the executable.
Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));
Datastore.Instance.Initialize();
// try and open our window matching the last size that we had for it.
string windowSize = ApplicationSettings.Instance.get("WindowSize");
int width = 600;
int height = 660;
if (windowSize != null && windowSize != "")
{
string[] sizes = windowSize.Split(',');
width = Math.Max(int.Parse(sizes[0]), 600);
height = Math.Max(int.Parse(sizes[1]), 600);
}
new MatterControlApplication(width, height);
}
public override void OnClosed(EventArgs e)
{
PrinterConnectionAndCommunication.Instance.Disable();
//Close connection to the local datastore
Datastore.Instance.Exit();
PrinterConnectionAndCommunication.Instance.HaltConnectionThread();
SlicingQueue.Instance.ShutDownSlicingThread();
if (RestartOnClose)
{
string appPathAndFile = System.Reflection.Assembly.GetExecutingAssembly().Location;
string pathToAppFolder = Path.GetDirectoryName(appPathAndFile);
ProcessStartInfo runAppLauncherStartInfo = new ProcessStartInfo();
runAppLauncherStartInfo.Arguments = "\"{0}\" \"{1}\"".FormatWith(appPathAndFile, 1000);
runAppLauncherStartInfo.FileName = Path.Combine(pathToAppFolder, "Launcher.exe");
runAppLauncherStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
runAppLauncherStartInfo.CreateNoWindow = true;
Process.Start(runAppLauncherStartInfo);
}
base.OnClosed(e);
}
string unableToExitMessage = "Oops! You cannot exit while a print is active.".Localize();
string unableToExitTitle = "Unable to Exit".Localize();
string savePartsSheetExitAnywayMessage = "You are currently saving a parts sheet, are you sure you want to exit?".Localize();
string confirmExit = "Confirm Exit".Localize();
public override void OnClosing(out bool CancelClose)
{
// save the last size of the window so we can restore it next time.
ApplicationSettings.Instance.set("WindowSize", string.Format("{0},{1}", Width, Height));
ApplicationSettings.Instance.set("DesktopPosition", string.Format("{0},{1}", DesktopPosition.x, DesktopPosition.y));
//Save a snapshot of the prints in queue
QueueData.Instance.SaveDefaultQueue();
if (PrinterConnectionAndCommunication.Instance.PrinterIsPrinting)
{
StyledMessageBox.ShowMessageBox(unableToExitMessage, unableToExitTitle);
CancelClose = true;
}
else if (PartsSheet.IsSaving())
{
if (!StyledMessageBox.ShowMessageBox(savePartsSheetExitAnywayMessage, confirmExit, StyledMessageBox.MessageType.YES_NO))
{
CancelClose = true;
}
else
{
base.OnClosing(out CancelClose);
}
}
else
{
base.OnClosing(out CancelClose);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class ExprFactory
{
private readonly GlobalSymbolContext _globalSymbolContext;
public ExprFactory(GlobalSymbolContext globalSymbolContext)
{
Debug.Assert(globalSymbolContext != null);
_globalSymbolContext = globalSymbolContext;
}
private TypeManager GetTypes()
{
return _globalSymbolContext.GetTypes();
}
private BSYMMGR GetGlobalSymbols()
{
return _globalSymbolContext.GetGlobalSymbols();
}
public ExprCall CreateCall(EXPRFLAG nFlags, CType pType, Expr pOptionalArguments, ExprMemberGroup pMemberGroup, MethWithInst MWI)
{
Debug.Assert(0 == (nFlags &
~(
EXPRFLAG.EXF_NEWOBJCALL | EXPRFLAG.EXF_CONSTRAINED | EXPRFLAG.EXF_BASECALL |
EXPRFLAG.EXF_NEWSTRUCTASSG |
EXPRFLAG.EXF_IMPLICITSTRUCTASSG | EXPRFLAG.EXF_MASK_ANY
)
));
ExprCall rval = new ExprCall(pType);
rval.Flags = nFlags;
rval.OptionalArguments = pOptionalArguments;
rval.MemberGroup = pMemberGroup;
rval.NullableCallLiftKind = NullableCallLiftKind.NotLifted;
rval.MethWithInst = MWI;
return rval;
}
public ExprField CreateField(EXPRFLAG nFlags, CType pType, Expr pOptionalObject, FieldWithType FWT)
{
Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MEMBERSET | EXPRFLAG.EXF_MASK_ANY)));
ExprField rval = new ExprField(pType);
rval.Flags = nFlags;
rval.OptionalObject = pOptionalObject;
rval.FieldWithType = FWT;
return rval;
}
public ExprFuncPtr CreateFunctionPointer(EXPRFLAG nFlags, CType pType, Expr pObject, MethWithInst MWI)
{
Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_BASECALL)));
ExprFuncPtr rval = new ExprFuncPtr(pType);
rval.Flags = nFlags;
rval.OptionalObject = pObject;
rval.MethWithInst = new MethWithInst(MWI);
return rval;
}
public ExprArrayInit CreateArrayInit(EXPRFLAG nFlags, CType pType, Expr pOptionalArguments, Expr pOptionalArgumentDimensions, int[] pDimSizes)
{
Debug.Assert(0 == (nFlags &
~(EXPRFLAG.EXF_MASK_ANY | EXPRFLAG.EXF_ARRAYCONST | EXPRFLAG.EXF_ARRAYALLCONST)));
ExprArrayInit rval = new ExprArrayInit(pType);
rval.OptionalArguments = pOptionalArguments;
rval.OptionalArgumentDimensions = pOptionalArgumentDimensions;
rval.DimensionSizes = pDimSizes;
rval.DimensionSize = pDimSizes?.Length ?? 0;
return rval;
}
public ExprProperty CreateProperty(CType pType, Expr pOptionalObject)
{
MethPropWithInst mwi = new MethPropWithInst();
ExprMemberGroup pMemGroup = CreateMemGroup(pOptionalObject, mwi);
return CreateProperty(pType, null, null, pMemGroup, null, null, null);
}
public ExprProperty CreateProperty(CType pType, Expr pOptionalObjectThrough, Expr pOptionalArguments, ExprMemberGroup pMemberGroup, PropWithType pwtSlot, MethWithType mwtGet, MethWithType mwtSet)
{
ExprProperty rval = new ExprProperty(pType);
rval.OptionalObjectThrough = pOptionalObjectThrough;
rval.OptionalArguments = pOptionalArguments;
rval.MemberGroup = pMemberGroup;
if (pwtSlot != null)
{
rval.PropWithTypeSlot = pwtSlot;
}
if (mwtSet != null)
{
rval.MethWithTypeSet = mwtSet;
}
return rval;
}
public ExprEvent CreateEvent(CType pType, Expr pOptionalObject, EventWithType EWT)
{
ExprEvent rval = new ExprEvent(pType);
rval.OptionalObject = pOptionalObject;
rval.EventWithType = EWT;
return rval;
}
public ExprMemberGroup CreateMemGroup(EXPRFLAG nFlags, Name pName, TypeArray pTypeArgs, SYMKIND symKind, CType pTypePar, MethodOrPropertySymbol pMPS, Expr pObject, CMemberLookupResults memberLookupResults)
{
Debug.Assert(0 == (nFlags & ~(
EXPRFLAG.EXF_CTOR | EXPRFLAG.EXF_INDEXER | EXPRFLAG.EXF_OPERATOR | EXPRFLAG.EXF_NEWOBJCALL |
EXPRFLAG.EXF_BASECALL | EXPRFLAG.EXF_DELEGATE | EXPRFLAG.EXF_USERCALLABLE | EXPRFLAG.EXF_MASK_ANY
)
));
ExprMemberGroup rval = new ExprMemberGroup(GetTypes().GetMethGrpType());
rval.Flags = nFlags;
rval.Name = pName;
rval.TypeArgs = pTypeArgs ?? BSYMMGR.EmptyTypeArray();
rval.SymKind = symKind;
rval.ParentType = pTypePar;
rval.OptionalObject = pObject;
rval.MemberLookupResults = memberLookupResults;
return rval;
}
public ExprMemberGroup CreateMemGroup(
Expr pObject,
MethPropWithInst mwi)
{
Name pName = mwi.Sym?.name;
MethodOrPropertySymbol methProp = mwi.MethProp();
CType pType = mwi.GetType() ?? (CType)GetTypes().GetErrorSym();
return CreateMemGroup(0, pName, mwi.TypeArgs, methProp?.getKind() ?? SYMKIND.SK_MethodSymbol, mwi.GetType(), methProp, pObject, new CMemberLookupResults(GetGlobalSymbols().AllocParams(1, new CType[] { pType }), pName));
}
public ExprUserDefinedConversion CreateUserDefinedConversion(Expr arg, Expr call, MethWithInst mwi)
{
Debug.Assert(arg != null);
Debug.Assert(call != null);
ExprUserDefinedConversion rval = new ExprUserDefinedConversion();
rval.Argument = arg;
rval.UserDefinedCall = call;
rval.UserDefinedCallMethod = mwi;
if (call.HasError)
{
rval.SetError();
}
return rval;
}
public ExprCast CreateCast(EXPRFLAG nFlags, CType pType, Expr pArg)
{
return CreateCast(nFlags, CreateClass(pType, null), pArg);
}
public ExprCast CreateCast(EXPRFLAG nFlags, ExprClass pType, Expr pArg)
{
Debug.Assert(pArg != null);
Debug.Assert(pType != null);
Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_CAST_ALL | EXPRFLAG.EXF_MASK_ANY)));
ExprCast rval = new ExprCast();
rval.Argument = pArg;
rval.Flags = nFlags;
rval.DestinationType = pType;
return rval;
}
public ExprReturn CreateReturn(EXPRFLAG nFlags, Scope pCurrentScope, Expr pOptionalObject)
{
Debug.Assert(0 == (nFlags &
~(EXPRFLAG.EXF_ASLEAVE | EXPRFLAG.EXF_FINALLYBLOCKED | EXPRFLAG.EXF_RETURNISYIELD |
EXPRFLAG.EXF_ASFINALLYLEAVE | EXPRFLAG.EXF_GENERATEDSTMT | EXPRFLAG.EXF_MARKING |
EXPRFLAG.EXF_MASK_ANY
)
));
ExprReturn rval = new ExprReturn();
rval.Flags = nFlags;
rval.OptionalObject = pOptionalObject;
return rval;
}
public ExprLocal CreateLocal(EXPRFLAG nFlags, LocalVariableSymbol pLocal)
{
Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MASK_ANY)));
ExprLocal rval = new ExprLocal();
rval.Flags = nFlags;
rval.Local = pLocal;
return rval;
}
public ExprBoundLambda CreateAnonymousMethod(AggregateType delegateType)
{
Debug.Assert(delegateType == null || delegateType.isDelegateType());
ExprBoundLambda rval = new ExprBoundLambda(delegateType);
return rval;
}
public ExprUnboundLambda CreateLambda()
{
ExprUnboundLambda rval = new ExprUnboundLambda(GetTypes().GetAnonMethType());
return rval;
}
public ExprHoistedLocalExpr CreateHoistedLocalInExpression(ExprLocal localToHoist)
{
Debug.Assert(localToHoist != null);
return new ExprHoistedLocalExpr(GetTypes().GetOptPredefAgg(PredefinedType.PT_EXPRESSION).getThisType());
}
public ExprMethodInfo CreateMethodInfo(MethPropWithInst mwi)
{
return CreateMethodInfo(mwi.Meth(), mwi.GetType(), mwi.TypeArgs);
}
public ExprMethodInfo CreateMethodInfo(MethodSymbol method, AggregateType methodType, TypeArray methodParameters)
{
Debug.Assert(method != null);
Debug.Assert(methodType != null);
ExprMethodInfo methodInfo = new ExprMethodInfo(
GetTypes().GetOptPredefAgg(method.IsConstructor() ? PredefinedType.PT_CONSTRUCTORINFO : PredefinedType.PT_METHODINFO).getThisType());
methodInfo.Method = new MethWithInst(method, methodType, methodParameters);
return methodInfo;
}
public ExprPropertyInfo CreatePropertyInfo(PropertySymbol prop, AggregateType propertyType)
{
Debug.Assert(prop != null);
Debug.Assert(propertyType != null);
ExprPropertyInfo propInfo = new ExprPropertyInfo(GetTypes().GetOptPredefAgg(PredefinedType.PT_PROPERTYINFO).getThisType());
propInfo.Property = new PropWithType(prop, propertyType);
return propInfo;
}
public ExprFieldInfo CreateFieldInfo(FieldSymbol field, AggregateType fieldType)
{
Debug.Assert(field != null);
Debug.Assert(fieldType != null);
return new ExprFieldInfo(field, fieldType, GetTypes().GetOptPredefAgg(PredefinedType.PT_FIELDINFO).getThisType());
}
private ExprTypeOf CreateTypeOf(ExprClass pSourceType)
{
ExprTypeOf rval = new ExprTypeOf(GetTypes().GetReqPredefAgg(PredefinedType.PT_TYPE).getThisType());
rval.Flags = EXPRFLAG.EXF_CANTBENULL;
rval.SourceType = pSourceType;
return rval;
}
public ExprTypeOf CreateTypeOf(CType pSourceType)
{
return CreateTypeOf(MakeClass(pSourceType));
}
public ExprUserLogicalOp CreateUserLogOp(CType pType, Expr pCallTF, ExprCall pCallOp)
{
Debug.Assert(pCallTF != null);
Debug.Assert((pCallOp?.OptionalArguments as ExprList)?.OptionalElement != null);
ExprUserLogicalOp rval = new ExprUserLogicalOp(pType);
Expr leftChild = ((ExprList)pCallOp.OptionalArguments).OptionalElement;
Debug.Assert(leftChild != null);
if (leftChild is ExprWrap wrap)
{
// In the EE case, we don't create WRAPEXPRs.
leftChild = wrap.OptionalExpression;
Debug.Assert(leftChild != null);
}
rval.Flags = EXPRFLAG.EXF_ASSGOP;
rval.TrueFalseCall = pCallTF;
rval.OperatorCall = pCallOp;
rval.FirstOperandToExamine = leftChild;
return rval;
}
public ExprUserLogicalOp CreateUserLogOpError(CType pType, Expr pCallTF, ExprCall pCallOp)
{
ExprUserLogicalOp rval = CreateUserLogOp(pType, pCallTF, pCallOp);
rval.SetError();
return rval;
}
public ExprConcat CreateConcat(Expr op1, Expr op2)
{
Debug.Assert(op1?.Type != null);
Debug.Assert(op2?.Type != null);
Debug.Assert(op1.Type.isPredefType(PredefinedType.PT_STRING) || op2.Type.isPredefType(PredefinedType.PT_STRING));
CType type = op1.Type;
if (!type.isPredefType(PredefinedType.PT_STRING))
{
type = op2.Type;
}
Debug.Assert(type.isPredefType(PredefinedType.PT_STRING));
ExprConcat rval = new ExprConcat(type);
rval.FirstArgument = op1;
rval.SecondArgument = op2;
return rval;
}
public ExprConstant CreateStringConstant(string str)
{
return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_STRING).getThisType(), ConstVal.Get(str));
}
public ExprMultiGet CreateMultiGet(EXPRFLAG nFlags, CType pType, ExprMulti pOptionalMulti)
{
Debug.Assert(0 == (nFlags & ~(EXPRFLAG.EXF_MASK_ANY)));
ExprMultiGet rval = new ExprMultiGet(pType);
rval.Flags = nFlags;
rval.OptionalMulti = pOptionalMulti;
return rval;
}
public ExprMulti CreateMulti(EXPRFLAG nFlags, CType pType, Expr pLeft, Expr pOp)
{
Debug.Assert(pLeft != null);
Debug.Assert(pOp != null);
ExprMulti rval = new ExprMulti(pType);
rval.Flags = nFlags;
rval.Left = pLeft;
rval.Operator = pOp;
return rval;
}
////////////////////////////////////////////////////////////////////////////////
//
// Precondition:
//
// pType - Non-null
//
// This returns a null for reference types and an EXPRZEROINIT for all others.
public Expr CreateZeroInit(CType pType)
{
ExprClass exprClass = MakeClass(pType);
return CreateZeroInit(exprClass);
}
private Expr CreateZeroInit(ExprClass pTypeExpr)
{
return CreateZeroInit(pTypeExpr, null, false);
}
private Expr CreateZeroInit(ExprClass pTypeExpr, Expr pOptionalOriginalConstructorCall, bool isConstructor)
{
Debug.Assert(pTypeExpr != null);
CType pType = pTypeExpr.Type;
bool bIsError = false;
if (pType.isEnumType())
{
// For enum types, we create a constant that has the default value
// as an object pointer.
ExprConstant expr = CreateConstant(pType, ConstVal.Get(Activator.CreateInstance(pType.AssociatedSystemType)));
return expr;
}
switch (pType.fundType())
{
default:
bIsError = true;
break;
case FUNDTYPE.FT_PTR:
{
CType nullType = GetTypes().GetNullType();
// It looks like this if is always false ...
if (nullType.fundType() == pType.fundType())
{
// Create a constant here.
ExprConstant expr = CreateConstant(pType, ConstVal.GetDefaultValue(ConstValKind.IntPtr));
return (expr);
}
// Just allocate a new node and fill it in.
ExprCast cast = CreateCast(0, pTypeExpr, CreateNull());
return (cast);
}
case FUNDTYPE.FT_REF:
case FUNDTYPE.FT_I1:
case FUNDTYPE.FT_U1:
case FUNDTYPE.FT_I2:
case FUNDTYPE.FT_U2:
case FUNDTYPE.FT_I4:
case FUNDTYPE.FT_U4:
case FUNDTYPE.FT_I8:
case FUNDTYPE.FT_U8:
case FUNDTYPE.FT_R4:
case FUNDTYPE.FT_R8:
{
ExprConstant expr = CreateConstant(pType, ConstVal.GetDefaultValue(pType.constValKind()));
ExprConstant exprInOriginal = CreateConstant(pType, ConstVal.GetDefaultValue(pType.constValKind()));
exprInOriginal.OptionalConstructorCall = pOptionalOriginalConstructorCall;
return expr;
}
case FUNDTYPE.FT_STRUCT:
if (pType.isPredefType(PredefinedType.PT_DECIMAL))
{
ExprConstant expr = CreateConstant(pType, ConstVal.GetDefaultValue(pType.constValKind()));
ExprConstant exprOriginal = CreateConstant(pType, ConstVal.GetDefaultValue(pType.constValKind()));
exprOriginal.OptionalConstructorCall = pOptionalOriginalConstructorCall;
return expr;
}
break;
case FUNDTYPE.FT_VAR:
break;
}
ExprZeroInit rval = new ExprZeroInit(pType);
rval.OptionalConstructorCall = pOptionalOriginalConstructorCall;
rval.IsConstructor = isConstructor;
if (bIsError)
{
rval.SetError();
}
return rval;
}
public ExprConstant CreateConstant(CType pType, ConstVal constVal)
{
ExprConstant rval = CreateConstant(pType);
rval.Val = constVal;
return rval;
}
private ExprConstant CreateConstant(CType pType)
{
return new ExprConstant(pType);
}
public ExprConstant CreateIntegerConstant(int x)
{
return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_INT).getThisType(), ConstVal.Get(x));
}
public ExprConstant CreateBoolConstant(bool b)
{
return CreateConstant(GetTypes().GetReqPredefAgg(PredefinedType.PT_BOOL).getThisType(), ConstVal.Get(b));
}
public ExprBlock CreateBlock(ExprStatement pOptionalStatements, Scope pOptionalScope)
{
ExprBlock rval = new ExprBlock();
rval.OptionalStatements = pOptionalStatements;
rval.OptionalScopeSymbol = pOptionalScope;
return rval;
}
public ExprArrayIndex CreateArrayIndex(Expr pArray, Expr pIndex)
{
CType pType = pArray.Type;
if (pType != null && pType.IsArrayType())
{
pType = pType.AsArrayType().GetElementType();
}
else if (pType == null)
{
pType = GetTypes().GetReqPredefAgg(PredefinedType.PT_INT).getThisType();
}
ExprArrayIndex pResult = new ExprArrayIndex(pType);
pResult.Array = pArray;
pResult.Index = pIndex;
return pResult;
}
public ExprBinOp CreateBinop(ExpressionKind exprKind, CType pType, Expr p1, Expr p2)
{
//Debug.Assert(exprKind.isBinaryOperator());
ExprBinOp rval = new ExprBinOp(exprKind, pType);
rval.Flags = EXPRFLAG.EXF_BINOP;
rval.OptionalLeftChild = p1;
rval.OptionalRightChild = p2;
return rval;
}
public ExprUnaryOp CreateUnaryOp(ExpressionKind exprKind, CType pType, Expr pOperand)
{
Debug.Assert(exprKind.IsUnaryOperator());
Debug.Assert(pOperand != null);
ExprUnaryOp rval = new ExprUnaryOp(exprKind, pType);
rval.Child = pOperand;
return rval;
}
public ExprOperator CreateOperator(ExpressionKind exprKind, CType pType, Expr pArg1, Expr pOptionalArg2)
{
Debug.Assert(pArg1 != null);
Debug.Assert(exprKind.IsUnaryOperator() ? pOptionalArg2 == null : pOptionalArg2 != null);
return exprKind.IsUnaryOperator()
? (ExprOperator)CreateUnaryOp(exprKind, pType, pArg1)
: CreateBinop(exprKind, pType, pArg1, pOptionalArg2);
}
public ExprBinOp CreateUserDefinedBinop(ExpressionKind exprKind, CType pType, Expr p1, Expr p2, Expr call, MethPropWithInst pmpwi)
{
Debug.Assert(p1 != null);
Debug.Assert(p2 != null);
Debug.Assert(call != null);
ExprBinOp rval = new ExprBinOp(exprKind, pType);
rval.Flags = EXPRFLAG.EXF_BINOP;
rval.OptionalLeftChild = p1;
rval.OptionalRightChild = p2;
rval.OptionalUserDefinedCall = call;
rval.UserDefinedCallMethod = pmpwi;
if (call.HasError)
{
rval.SetError();
}
return rval;
}
public ExprUnaryOp CreateUserDefinedUnaryOperator(ExpressionKind exprKind, CType pType, Expr pOperand, ExprCall call, MethPropWithInst pmpwi)
{
Debug.Assert(pType != null);
Debug.Assert(pOperand != null);
Debug.Assert(call != null);
Debug.Assert(pmpwi != null);
ExprUnaryOp rval = new ExprUnaryOp(exprKind, pType);
rval.Child = pOperand;
// The call may be lifted, but we do not mark the outer binop as lifted.
rval.OptionalUserDefinedCall = call;
rval.UserDefinedCallMethod = pmpwi;
if (call.HasError)
{
rval.SetError();
}
return rval;
}
public ExprUnaryOp CreateNeg(EXPRFLAG nFlags, Expr pOperand)
{
Debug.Assert(pOperand != null);
ExprUnaryOp pUnaryOp = CreateUnaryOp(ExpressionKind.Negate, pOperand.Type, pOperand);
pUnaryOp.Flags |= nFlags;
return pUnaryOp;
}
////////////////////////////////////////////////////////////////////////////////
// Create a node that evaluates the first, evaluates the second, results in the second.
public ExprBinOp CreateSequence(Expr p1, Expr p2)
{
Debug.Assert(p1 != null);
Debug.Assert(p2 != null);
return CreateBinop(ExpressionKind.Sequence, p2.Type, p1, p2);
}
////////////////////////////////////////////////////////////////////////////////
// Create a node that evaluates the first, evaluates the second, results in the first.
public ExprBinOp CreateReverseSequence(Expr p1, Expr p2)
{
Debug.Assert(p1 != null);
Debug.Assert(p2 != null);
return CreateBinop(ExpressionKind.SequenceReverse, p1.Type, p1, p2);
}
public ExprAssignment CreateAssignment(Expr pLHS, Expr pRHS)
{
ExprAssignment pAssignment = new ExprAssignment();
pAssignment.Flags = EXPRFLAG.EXF_ASSGOP;
pAssignment.LHS = pLHS;
pAssignment.RHS = pRHS;
return pAssignment;
}
////////////////////////////////////////////////////////////////////////////////
public ExprNamedArgumentSpecification CreateNamedArgumentSpecification(Name pName, Expr pValue)
{
ExprNamedArgumentSpecification pResult = new ExprNamedArgumentSpecification();
pResult.Value = pValue;
pResult.Name = pName;
return pResult;
}
public ExprWrap CreateWrap(
Scope pCurrentScope,
Expr pOptionalExpression
)
{
ExprWrap rval = new ExprWrap();
rval.OptionalExpression = pOptionalExpression;
rval.Flags = EXPRFLAG.EXF_LVALUE;
return rval;
}
public ExprWrap CreateWrapNoAutoFree(Scope pCurrentScope, Expr pOptionalWrap)
{
ExprWrap rval = CreateWrap(pCurrentScope, pOptionalWrap);
return rval;
}
public ExprBinOp CreateSave(ExprWrap wrap)
{
Debug.Assert(wrap != null);
ExprBinOp expr = CreateBinop(ExpressionKind.Save, wrap.Type, wrap.OptionalExpression, wrap);
expr.SetAssignment();
return expr;
}
public ExprConstant CreateNull()
{
return CreateConstant(GetTypes().GetNullType(), default(ConstVal));
}
public void AppendItemToList(
Expr newItem,
ref Expr first,
ref Expr last
)
{
if (newItem == null)
{
// Nothing changes.
return;
}
if (first == null)
{
Debug.Assert(last == first);
first = newItem;
last = newItem;
return;
}
if (first.Kind != ExpressionKind.List)
{
Debug.Assert(last == first);
first = CreateList(first, newItem);
last = first;
return;
}
Debug.Assert((last as ExprList)?.OptionalNextListNode != null);
Debug.Assert((last as ExprList).OptionalNextListNode.Kind != ExpressionKind.List);
ExprList list = (ExprList)last;
list.OptionalNextListNode = CreateList(list.OptionalNextListNode, newItem);
last = list.OptionalNextListNode;
}
public ExprList CreateList(Expr op1, Expr op2)
{
ExprList rval = new ExprList();
rval.OptionalElement = op1;
rval.OptionalNextListNode = op2;
return rval;
}
public ExprList CreateList(Expr op1, Expr op2, Expr op3)
{
return CreateList(op1, CreateList(op2, op3));
}
public ExprList CreateList(Expr op1, Expr op2, Expr op3, Expr op4)
{
return CreateList(op1, CreateList(op2, CreateList(op3, op4)));
}
public ExprTypeArguments CreateTypeArguments(TypeArray pTypeArray, Expr pOptionalElements)
{
Debug.Assert(pTypeArray != null);
ExprTypeArguments rval = new ExprTypeArguments();
rval.OptionalElements = pOptionalElements;
return rval;
}
public ExprClass CreateClass(CType pType, ExprTypeArguments pOptionalTypeArguments)
{
Debug.Assert(pType != null);
ExprClass rval = new ExprClass(pType);
return rval;
}
public ExprClass MakeClass(CType pType)
{
Debug.Assert(pType != null);
return CreateClass(pType, null/* type arguments */);
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.Config.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Apps.
/// </summary>
[RoutePrefix("api/v1.0/config/app")]
public class AppController : FrapidApiController
{
/// <summary>
/// The App repository.
/// </summary>
private readonly IAppRepository AppRepository;
public AppController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.AppRepository = new Frapid.Config.DataAccess.App
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public AppController(IAppRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.AppRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "app" entity.
/// </summary>
/// <returns>Returns the "app" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/config/app/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "app_name",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "app_name", PropertyName = "AppName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = true, IsSerial = false, Value = "", MaxLength = 100 },
new EntityColumn { ColumnName = "name", PropertyName = "Name", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 },
new EntityColumn { ColumnName = "version_number", PropertyName = "VersionNumber", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 },
new EntityColumn { ColumnName = "publisher", PropertyName = "Publisher", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 },
new EntityColumn { ColumnName = "published_on", PropertyName = "PublishedOn", DataType = "DateTime", DbDataType = "date", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "icon", PropertyName = "Icon", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 },
new EntityColumn { ColumnName = "landing_url", PropertyName = "LandingUrl", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }
}
};
}
/// <summary>
/// Counts the number of apps.
/// </summary>
/// <returns>Returns the count of the apps.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/config/app/count")]
[Authorize]
public long Count()
{
try
{
return this.AppRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of app.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/config/app/all")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.App> GetAll()
{
try
{
return this.AppRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of app for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/config/app/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.AppRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of app.
/// </summary>
/// <param name="appName">Enter AppName to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{appName}")]
[Route("~/api/config/app/{appName}")]
[Authorize]
public Frapid.Config.Entities.App Get(string appName)
{
try
{
return this.AppRepository.Get(appName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/config/app/get")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.App> Get([FromUri] string[] appNames)
{
try
{
return this.AppRepository.Get(appNames);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of app.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/config/app/first")]
[Authorize]
public Frapid.Config.Entities.App GetFirst()
{
try
{
return this.AppRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of app.
/// </summary>
/// <param name="appName">Enter AppName to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{appName}")]
[Route("~/api/config/app/previous/{appName}")]
[Authorize]
public Frapid.Config.Entities.App GetPrevious(string appName)
{
try
{
return this.AppRepository.GetPrevious(appName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of app.
/// </summary>
/// <param name="appName">Enter AppName to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{appName}")]
[Route("~/api/config/app/next/{appName}")]
[Authorize]
public Frapid.Config.Entities.App GetNext(string appName)
{
try
{
return this.AppRepository.GetNext(appName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of app.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/config/app/last")]
[Authorize]
public Frapid.Config.Entities.App GetLast()
{
try
{
return this.AppRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 apps on each page, sorted by the property AppName.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/config/app")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.App> GetPaginatedResult()
{
try
{
return this.AppRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 apps on each page, sorted by the property AppName.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/config/app/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.App> GetPaginatedResult(long pageNumber)
{
try
{
return this.AppRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of apps using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered apps.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/config/app/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.AppRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 apps on each page, sorted by the property AppName.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/config/app/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.App> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.AppRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of apps using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered apps.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/config/app/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.AppRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 apps on each page, sorted by the property AppName.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/config/app/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.App> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.AppRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of apps.
/// </summary>
/// <returns>Returns an enumerable key/value collection of apps.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/config/app/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.AppRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for apps.
/// </summary>
/// <returns>Returns an enumerable custom field collection of apps.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/config/app/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.AppRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for apps.
/// </summary>
/// <returns>Returns an enumerable custom field collection of apps.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/config/app/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.AppRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of App class.
/// </summary>
/// <param name="app">Your instance of apps class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/config/app/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic app = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (app == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.AppRepository.AddOrEdit(app, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of App class.
/// </summary>
/// <param name="app">Your instance of apps class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{app}")]
[Route("~/api/config/app/add/{app}")]
[Authorize]
public void Add(Frapid.Config.Entities.App app)
{
if (app == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.AppRepository.Add(app);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of App class.
/// </summary>
/// <param name="app">Your instance of App class to edit.</param>
/// <param name="appName">Enter the value for AppName in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{appName}")]
[Route("~/api/config/app/edit/{appName}")]
[Authorize]
public void Edit(string appName, [FromBody] Frapid.Config.Entities.App app)
{
if (app == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.AppRepository.Update(app, appName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of App class.
/// </summary>
/// <param name="collection">Your collection of App class to bulk import.</param>
/// <returns>Returns list of imported appNames.</returns>
/// <exception cref="DataAccessException">Thrown when your any App class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/config/app/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> appCollection = this.ParseCollection(collection);
if (appCollection == null || appCollection.Count.Equals(0))
{
return null;
}
try
{
return this.AppRepository.BulkImport(appCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of App class via AppName.
/// </summary>
/// <param name="appName">Enter the value for AppName in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{appName}")]
[Route("~/api/config/app/delete/{appName}")]
[Authorize]
public void Delete(string appName)
{
try
{
this.AppRepository.Delete(appName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using CURLAUTH = Interop.libcurl.CURLAUTH;
using CURLcode = Interop.libcurl.CURLcode;
using CurlFeatures = Interop.libcurl.CURL_VERSION_Features;
using CURLMcode = Interop.libcurl.CURLMcode;
using CURLoption = Interop.libcurl.CURLoption;
using CurlVersionInfoData = Interop.libcurl.curl_version_info_data;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
#region Constants
private const string VerboseDebuggingConditional = "CURLHANDLER_VERBOSE";
private const string HttpPrefix = "HTTP/";
private const char SpaceChar = ' ';
private const int StatusCodeLength = 3;
private const string UriSchemeHttp = "http";
private const string UriSchemeHttps = "https";
private const string EncodingNameGzip = "gzip";
private const string EncodingNameDeflate = "deflate";
private const int RequestBufferSize = 16384; // Default used by libcurl
private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":";
private const string NoContentType = HttpKnownHeaderNames.ContentType + ":";
private const int CurlAge = 5;
private const int MinCurlAge = 3;
#endregion
#region Fields
private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF };
private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes
private readonly static ulong[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic };
private readonly static CurlVersionInfoData s_curlVersionInfoData;
private readonly static bool s_supportsAutomaticDecompression;
private readonly static bool s_supportsSSL;
private readonly MultiAgent _agent = new MultiAgent();
private volatile bool _anyOperationStarted;
private volatile bool _disposed;
private IWebProxy _proxy = null;
private ICredentials _serverCredentials = null;
private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate;
private CredentialCache _credentialCache = null; // protected by LockObject
private CookieContainer _cookieContainer = new CookieContainer();
private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private object LockObject { get { return _agent; } }
#endregion
static CurlHandler()
{
// curl_global_init call handled by Interop.libcurl's cctor
// Verify the version of curl we're using is new enough
s_curlVersionInfoData = Marshal.PtrToStructure<CurlVersionInfoData>(Interop.libcurl.curl_version_info(CurlAge));
if (s_curlVersionInfoData.age < MinCurlAge)
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old);
}
// Feature detection
s_supportsSSL = (CurlFeatures.CURL_VERSION_SSL & s_curlVersionInfoData.features) != 0;
s_supportsAutomaticDecompression = (CurlFeatures.CURL_VERSION_LIBZ & s_curlVersionInfoData.features) != 0;
}
#region Properties
internal bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
internal bool SupportsProxy
{
get
{
return true;
}
}
internal bool SupportsRedirectConfiguration
{
get
{
return true;
}
}
internal bool UseProxy
{
get
{
return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy;
}
set
{
CheckDisposedOrStarted();
_proxyPolicy = value ?
ProxyUsePolicy.UseCustomProxy :
ProxyUsePolicy.DoNotUseProxy;
}
}
internal IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
internal ICredentials Credentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
internal ClientCertificateOption ClientCertificateOptions
{
get
{
return ClientCertificateOption.Manual;
}
set
{
if (ClientCertificateOption.Manual != value)
{
throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option);
}
}
}
internal bool SupportsAutomaticDecompression
{
get
{
return s_supportsAutomaticDecompression;
}
}
internal DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
internal bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
CheckDisposedOrStarted();
_preAuthenticate = value;
if (value && _credentialCache == null)
{
_credentialCache = new CredentialCache();
}
}
}
internal bool UseCookie
{
get
{
return _useCookie;
}
set
{
CheckDisposedOrStarted();
_useCookie = value;
}
}
internal CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
internal int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
/// <summary>
/// <b> UseDefaultCredentials is a no op on Unix </b>
/// </summary>
internal bool UseDefaultCredentials
{
get
{
return false;
}
set
{
}
}
#endregion
protected override void Dispose(bool disposing)
{
_disposed = true;
base.Dispose(disposing);
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request", SR.net_http_handler_norequest);
}
if (request.RequestUri.Scheme == UriSchemeHttps)
{
if (!s_supportsSSL)
{
throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl);
}
}
else
{
Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https.");
}
if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
if (_useCookie && _cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
// Do an initial cancellation check to avoid initiating the async operation if
// cancellation has already been requested. After this, we'll rely on CancellationToken.Register
// to notify us of cancellation requests and shut down the operation if possible.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
}
// Create the easy request. This associates the easy request with this handler and configures
// it based on the settings configured for the handler.
var easy = new EasyRequest(this, request, cancellationToken);
try
{
easy.InitializeCurl();
if (easy._requestContentStream != null)
{
easy._requestContentStream.Run();
}
_agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
}
catch (Exception exc)
{
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
return easy.Task;
}
#region Private methods
private void SetOperationStarted()
{
if (!_anyOperationStarted)
{
_anyOperationStarted = true;
}
}
private KeyValuePair<NetworkCredential, ulong> GetNetworkCredentials(ICredentials credentials, Uri requestUri)
{
if (_preAuthenticate)
{
KeyValuePair<NetworkCredential, ulong> ncAndScheme;
lock (LockObject)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
ncAndScheme = GetCredentials(_credentialCache, requestUri);
}
if (ncAndScheme.Key != null)
{
return ncAndScheme;
}
}
return GetCredentials(credentials, requestUri);
}
private void AddCredentialToCache(Uri serverUri, ulong authAvail, NetworkCredential nc)
{
lock (LockObject)
{
for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
{
if ((authAvail & s_authSchemePriorityOrder[i]) != 0)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
try
{
_credentialCache.Add(serverUri, s_authenticationSchemes[i], nc);
}
catch(ArgumentException)
{
//Ignore the case of key already present
}
}
}
}
}
private void AddResponseCookies(Uri serverUri, HttpResponseMessage response)
{
if (!_useCookie)
{
return;
}
if (response.Headers.Contains(HttpKnownHeaderNames.SetCookie))
{
IEnumerable<string> cookieHeaders = response.Headers.GetValues(HttpKnownHeaderNames.SetCookie);
foreach (var cookieHeader in cookieHeaders)
{
try
{
_cookieContainer.SetCookies(serverUri, cookieHeader);
}
catch (CookieException e)
{
string msg = string.Format("Malformed cookie: SetCookies Failed with {0}, server: {1}, cookie:{2}",
e.Message,
serverUri.OriginalString,
cookieHeader);
VerboseTrace(msg);
}
}
}
}
private static KeyValuePair<NetworkCredential, ulong> GetCredentials(ICredentials credentials, Uri requestUri)
{
NetworkCredential nc = null;
ulong curlAuthScheme = CURLAUTH.None;
if (credentials != null)
{
// we collect all the schemes that are accepted by libcurl for which there is a non-null network credential.
// But CurlHandler works under following assumption:
// for a given server, the credentials do not vary across authentication schemes.
for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
{
NetworkCredential networkCredential = credentials.GetCredential(requestUri, s_authenticationSchemes[i]);
if (networkCredential != null)
{
curlAuthScheme |= s_authSchemePriorityOrder[i];
if (nc == null)
{
nc = networkCredential;
}
else if(!AreEqualNetworkCredentials(nc, networkCredential))
{
throw new PlatformNotSupportedException(SR.net_http_unix_invalid_credential);
}
}
}
}
VerboseTrace("curlAuthScheme = " + curlAuthScheme);
return new KeyValuePair<NetworkCredential, ulong>(nc, curlAuthScheme); ;
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_anyOperationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private static void ThrowIfCURLEError(int error)
{
if (error != CURLcode.CURLE_OK)
{
var inner = new CurlException(error, isMulti: false);
VerboseTrace(inner.Message);
throw inner;
}
}
private static void ThrowIfCURLMError(int error)
{
if (error != CURLMcode.CURLM_OK)
{
string msg = CurlException.GetCurlErrorString(error, true);
VerboseTrace(msg);
switch (error)
{
case CURLMcode.CURLM_ADDED_ALREADY:
case CURLMcode.CURLM_BAD_EASY_HANDLE:
case CURLMcode.CURLM_BAD_HANDLE:
case CURLMcode.CURLM_BAD_SOCKET:
throw new ArgumentException(msg);
case CURLMcode.CURLM_UNKNOWN_OPTION:
throw new ArgumentOutOfRangeException(msg);
case CURLMcode.CURLM_OUT_OF_MEMORY:
throw new OutOfMemoryException(msg);
case CURLMcode.CURLM_INTERNAL_ERROR:
default:
throw new CurlException(error, msg);
}
}
}
private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2)
{
Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check");
return credential1.UserName == credential2.UserName &&
credential1.Domain == credential2.Domain &&
string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal);
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null, MultiAgent agent = null)
{
// If we weren't handed a multi agent, see if we can get one from the EasyRequest
if (agent == null && easy != null && easy._associatedMultiAgent != null)
{
agent = easy._associatedMultiAgent;
}
int? agentId = agent != null ? agent.RunningWorkerId : null;
// Get an ID string that provides info about which MultiAgent worker and which EasyRequest this trace is about
string ids = "";
if (agentId != null || easy != null)
{
ids = "(" +
(agentId != null ? "M#" + agentId : "") +
(agentId != null && easy != null ? ", " : "") +
(easy != null ? "E#" + easy.Task.Id : "") +
")";
}
// Create the message and trace it out
string msg = string.Format("[{0, -30}]{1, -16}: {2}", memberName, ids, text);
Interop.Sys.PrintF("%s\n", msg);
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
if (condition)
{
VerboseTrace(text, memberName, easy, agent: null);
}
}
private static Exception CreateHttpRequestException(Exception inner = null)
{
return new HttpRequestException(SR.net_http_client_execution_error, inner);
}
private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state)
{
if (!responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection).
response.Headers.Clear();
response.Content.Headers.Clear();
int responseHeaderLength = responseHeader.Length;
// Check if line begins with HTTP/1.1 or HTTP/1.0
int prefixLength = HttpPrefix.Length;
int versionIndex = prefixLength + 2;
if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.'))
{
response.Version =
responseHeader[versionIndex] == '1' ? HttpVersion.Version11 :
responseHeader[versionIndex] == '0' ? HttpVersion.Version10 :
new Version(0, 0);
}
else
{
response.Version = new Version(0, 0);
}
// TODO: Parsing errors are treated as fatal. Find right behaviour
int spaceIndex = responseHeader.IndexOf(SpaceChar);
if (spaceIndex > -1)
{
int codeStartIndex = spaceIndex + 1;
int statusCode = 0;
// Parse first 3 characters after a space as status code
if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode))
{
response.StatusCode = (HttpStatusCode)statusCode;
int codeEndIndex = codeStartIndex + StatusCodeLength;
int reasonPhraseIndex = codeEndIndex + 1;
if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar)
{
int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex);
int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength;
response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex);
}
state._isRedirect = state._handler.AutomaticRedirection &&
(response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.RedirectKeepVerb ||
response.StatusCode == HttpStatusCode.RedirectMethod) ;
}
}
return true;
}
private static bool TryParseStatusCode(string responseHeader, int statusCodeStartIndex, out int statusCode)
{
if (statusCodeStartIndex + StatusCodeLength > responseHeader.Length)
{
statusCode = 0;
return false;
}
char c100 = responseHeader[statusCodeStartIndex];
char c10 = responseHeader[statusCodeStartIndex + 1];
char c1 = responseHeader[statusCodeStartIndex + 2];
if (c100 < '0' || c100 > '9' ||
c10 < '0' || c10 > '9' ||
c1 < '0' || c1 > '9')
{
statusCode = 0;
return false;
}
statusCode = (c100 - '0') * 100 + (c10 - '0') * 10 + (c1 - '0');
return true;
}
private static void HandleRedirectLocationHeader(EasyRequest state, string locationValue)
{
Debug.Assert(state._isRedirect);
Debug.Assert(state._handler.AutomaticRedirection);
string location = locationValue.Trim();
//only for absolute redirects
Uri forwardUri;
if (Uri.TryCreate(location, UriKind.RelativeOrAbsolute, out forwardUri) && forwardUri.IsAbsoluteUri)
{
KeyValuePair<NetworkCredential, ulong> ncAndScheme = GetCredentials(state._handler.Credentials as CredentialCache, forwardUri);
if (ncAndScheme.Key != null)
{
state.SetCredentialsOptions(ncAndScheme);
}
else
{
state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
}
// reset proxy - it is possible that the proxy has different credentials for the new URI
state.SetProxyOptions(forwardUri);
if (state._handler._useCookie)
{
// reset cookies.
state.SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero);
// set cookies again
state.SetCookieOption(forwardUri);
}
}
}
private static void SetChunkedModeForSend(HttpRequestMessage request)
{
bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault();
HttpContent requestContent = request.Content;
Debug.Assert(requestContent != null, "request is null");
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// libcurl adds a Tranfer-Encoding header by default and the request fails if both are set.
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Same behaviour as WinHttpHandler
requestContent.Headers.ContentLength = null;
}
else
{
// Prevent libcurl from adding Transfer-Encoding header
request.Headers.TransferEncodingChunked = false;
}
}
else if (!chunkedMode)
{
// Make sure Transfer-Encoding: chunked header is set,
// as we have content to send but no known length for it.
request.Headers.TransferEncodingChunked = true;
}
}
#endregion
private enum ProxyUsePolicy
{
DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment.
UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any.
UseCustomProxy = 2 // Use The proxy specified by the user.
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using Launchpad.Launcher.Events.Arguments;
using Launchpad.Launcher.Events.Delegates;
/*
* This class has a lot of async stuff going on. It handles updating the launcher
* and loading the changelog from the server.
* Since this class starts new threads in which it does the larger computations,
* there must be no useage of UI code in this class. Keep it clean!
*
*/
namespace Launchpad.Launcher
{
/// <summary>
/// This class has a lot of async stuff going on. It handles updating the launcher
/// and loading the changelog from the server.
/// Since this class starts new threads in which it does the larger computations,
/// there must be no useage of UI code in this class. Keep it clean!
/// </summary>
internal sealed class LauncherHandler
{
/// <summary>
/// Occurs when changelog download progress changes.
/// </summary>
public event ChangelogProgressChangedEventHandler ChangelogProgressChanged;
/// <summary>
/// Occurs when changelog download finishes.
/// </summary>
public event ChangelogDownloadFinishedEventHandler ChangelogDownloadFinished;
/// <summary>
/// The progress arguments object. Is updated during file download operations.
/// </summary>
private FileDownloadProgressChangedEventArgs ProgressArgs;
/// <summary>
/// The download finished arguments object. Is updated once a file download finishes.
/// </summary>
private GameDownloadFinishedEventArgs DownloadFinishedArgs;
/// <summary>
/// The config handler reference.
/// </summary>
ConfigHandler Config = ConfigHandler._instance;
/// <summary>
/// Initializes a new instance of the <see cref="Launchpad_Launcher.LauncherHandler"/> class.
/// </summary>
public LauncherHandler ()
{
ProgressArgs = new FileDownloadProgressChangedEventArgs ();
DownloadFinishedArgs = new GameDownloadFinishedEventArgs ();
}
//TODO: Update this function to handle DLLs as well. May have to implement a full-blown
//manifest system here as well.
/// <summary>
/// Updates the launcher synchronously.
/// </summary>
public void UpdateLauncher()
{
try
{
FTPHandler FTP = new FTPHandler ();
//crawl the server for all of the files in the /launcher/bin directory.
List<string> remotePaths = FTP.GetFilePaths(Config.GetLauncherBinariesURL(), true);
//download all of them
foreach (string path in remotePaths)
{
try
{
if (!String.IsNullOrEmpty(path))
{
string Local = String.Format("{0}launchpad{1}{2}",
ConfigHandler.GetTempDir(),
Path.DirectorySeparatorChar,
path);
string Remote = String.Format("{0}{1}",
Config.GetLauncherBinariesURL(),
path);
if (!Directory.Exists(Local))
{
Directory.CreateDirectory(Directory.GetParent(Local).ToString());
}
FTP.DownloadFTPFile(Remote, Local, false);
}
}
catch (WebException wex)
{
Console.WriteLine("WebException in UpdateLauncher(): " + wex.Message);
}
}
//TODO: Make the script copy recursively
ProcessStartInfo script = CreateUpdateScript ();
Process.Start(script);
Environment.Exit(0);
}
catch (IOException ioex)
{
Console.WriteLine ("IOException in UpdateLauncher(): " + ioex.Message);
}
}
/// <summary>
/// Downloads the manifest.
/// </summary>
public void DownloadManifest()
{
Stream manifestStream = null;
try
{
FTPHandler FTP = new FTPHandler ();
string remoteChecksum = FTP.GetRemoteManifestChecksum ();
string localChecksum = "";
string RemoteURL = Config.GetManifestURL ();
string LocalPath = ConfigHandler.GetManifestPath ();
if (File.Exists(ConfigHandler.GetManifestPath()))
{
manifestStream = File.OpenRead (ConfigHandler.GetManifestPath ());
localChecksum = MD5Handler.GetFileHash(manifestStream);
if (!(remoteChecksum == localChecksum))
{
//Copy the old manifest so that we can compare them when updating the game
File.Copy(LocalPath, LocalPath + ".old", true);
FTP.DownloadFTPFile (RemoteURL, LocalPath, false);
}
}
else
{
FTP.DownloadFTPFile (RemoteURL, LocalPath, false);
}
}
catch (IOException ioex)
{
Console.WriteLine ("IOException in DownloadManifest(): " + ioex.Message);
}
finally
{
if (manifestStream != null)
{
manifestStream.Close ();
}
}
}
/// <summary>
/// Gets the changelog from the server asynchronously.
/// </summary>
public void LoadChangelog()
{
Thread t = new Thread (LoadChangelogAsync);
t.Start ();
}
private void LoadChangelogAsync()
{
FTPHandler FTP = new FTPHandler ();
//load the HTML from the server as a string
string content = FTP.ReadFTPFile (Config.GetChangelogURL ());
OnChangelogProgressChanged();
DownloadFinishedArgs.Result = content;
DownloadFinishedArgs.Metadata = Config.GetChangelogURL ();
OnChangelogDownloadFinished ();
}
/// <summary>
/// Creates the update script on disk.
/// </summary>
/// <returns>ProcessStartInfo for the update script.</returns>
private static ProcessStartInfo CreateUpdateScript()
{
try
{
//maintain the executable name if it was renamed to something other than 'Launchpad'
string fullName = Assembly.GetEntryAssembly().Location;
string executableName = Path.GetFileName(fullName); // should be "Launchpad", unless the user has renamed it
if (ChecksHandler.IsRunningOnUnix())
{
//creating a .sh script
string scriptPath = String.Format (@"{0}launchpadupdate.sh",
ConfigHandler.GetTempDir ()) ;
FileStream updateScript = File.Create (scriptPath);
TextWriter tw = new StreamWriter (updateScript);
//write commands to the script
//wait five seconds, then copy the new executable
string copyCom = String.Format ("cp -rf {0} {1}",
ConfigHandler.GetTempDir() + "launchpad/*",
ConfigHandler.GetLocalDir());
string delCom = String.Format ("rm -rf {0}",
ConfigHandler.GetTempDir() + "launchpad");
string dirCom = String.Format ("cd {0}", ConfigHandler.GetLocalDir ());
string launchCom = String.Format (@"nohup ./{0} &", executableName);
tw.WriteLine (@"#!/bin/sh");
tw.WriteLine ("sleep 5");
tw.WriteLine (copyCom);
tw.WriteLine (delCom);
tw.WriteLine (dirCom);
tw.WriteLine("chmod +x " + executableName);
tw.WriteLine (launchCom);
tw.Close();
UnixHandler.MakeExecutable(scriptPath);
//Now create some ProcessStartInfo for this script
ProcessStartInfo updateShellProcess = new ProcessStartInfo ();
updateShellProcess.FileName = scriptPath;
updateShellProcess.UseShellExecute = false;
updateShellProcess.RedirectStandardOutput = false;
updateShellProcess.WindowStyle = ProcessWindowStyle.Hidden;
return updateShellProcess;
}
else
{
//creating a .bat script
string scriptPath = String.Format (@"{0}launchpadupdate.bat",
ConfigHandler.GetTempDir ());
FileStream updateScript = File.Create(scriptPath);
TextWriter tw = new StreamWriter(updateScript);
//write commands to the script
//wait three seconds, then copy the new executable
tw.WriteLine(String.Format(@"timeout 3 & xcopy /e /s /y ""{0}\launchpad"" ""{1}"" && rmdir /s /q {0}\launchpad",
ConfigHandler.GetTempDir(),
ConfigHandler.GetLocalDir()));
//then start the new executable
tw.WriteLine(String.Format(@"start {0}", executableName));
tw.Close();
ProcessStartInfo updateBatchProcess = new ProcessStartInfo();
updateBatchProcess.FileName = scriptPath;
updateBatchProcess.UseShellExecute = true;
updateBatchProcess.RedirectStandardOutput = false;
updateBatchProcess.WindowStyle = ProcessWindowStyle.Hidden;
return updateBatchProcess;
}
}
catch (IOException ioex)
{
Console.WriteLine ("IOException in CreateUpdateScript(): " + ioex.Message);
return null;
}
}
/// <summary>
/// Raises the changelog progress changed event.
/// Fires once after the changelog has been downloaded, but the values have not been assigned yet.
/// </summary>
private void OnChangelogProgressChanged()
{
if (ChangelogProgressChanged != null)
{
//raise the event
ChangelogProgressChanged (this, ProgressArgs);
}
}
/// <summary>
/// Raises the changelog download finished event.
/// Fires when the changelog has finished downloading and all values have been assigned.
/// </summary>
private void OnChangelogDownloadFinished()
{
if (ChangelogDownloadFinished != null)
{
//raise the event
ChangelogDownloadFinished (this, DownloadFinishedArgs);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Sprite/tk2dSprite")]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[ExecuteInEditMode]
/// <summary>
/// Sprite implementation which maintains its own Unity Mesh. Leverages dynamic batching.
/// </summary>
public class tk2dSprite : tk2dBaseSprite
{
Mesh mesh;
Vector3[] meshVertices;
Vector3[] meshNormals = null;
Vector4[] meshTangents = null;
Color32[] meshColors;
new void Awake()
{
base.Awake();
// Create mesh, independently to everything else
mesh = new Mesh();
#if !UNITY_3_5
mesh.MarkDynamic();
#endif
mesh.hideFlags = HideFlags.DontSave;
GetComponent<MeshFilter>().mesh = mesh;
// This will not be set when instantiating in code
// In that case, Build will need to be called
if (Collection)
{
// reset spriteId if outside bounds
// this is when the sprite collection data is corrupt
if (_spriteId < 0 || _spriteId >= Collection.Count)
_spriteId = 0;
Build();
}
}
protected void OnDestroy()
{
if (mesh)
{
#if UNITY_EDITOR
DestroyImmediate(mesh);
#else
Destroy(mesh);
#endif
}
if (meshColliderMesh)
{
#if UNITY_EDITOR
DestroyImmediate(meshColliderMesh);
#else
Destroy(meshColliderMesh);
#endif
}
}
public override void Build()
{
var sprite = collectionInst.spriteDefinitions[spriteId];
meshVertices = new Vector3[sprite.positions.Length];
meshColors = new Color32[sprite.positions.Length];
meshNormals = new Vector3[0];
meshTangents = new Vector4[0];
if (sprite.normals != null && sprite.normals.Length > 0)
{
meshNormals = new Vector3[sprite.normals.Length];
}
if (sprite.tangents != null && sprite.tangents.Length > 0)
{
meshTangents = new Vector4[sprite.tangents.Length];
}
SetPositions(meshVertices, meshNormals, meshTangents);
SetColors(meshColors);
if (mesh == null)
{
mesh = new Mesh();
#if !UNITY_3_5
mesh.MarkDynamic();
#endif
mesh.hideFlags = HideFlags.DontSave;
GetComponent<MeshFilter>().mesh = mesh;
}
mesh.Clear();
mesh.vertices = meshVertices;
mesh.normals = meshNormals;
mesh.tangents = meshTangents;
mesh.colors32 = meshColors;
mesh.uv = sprite.uvs;
mesh.triangles = sprite.indices;
mesh.bounds = AdjustedMeshBounds( GetBounds(), renderLayer );
UpdateMaterial();
CreateCollider();
}
/// <summary>
/// Adds a tk2dSprite as a component to the gameObject passed in, setting up necessary parameters and building geometry.
/// Convenience alias of tk2dBaseSprite.AddComponent<tk2dSprite>(...).
/// </summary>
public static tk2dSprite AddComponent(GameObject go, tk2dSpriteCollectionData spriteCollection, int spriteId)
{
return tk2dBaseSprite.AddComponent<tk2dSprite>(go, spriteCollection, spriteId);
}
/// <summary>
/// Adds a tk2dSprite as a component to the gameObject passed in, setting up necessary parameters and building geometry.
/// Convenience alias of tk2dBaseSprite.AddComponent<tk2dSprite>(...).
/// </summary>
public static tk2dSprite AddComponent(GameObject go, tk2dSpriteCollectionData spriteCollection, string spriteName)
{
return tk2dBaseSprite.AddComponent<tk2dSprite>(go, spriteCollection, spriteName);
}
/// <summary>
/// Create a sprite (and gameObject) displaying the region of the texture specified.
/// Use <see cref="tk2dSpriteCollectionData.CreateFromTexture"/> if you need to create a sprite collection
/// with multiple sprites. It is your responsibility to destroy the collection when you
/// destroy this sprite game object. You can get to it by using sprite.Collection.
/// Convenience alias of tk2dBaseSprite.CreateFromTexture<tk2dSprite>(...)
/// </summary>
public static GameObject CreateFromTexture(Texture texture, tk2dSpriteCollectionSize size, Rect region, Vector2 anchor)
{
return tk2dBaseSprite.CreateFromTexture<tk2dSprite>(texture, size, region, anchor);
}
protected override void UpdateGeometry() { UpdateGeometryImpl(); }
protected override void UpdateColors() { UpdateColorsImpl(); }
protected override void UpdateVertices() { UpdateVerticesImpl(); }
protected void UpdateColorsImpl()
{
// This can happen with prefabs in the inspector
if (mesh == null || meshColors == null || meshColors.Length == 0)
return;
SetColors(meshColors);
mesh.colors32 = meshColors;
}
protected void UpdateVerticesImpl()
{
var sprite = collectionInst.spriteDefinitions[spriteId];
// This can happen with prefabs in the inspector
if (mesh == null || meshVertices == null || meshVertices.Length == 0)
return;
// Clear out normals and tangents when switching from a sprite with them to one without
if (sprite.normals.Length != meshNormals.Length)
{
meshNormals = (sprite.normals != null && sprite.normals.Length > 0)?(new Vector3[sprite.normals.Length]):(new Vector3[0]);
}
if (sprite.tangents.Length != meshTangents.Length)
{
meshTangents = (sprite.tangents != null && sprite.tangents.Length > 0)?(new Vector4[sprite.tangents.Length]):(new Vector4[0]);
}
SetPositions(meshVertices, meshNormals, meshTangents);
mesh.vertices = meshVertices;
mesh.normals = meshNormals;
mesh.tangents = meshTangents;
mesh.uv = sprite.uvs;
mesh.bounds = AdjustedMeshBounds( GetBounds(), renderLayer );
}
protected void UpdateGeometryImpl()
{
// This can happen with prefabs in the inspector
if (mesh == null)
return;
var sprite = collectionInst.spriteDefinitions[spriteId];
if (meshVertices == null || meshVertices.Length != sprite.positions.Length)
{
meshVertices = new Vector3[sprite.positions.Length];
meshColors = new Color32[sprite.positions.Length];
}
if (meshNormals == null || (sprite.normals != null && meshNormals.Length != sprite.normals.Length))
{
meshNormals = new Vector3[sprite.normals.Length];
}
else if (sprite.normals == null)
{
meshNormals = new Vector3[0];
}
if (meshTangents == null || (sprite.tangents != null && meshTangents.Length != sprite.tangents.Length))
{
meshTangents = new Vector4[sprite.tangents.Length];
}
else if (sprite.tangents == null)
{
meshTangents = new Vector4[0];
}
SetPositions(meshVertices, meshNormals, meshTangents);
SetColors(meshColors);
mesh.Clear();
mesh.vertices = meshVertices;
mesh.normals = meshNormals;
mesh.tangents = meshTangents;
mesh.colors32 = meshColors;
mesh.uv = sprite.uvs;
mesh.bounds = AdjustedMeshBounds( GetBounds(), renderLayer );
mesh.triangles = sprite.indices;
}
protected override void UpdateMaterial()
{
Renderer renderer = GetComponent<Renderer>();
if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst)
renderer.material = collectionInst.spriteDefinitions[spriteId].materialInst;
}
protected override int GetCurrentVertexCount()
{
if (meshVertices == null)
return 0;
// Really nasty bug here found by Andrew Welch.
return meshVertices.Length;
}
#if UNITY_EDITOR
void OnDrawGizmos() {
if (collectionInst != null && spriteId >= 0 && spriteId < collectionInst.Count) {
var sprite = collectionInst.spriteDefinitions[spriteId];
Gizmos.color = Color.clear;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawCube(Vector3.Scale(sprite.untrimmedBoundsData[0], _scale), Vector3.Scale(sprite.untrimmedBoundsData[1], _scale));
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = Color.white;
}
}
#endif
public override void ForceBuild()
{
base.ForceBuild();
GetComponent<MeshFilter>().mesh = mesh;
}
public override void ReshapeBounds(Vector3 dMin, Vector3 dMax) {
float minSizeClampTexelScale = 0.1f; // Can't shrink sprite smaller than this many texels
// Irrespective of transform
var sprite = CurrentSprite;
Vector3 oldAbsScale = new Vector3(Mathf.Abs(_scale.x), Mathf.Abs(_scale.y), Mathf.Abs(_scale.z));
Vector3 oldMin = Vector3.Scale(sprite.untrimmedBoundsData[0], _scale) - 0.5f * Vector3.Scale(sprite.untrimmedBoundsData[1], oldAbsScale);
Vector3 oldSize = Vector3.Scale(sprite.untrimmedBoundsData[1], oldAbsScale);
Vector3 newAbsScale = oldSize + dMax - dMin;
newAbsScale.x /= sprite.untrimmedBoundsData[1].x;
newAbsScale.y /= sprite.untrimmedBoundsData[1].y;
// Clamp the minimum size to avoid having the pivot move when we scale from near-zero
if (sprite.untrimmedBoundsData[1].x * newAbsScale.x < sprite.texelSize.x * minSizeClampTexelScale && newAbsScale.x < oldAbsScale.x) {
dMin.x = 0;
newAbsScale.x = oldAbsScale.x;
}
if (sprite.untrimmedBoundsData[1].y * newAbsScale.y < sprite.texelSize.y * minSizeClampTexelScale && newAbsScale.y < oldAbsScale.y) {
dMin.y = 0;
newAbsScale.y = oldAbsScale.y;
}
// Add our wanted local dMin offset, while negating the positional offset caused by scaling
Vector2 scaleFactor = new Vector3(Mathf.Approximately(oldAbsScale.x, 0) ? 0 : (newAbsScale.x / oldAbsScale.x),
Mathf.Approximately(oldAbsScale.y, 0) ? 0 : (newAbsScale.y / oldAbsScale.y));
Vector3 scaledMin = new Vector3(oldMin.x * scaleFactor.x, oldMin.y * scaleFactor.y);
Vector3 offset = dMin + oldMin - scaledMin;
offset.z = 0;
transform.position = transform.TransformPoint(offset);
scale = new Vector3(_scale.x * scaleFactor.x, _scale.y * scaleFactor.y, _scale.z);
}
}
| |
// 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 Cake.Common.Tests.Fixtures.Tools.GitReleaseManager;
using Cake.Testing;
using Cake.Testing.Xunit;
using Xunit;
namespace Cake.Common.Tests.Unit.Tools.GitReleaseManager.Label
{
public sealed class GitReleaseManagerLabellerTests
{
public sealed class TheLabelMethod
{
[Fact]
public void Should_Throw_If_UserName_Is_Null()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UserName = string.Empty;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "userName");
}
[Fact]
public void Should_Throw_If_Password_Is_Null()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.Password = string.Empty;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "password");
}
[Fact]
public void Should_Throw_If_Token_Is_Null()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.Token = string.Empty;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "token");
}
[Fact]
public void Should_Throw_If_Owner_Is_Null()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.Owner = string.Empty;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "owner");
}
[Fact]
public void Should_Throw_If_Owner_Is_Null_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.Owner = string.Empty;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "owner");
}
[Fact]
public void Should_Throw_If_Repository_Is_Null()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.Repository = string.Empty;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "repository");
}
[Fact]
public void Should_Throw_If_Repository_Is_Null_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.Repository = string.Empty;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "repository");
}
[Fact]
public void Should_Throw_If_Settings_Are_Null()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.Settings = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "settings");
}
[Fact]
public void Should_Throw_If_Settings_Are_Null_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.Settings = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "settings");
}
[Fact]
public void Should_Throw_If_GitReleaseManager_Executable_Was_Not_Found()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.GivenDefaultToolDoNotExist();
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsCakeException(result, "GitReleaseManager: Could not locate executable.");
}
[Fact]
public void Should_Throw_If_GitReleaseManager_Executable_Was_Not_Found_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.GivenDefaultToolDoNotExist();
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsCakeException(result, "GitReleaseManager: Could not locate executable.");
}
[Theory]
[InlineData("/bin/tools/GitReleaseManager/GitReleaseManager.exe", "/bin/tools/GitReleaseManager/GitReleaseManager.exe")]
[InlineData("./tools/GitReleaseManager/GitReleaseManager.exe", "/Working/tools/GitReleaseManager/GitReleaseManager.exe")]
public void Should_Use_GitReleaseManager_Executable_From_Tool_Path_If_Provided(string toolPath, string expected)
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.Settings.ToolPath = toolPath;
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
[Theory]
[InlineData("/bin/tools/GitReleaseManager/GitReleaseManager.exe", "/bin/tools/GitReleaseManager/GitReleaseManager.exe")]
[InlineData("./tools/GitReleaseManager/GitReleaseManager.exe", "/Working/tools/GitReleaseManager/GitReleaseManager.exe")]
public void Should_Use_GitReleaseManager_Executable_From_Tool_Path_If_Provided_When_Using_Token(string toolPath, string expected)
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.Settings.ToolPath = toolPath;
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
[WindowsTheory]
[InlineData("C:/GitReleaseManager/GitReleaseManager.exe", "C:/GitReleaseManager/GitReleaseManager.exe")]
public void Should_Use_GitReleaseManager_Executable_From_Tool_Path_If_Provided_On_Windows(string toolPath, string expected)
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.Settings.ToolPath = toolPath;
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
[WindowsTheory]
[InlineData("C:/GitReleaseManager/GitReleaseManager.exe", "C:/GitReleaseManager/GitReleaseManager.exe")]
public void Should_Use_GitReleaseManager_Executable_From_Tool_Path_If_Provided_On_Windows_When_Using_Token(string toolPath, string expected)
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.Settings.ToolPath = toolPath;
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
[Fact]
public void Should_Throw_If_Process_Was_Not_Started()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.GivenProcessCannotStart();
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsCakeException(result, "GitReleaseManager: Process was not started.");
}
[Fact]
public void Should_Throw_If_Process_Was_Not_Started_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.GivenProcessCannotStart();
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsCakeException(result, "GitReleaseManager: Process was not started.");
}
[Fact]
public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.GivenProcessExitsWithCode(1);
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsCakeException(result, "GitReleaseManager: Process returned an error (exit code 1).");
}
[Fact]
public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.GivenProcessExitsWithCode(1);
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsCakeException(result, "GitReleaseManager: Process returned an error (exit code 1).");
}
[Fact]
public void Should_Find_GitReleaseManager_Executable_If_Tool_Path_Not_Provided()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
// When
var result = fixture.Run();
// Then
Assert.Equal("/Working/tools/GitReleaseManager.exe", result.Path.FullPath);
}
[Fact]
public void Should_Find_GitReleaseManager_Executable_If_Tool_Path_Not_Provided_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
// When
var result = fixture.Run();
// Then
Assert.Equal("/Working/tools/GitReleaseManager.exe", result.Path.FullPath);
}
[Fact]
public void Should_Add_Mandatory_Arguments()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
// When
var result = fixture.Run();
// Then
Assert.Equal("label -u \"bob\" -p \"password\" " +
"-o \"repoOwner\" -r \"repo\"", result.Args);
}
[Fact]
public void Should_Add_Mandatory_Arguments_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
// When
var result = fixture.Run();
// Then
Assert.Equal("label --token \"token\" " +
"-o \"repoOwner\" -r \"repo\"", result.Args);
}
[Fact]
public void Should_Add_TargetDirectory_To_Arguments_If_Set()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.Settings.TargetDirectory = @"/temp";
// When
var result = fixture.Run();
// Then
Assert.Equal("label -u \"bob\" -p \"password\" " +
"-o \"repoOwner\" -r \"repo\" -d \"/temp\"", result.Args);
}
[Fact]
public void Should_Add_TargetDirectory_To_Arguments_If_Set_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.Settings.TargetDirectory = @"/temp";
// When
var result = fixture.Run();
// Then
Assert.Equal("label --token \"token\" " +
"-o \"repoOwner\" -r \"repo\" -d \"/temp\"", result.Args);
}
[Fact]
public void Should_Add_LogFilePath_To_Arguments_If_Set()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.Settings.LogFilePath = @"/temp/log.txt";
// When
var result = fixture.Run();
// Then
Assert.Equal("label -u \"bob\" -p \"password\" " +
"-o \"repoOwner\" -r \"repo\" " +
"-l \"/temp/log.txt\"", result.Args);
}
[Fact]
public void Should_Add_LogFilePath_To_Arguments_If_Set_When_Using_Token()
{
// Given
var fixture = new GitReleaseManagerLabellerFixture();
fixture.UseToken();
fixture.Settings.LogFilePath = @"/temp/log.txt";
// When
var result = fixture.Run();
// Then
Assert.Equal("label --token \"token\" " +
"-o \"repoOwner\" -r \"repo\" " +
"-l \"/temp/log.txt\"", result.Args);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.UserModel
{
using System;
public class CellCopyPolicy
{
// cell-level policies
public static bool DEFAULT_COPY_CELL_VALUE_POLICY = true;
public static bool DEFAULT_COPY_CELL_STYLE_POLICY = true;
public static bool DEFAULT_COPY_CELL_FORMULA_POLICY = true;
public static bool DEFAULT_COPY_HYPERLINK_POLICY = true;
public static bool DEFAULT_MERGE_HYPERLINK_POLICY = false;
// row-level policies
public static bool DEFAULT_COPY_ROW_HEIGHT_POLICY = true;
public static bool DEFAULT_CONDENSE_ROWS_POLICY = false;
// sheet-level policies
public static bool DEFAULT_COPY_MERGED_REGIONS_POLICY = true;
// cell-level policies
private bool copyCellValue = DEFAULT_COPY_CELL_VALUE_POLICY;
private bool copyCellStyle = DEFAULT_COPY_CELL_STYLE_POLICY;
private bool copyCellFormula = DEFAULT_COPY_CELL_FORMULA_POLICY;
private bool copyHyperlink = DEFAULT_COPY_HYPERLINK_POLICY;
private bool mergeHyperlink = DEFAULT_MERGE_HYPERLINK_POLICY;
// row-level policies
private bool copyRowHeight = DEFAULT_COPY_ROW_HEIGHT_POLICY;
private bool condenseRows = DEFAULT_CONDENSE_ROWS_POLICY;
// sheet-level policies
private bool copyMergedRegions = DEFAULT_COPY_MERGED_REGIONS_POLICY;
/**
* Default CellCopyPolicy, uses default policy
* For custom CellCopyPolicy, use {@link Builder} class
*/
public CellCopyPolicy() { }
/**
* Copy constructor
*
* @param other policy to copy
*/
public CellCopyPolicy(CellCopyPolicy other)
{
copyCellValue = other.IsCopyCellValue;
copyCellStyle = other.IsCopyCellStyle;
copyCellFormula = other.IsCopyCellFormula;
copyHyperlink = other.IsCopyHyperlink;
mergeHyperlink = other.IsMergeHyperlink;
copyRowHeight = other.IsCopyRowHeight;
condenseRows = other.IsCondenseRows;
copyMergedRegions = other.IsCopyMergedRegions;
}
// should builder be Replaced with CellCopyPolicy Setters that return the object
// to allow Setters to be chained together?
// policy.CopyCellValue=(/*setter*/true).CopyCellStyle=(/*setter*/true)
private CellCopyPolicy(Builder builder)
{
copyCellValue = builder.copyCellValue;
copyCellStyle = builder.copyCellStyle;
copyCellFormula = builder.copyCellFormula;
copyHyperlink = builder.copyHyperlink;
mergeHyperlink = builder.mergeHyperlink;
copyRowHeight = builder.copyRowHeight;
condenseRows = builder.condenseRows;
copyMergedRegions = builder.copyMergedRegions;
}
public class Builder
{
// cell-level policies
internal bool copyCellValue = DEFAULT_COPY_CELL_VALUE_POLICY;
internal bool copyCellStyle = DEFAULT_COPY_CELL_STYLE_POLICY;
internal bool copyCellFormula = DEFAULT_COPY_CELL_FORMULA_POLICY;
internal bool copyHyperlink = DEFAULT_COPY_HYPERLINK_POLICY;
internal bool mergeHyperlink = DEFAULT_MERGE_HYPERLINK_POLICY;
// row-level policies
internal bool copyRowHeight = DEFAULT_COPY_ROW_HEIGHT_POLICY;
internal bool condenseRows = DEFAULT_CONDENSE_ROWS_POLICY;
// sheet-level policies
internal bool copyMergedRegions = DEFAULT_COPY_MERGED_REGIONS_POLICY;
/**
* Builder class for CellCopyPolicy
*/
public Builder()
{
}
// cell-level policies
public Builder CellValue(bool copyCellValue)
{
this.copyCellValue = copyCellValue;
return this;
}
public Builder CellStyle(bool copyCellStyle)
{
this.copyCellStyle = copyCellStyle;
return this;
}
public Builder CellFormula(bool copyCellFormula)
{
this.copyCellFormula = copyCellFormula;
return this;
}
public Builder CopyHyperlink(bool copyHyperlink)
{
this.copyHyperlink = copyHyperlink;
return this;
}
public Builder MergeHyperlink(bool mergeHyperlink)
{
this.mergeHyperlink = mergeHyperlink;
return this;
}
// row-level policies
public Builder RowHeight(bool copyRowHeight)
{
this.copyRowHeight = copyRowHeight;
return this;
}
public Builder CondenseRows(bool condenseRows)
{
this.condenseRows = condenseRows;
return this;
}
// sheet-level policies
public Builder MergedRegions(bool copyMergedRegions)
{
this.copyMergedRegions = copyMergedRegions;
return this;
}
public CellCopyPolicy Build()
{
return new CellCopyPolicy(this);
}
}
public Builder CreateBuilder()
{
Builder builder = new Builder()
.CellValue(copyCellValue)
.CellStyle(copyCellStyle)
.CellFormula(copyCellFormula)
.CopyHyperlink(copyHyperlink)
.MergeHyperlink(mergeHyperlink)
.RowHeight(copyRowHeight)
.CondenseRows(condenseRows)
.MergedRegions(copyMergedRegions);
return builder;
}
/*
* Cell-level policies
*/
/**
* @return the copyCellValue
*/
public bool IsCopyCellValue
{
get
{
return copyCellValue;
}
set
{
this.copyCellValue = value;
}
}
/**
* @return the copyCellStyle
*/
public bool IsCopyCellStyle
{
get
{
return copyCellStyle;
}
set
{
this.copyCellStyle = value;
}
}
/**
* @return the copyCellFormula
*/
public bool IsCopyCellFormula
{
get
{
return copyCellFormula;
}
set
{
this.copyCellFormula = value;
}
}
/**
* @return the copyHyperlink
*/
public bool IsCopyHyperlink
{
get
{
return copyHyperlink;
}
set
{
this.copyHyperlink = value;
}
}
/**
* @return the mergeHyperlink
*/
public bool IsMergeHyperlink
{
get
{
return mergeHyperlink;
}
set
{
this.mergeHyperlink = value;
}
}
/*
* Row-level policies
*/
/**
* @return the copyRowHeight
*/
public bool IsCopyRowHeight
{
get
{
return copyRowHeight;
}
set
{
this.copyRowHeight = value;
}
}
/**
* If condenseRows is true, a discontinuities in srcRows will be Removed when copied to destination
* For example:
* Sheet.CopyRows({Row(1), Row(2), Row(5)}, 11, policy) results in rows 1, 2, and 5
* being copied to rows 11, 12, and 13 if condenseRows is True, or rows 11, 11, 15 if condenseRows is false
* @return the condenseRows
*/
public bool IsCondenseRows
{
get
{
return condenseRows;
}
set
{
this.condenseRows = value;
}
}
/*
* Sheet-level policies
*/
/**
* @return the copyMergedRegions
*/
public bool IsCopyMergedRegions
{
get
{
return copyMergedRegions;
}
set
{
this.copyMergedRegions = value;
}
}
public CellCopyPolicy Clone()
{
return (CellCopyPolicy)this.MemberwiseClone();
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
namespace Multiverse.Patcher {
public delegate void UpdateHandler(object scriptCall);
public delegate void InvokeHandler(object scriptCall, object methodCall);
/// <summary>
/// This class wraps a call to javascript. We pass in the C# arguments
/// and the name of the javascript method to invoke.
/// </summary>
public class ScriptCall {
public string method;
public object[] args;
public ScriptCall(string method, object[] args) {
this.method = method;
this.args = args;
}
/// <summary>
/// Convert the argument array in a form that is usable from javascript
/// </summary>
/// <returns></returns>
public object[] GetScriptingArgs() {
object[] rv = new object[args.Length];
for (int i = 0; i < args.Length; ++i) {
if (args[i] is long) {
long val = (long)args[i];
rv[i] = (double)val;
} else {
rv[i] = args[i];
}
}
return rv;
}
public override string ToString() {
StringBuilder msg = new StringBuilder();
msg.AppendFormat("{0}(", this.method);
for (int i = 0; i < this.args.Length; ++i) {
if (i == (this.args.Length - 1))
msg.AppendFormat("'{0}'", this.args[i]);
else
msg.AppendFormat("'{0}', ", this.args[i]);
}
msg.Append(")");
return msg.ToString();
}
}
/// <summary>
/// This class wraps a call to some method. We pass in the arguments
/// and the name of the method to invoke.
/// </summary>
/// <remarks>
/// Unlike the ScriptCall class, this class is designed for methods
/// that have a CLR implementation.
/// </remarks>
public class MethodCall {
public Delegate method;
public object[] args;
public MethodCall(Delegate method, object[] args) {
this.method = method;
this.args = args;
}
public object[] GetMethodArgs() {
return args;
}
}
/// <summary>
/// This class is made available to the browser object.
/// </summary>
public class UpdateHelper {
UpdateManager parentForm;
public string FileFetchStartedMethod = "HandleFileFetchStarted";
public string FileFetchEndedMethod = "HandleFileFetchEnded";
public string FileAddedMethod = "HandleFileAdded";
public string FileModifiedMethod = "HandleFileModified";
public string FileIgnoredMethod = "HandleFileIgnored";
public string FileRemovedMethod = "HandleFileRemoved";
public string StateChangedMethod = "HandleStateChanged";
public string UpdateAbortedMethod = "HandleUpdateAborted";
public string UpdateStartedMethod = "HandleUpdateStarted";
public string UpdateCompletedMethod = "HandleUpdateCompleted";
public string UpdateProgressMethod = "HandleUpdateProgress";
public UpdateHelper(UpdateManager parent) {
parentForm = parent;
}
public void StartUpdate()
{
parentForm.StartUpdate();
}
public void AbortUpdate()
{
parentForm.AbortUpdate();
}
/// <summary>
/// Determine whether we need to update our media.
/// </summary>
/// <remarks>
/// This method is virtual, so that it can be overridden. The
/// LoginHelper class uses this to return false when we disable
/// media updates.
/// </remarks>
/// <returns>whether any files need to be updated</returns>
public virtual bool NeedUpdate()
{
return parentForm.NeedUpdate();
}
public void OnLoaded() {
parentForm.OnLoaded();
}
public void OK() {
parentForm.DialogResult = DialogResult.OK;
parentForm.Close();
}
public void Abort() {
parentForm.DialogResult = DialogResult.Abort;
parentForm.Close();
}
public UpdaterStatus GetUpdaterStatus()
{
return parentForm.UpdaterStatus;
}
public void HandleFileFetchStarted(object sender, UpdateFileStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(FileFetchStartedMethod, new object[] { status.file, status.length }));
}
// Called from the worker thread
public void HandleFileFetchEnded(object sender, UpdateFileStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(FileFetchEndedMethod, new object[] { status.file, status.length, status.compressedLength }));
}
// Called from the worker thread
public void HandleFileAdded(object sender, UpdateFileStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(FileAddedMethod, new object[] { status.file, status.length }));
}
// Called from the worker thread
public void HandleFileModified(object sender, UpdateFileStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(FileModifiedMethod, new object[] { status.file, status.length }));
}
// Called from the worker thread
public void HandleFileIgnored(object sender, UpdateFileStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(FileIgnoredMethod, new object[] { status.file, status.length }));
}
// Called from the worker thread
public void HandleFileRemoved(object sender, UpdateFileStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(FileRemovedMethod, new object[] { status.file, status.length }));
}
// Called from the worker thread
public void HandleStateChanged(object sender, int state) {
parentForm.AsyncInvokeScript(new ScriptCall(StateChangedMethod, new object[] { state }));
}
// Called from the worker thread
public void HandleUpdateAborted(object sender, UpdaterStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(UpdateAbortedMethod, new object[] { status.message }),
new MethodCall(new UpdateHandler(parentForm.Abort), new object[] { status.message }));
}
// Called from the worker thread
public void HandleUpdateStarted(object sender, UpdaterStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(UpdateStartedMethod, new object[] { status.bytes, status.files }));
}
// Called from the worker thread
public void HandleUpdateCompleted(object sender, UpdaterStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(UpdateCompletedMethod, new object[] { status.bytes, status.files, status.bytesFetched, status.bytesTransferred }));
}
// Called from the worker thread
public void HandleUpdateProgress(object sender, UpdaterStatus status)
{
parentForm.AsyncInvokeScript(new ScriptCall(UpdateProgressMethod, new object[] { status.bytesFetched }));
// System.Diagnostics.Trace.Write(string.Format("HandleUpdateProgress: {0}/{1}", status.bytesFetched, status.bytes));
}
public Version Version
{
get
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
return assembly.GetName().Version;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.Data;
using OrchardCore.Infrastructure.Cache;
using OrchardCore.Modules;
using OrchardCore.Roles.Models;
using OrchardCore.Security;
using YesSql;
namespace OrchardCore.Roles.Services
{
public class RoleStore : IRoleClaimStore<IRole>, IQueryableRoleStore<IRole>
{
private readonly ISession _session;
private readonly ISessionHelper _sessionHelper;
private readonly IScopedDistributedCache _scopedDistributedCache;
private readonly IServiceProvider _serviceProvider;
private readonly IStringLocalizer S;
private readonly ILogger _logger;
public RoleStore(
ISession session,
ISessionHelper sessionHelper,
IScopedDistributedCache scopedDistributedCache,
IServiceProvider serviceProvider,
IStringLocalizer<RoleStore> stringLocalizer,
ILogger<RoleStore> logger)
{
_session = session;
_sessionHelper = sessionHelper;
_scopedDistributedCache = scopedDistributedCache;
_serviceProvider = serviceProvider;
S = stringLocalizer;
_logger = logger;
}
public void Dispose()
{
}
public IQueryable<IRole> Roles => GetRolesAsync().GetAwaiter().GetResult().Roles.AsQueryable();
/// <summary>
/// Returns the document from the database to be updated.
/// </summary>
public Task<RolesDocument> LoadRolesAsync() => _sessionHelper.LoadForUpdateAsync<RolesDocument>();
/// <summary>
/// Returns the document from the cache or creates a new one. The result should not be updated.
/// </summary>
private async Task<RolesDocument> GetRolesAsync()
{
return await _scopedDistributedCache.GetOrSetAsync(() =>
{
return _sessionHelper.GetForCachingAsync<RolesDocument>();
});
}
private Task UpdateRolesAsync(RolesDocument roles)
{
roles.Serial++;
_session.Save(roles);
return _scopedDistributedCache.SetAsync(roles);
}
#region IRoleStore<IRole>
public async Task<IdentityResult> CreateAsync(IRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
var roles = await LoadRolesAsync();
roles.Roles.Add((Role)role);
await UpdateRolesAsync(roles);
return IdentityResult.Success;
}
public async Task<IdentityResult> DeleteAsync(IRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
var roleToRemove = (Role)role;
if (String.Equals(roleToRemove.NormalizedRoleName, "ANONYMOUS") ||
String.Equals(roleToRemove.NormalizedRoleName, "AUTHENTICATED"))
{
return IdentityResult.Failed(new IdentityError { Description = S["Can't delete system roles."] });
}
var roleRemovedEventHandlers = _serviceProvider.GetRequiredService<IEnumerable<IRoleRemovedEventHandler>>();
await roleRemovedEventHandlers.InvokeAsync((handler, roleToRemove) => handler.RoleRemovedAsync(roleToRemove.RoleName), roleToRemove, _logger);
var roles = await LoadRolesAsync();
roleToRemove = roles.Roles.FirstOrDefault(r => r.RoleName == roleToRemove.RoleName);
roles.Roles.Remove(roleToRemove);
await UpdateRolesAsync(roles);
return IdentityResult.Success;
}
public async Task<IRole> FindByIdAsync(string roleId, CancellationToken cancellationToken)
{
var roles = await GetRolesAsync();
var role = roles.Roles.FirstOrDefault(x => x.RoleName == roleId);
return role;
}
public async Task<IRole> FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken)
{
var roles = await GetRolesAsync();
var role = roles.Roles.FirstOrDefault(x => x.NormalizedRoleName == normalizedRoleName);
return role;
}
public Task<string> GetNormalizedRoleNameAsync(IRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
return Task.FromResult(((Role)role).NormalizedRoleName);
}
public Task<string> GetRoleIdAsync(IRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
return Task.FromResult(role.RoleName.ToUpperInvariant());
}
public Task<string> GetRoleNameAsync(IRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
return Task.FromResult(role.RoleName);
}
public Task SetNormalizedRoleNameAsync(IRole role, string normalizedName, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
((Role)role).NormalizedRoleName = normalizedName;
return Task.CompletedTask;
}
public Task SetRoleNameAsync(IRole role, string roleName, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
((Role)role).RoleName = roleName;
return Task.CompletedTask;
}
public async Task<IdentityResult> UpdateAsync(IRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
var roles = await LoadRolesAsync();
var existingRole = roles.Roles.FirstOrDefault(x => x.RoleName == role.RoleName);
roles.Roles.Remove(existingRole);
roles.Roles.Add((Role)role);
await UpdateRolesAsync(roles);
return IdentityResult.Success;
}
#endregion IRoleStore<IRole>
#region IRoleClaimStore<IRole>
public Task AddClaimAsync(IRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
((Role)role).RoleClaims.Add(new RoleClaim { ClaimType = claim.Type, ClaimValue = claim.Value });
return Task.CompletedTask;
}
public Task<IList<Claim>> GetClaimsAsync(IRole role, CancellationToken cancellationToken = default(CancellationToken))
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
return Task.FromResult<IList<Claim>>(((Role)role).RoleClaims.Select(x => x.ToClaim()).ToList());
}
public Task RemoveClaimAsync(IRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
((Role)role).RoleClaims.RemoveAll(x => x.ClaimType == claim.Type && x.ClaimValue == claim.Value);
return Task.CompletedTask;
}
#endregion IRoleClaimStore<IRole>
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Monitoring.V3.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedAlertPolicyServiceClientSnippets
{
/// <summary>Snippet for ListAlertPolicies</summary>
public void ListAlertPoliciesRequestObject()
{
// Snippet: ListAlertPolicies(ListAlertPoliciesRequest, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
ListAlertPoliciesRequest request = new ListAlertPoliciesRequest
{
ProjectName = ProjectName.FromProject("[PROJECT]"),
Filter = "",
OrderBy = "",
};
// Make the request
PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (AlertPolicy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAlertPoliciesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPoliciesAsync</summary>
public async Task ListAlertPoliciesRequestObjectAsync()
{
// Snippet: ListAlertPoliciesAsync(ListAlertPoliciesRequest, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
ListAlertPoliciesRequest request = new ListAlertPoliciesRequest
{
ProjectName = ProjectName.FromProject("[PROJECT]"),
Filter = "",
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((AlertPolicy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPolicies</summary>
public void ListAlertPolicies()
{
// Snippet: ListAlertPolicies(string, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]";
// Make the request
PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (AlertPolicy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAlertPoliciesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPoliciesAsync</summary>
public async Task ListAlertPoliciesAsync()
{
// Snippet: ListAlertPoliciesAsync(string, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]";
// Make the request
PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((AlertPolicy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPolicies</summary>
public void ListAlertPoliciesResourceNames1()
{
// Snippet: ListAlertPolicies(ProjectName, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
ProjectName name = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (AlertPolicy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAlertPoliciesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPoliciesAsync</summary>
public async Task ListAlertPoliciesResourceNames1Async()
{
// Snippet: ListAlertPoliciesAsync(ProjectName, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((AlertPolicy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPolicies</summary>
public void ListAlertPoliciesResourceNames2()
{
// Snippet: ListAlertPolicies(OrganizationName, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]");
// Make the request
PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (AlertPolicy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAlertPoliciesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPoliciesAsync</summary>
public async Task ListAlertPoliciesResourceNames2Async()
{
// Snippet: ListAlertPoliciesAsync(OrganizationName, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]");
// Make the request
PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((AlertPolicy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPolicies</summary>
public void ListAlertPoliciesResourceNames3()
{
// Snippet: ListAlertPolicies(FolderName, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
FolderName name = FolderName.FromFolder("[FOLDER]");
// Make the request
PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (AlertPolicy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAlertPoliciesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPoliciesAsync</summary>
public async Task ListAlertPoliciesResourceNames3Async()
{
// Snippet: ListAlertPoliciesAsync(FolderName, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
FolderName name = FolderName.FromFolder("[FOLDER]");
// Make the request
PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((AlertPolicy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPolicies</summary>
public void ListAlertPoliciesResourceNames4()
{
// Snippet: ListAlertPolicies(IResourceName, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (AlertPolicy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAlertPoliciesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAlertPoliciesAsync</summary>
public async Task ListAlertPoliciesResourceNames4Async()
{
// Snippet: ListAlertPoliciesAsync(IResourceName, string, int?, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((AlertPolicy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (AlertPolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (AlertPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetAlertPolicy</summary>
public void GetAlertPolicyRequestObject()
{
// Snippet: GetAlertPolicy(GetAlertPolicyRequest, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
// Make the request
AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(request);
// End snippet
}
/// <summary>Snippet for GetAlertPolicyAsync</summary>
public async Task GetAlertPolicyRequestObjectAsync()
{
// Snippet: GetAlertPolicyAsync(GetAlertPolicyRequest, CallSettings)
// Additional: GetAlertPolicyAsync(GetAlertPolicyRequest, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
// Make the request
AlertPolicy response = await alertPolicyServiceClient.GetAlertPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetAlertPolicy</summary>
public void GetAlertPolicy()
{
// Snippet: GetAlertPolicy(string, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/alertPolicies/[ALERT_POLICY]";
// Make the request
AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(name);
// End snippet
}
/// <summary>Snippet for GetAlertPolicyAsync</summary>
public async Task GetAlertPolicyAsync()
{
// Snippet: GetAlertPolicyAsync(string, CallSettings)
// Additional: GetAlertPolicyAsync(string, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/alertPolicies/[ALERT_POLICY]";
// Make the request
AlertPolicy response = await alertPolicyServiceClient.GetAlertPolicyAsync(name);
// End snippet
}
/// <summary>Snippet for GetAlertPolicy</summary>
public void GetAlertPolicyResourceNames1()
{
// Snippet: GetAlertPolicy(AlertPolicyName, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
AlertPolicyName name = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]");
// Make the request
AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(name);
// End snippet
}
/// <summary>Snippet for GetAlertPolicyAsync</summary>
public async Task GetAlertPolicyResourceNames1Async()
{
// Snippet: GetAlertPolicyAsync(AlertPolicyName, CallSettings)
// Additional: GetAlertPolicyAsync(AlertPolicyName, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
AlertPolicyName name = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]");
// Make the request
AlertPolicy response = await alertPolicyServiceClient.GetAlertPolicyAsync(name);
// End snippet
}
/// <summary>Snippet for GetAlertPolicy</summary>
public void GetAlertPolicyResourceNames2()
{
// Snippet: GetAlertPolicy(IResourceName, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
// Make the request
AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(name);
// End snippet
}
/// <summary>Snippet for GetAlertPolicyAsync</summary>
public async Task GetAlertPolicyResourceNames2Async()
{
// Snippet: GetAlertPolicyAsync(IResourceName, CallSettings)
// Additional: GetAlertPolicyAsync(IResourceName, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
// Make the request
AlertPolicy response = await alertPolicyServiceClient.GetAlertPolicyAsync(name);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicy</summary>
public void CreateAlertPolicyRequestObject()
{
// Snippet: CreateAlertPolicy(CreateAlertPolicyRequest, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(request);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicyAsync</summary>
public async Task CreateAlertPolicyRequestObjectAsync()
{
// Snippet: CreateAlertPolicyAsync(CreateAlertPolicyRequest, CallSettings)
// Additional: CreateAlertPolicyAsync(CreateAlertPolicyRequest, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicy</summary>
public void CreateAlertPolicy()
{
// Snippet: CreateAlertPolicy(string, AlertPolicy, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]";
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicyAsync</summary>
public async Task CreateAlertPolicyAsync()
{
// Snippet: CreateAlertPolicyAsync(string, AlertPolicy, CallSettings)
// Additional: CreateAlertPolicyAsync(string, AlertPolicy, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]";
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicy</summary>
public void CreateAlertPolicyResourceNames1()
{
// Snippet: CreateAlertPolicy(ProjectName, AlertPolicy, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
ProjectName name = ProjectName.FromProject("[PROJECT]");
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicyAsync</summary>
public async Task CreateAlertPolicyResourceNames1Async()
{
// Snippet: CreateAlertPolicyAsync(ProjectName, AlertPolicy, CallSettings)
// Additional: CreateAlertPolicyAsync(ProjectName, AlertPolicy, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = ProjectName.FromProject("[PROJECT]");
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicy</summary>
public void CreateAlertPolicyResourceNames2()
{
// Snippet: CreateAlertPolicy(OrganizationName, AlertPolicy, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]");
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicyAsync</summary>
public async Task CreateAlertPolicyResourceNames2Async()
{
// Snippet: CreateAlertPolicyAsync(OrganizationName, AlertPolicy, CallSettings)
// Additional: CreateAlertPolicyAsync(OrganizationName, AlertPolicy, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]");
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicy</summary>
public void CreateAlertPolicyResourceNames3()
{
// Snippet: CreateAlertPolicy(FolderName, AlertPolicy, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
FolderName name = FolderName.FromFolder("[FOLDER]");
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicyAsync</summary>
public async Task CreateAlertPolicyResourceNames3Async()
{
// Snippet: CreateAlertPolicyAsync(FolderName, AlertPolicy, CallSettings)
// Additional: CreateAlertPolicyAsync(FolderName, AlertPolicy, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
FolderName name = FolderName.FromFolder("[FOLDER]");
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicy</summary>
public void CreateAlertPolicyResourceNames4()
{
// Snippet: CreateAlertPolicy(IResourceName, AlertPolicy, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for CreateAlertPolicyAsync</summary>
public async Task CreateAlertPolicyResourceNames4Async()
{
// Snippet: CreateAlertPolicyAsync(IResourceName, AlertPolicy, CallSettings)
// Additional: CreateAlertPolicyAsync(IResourceName, AlertPolicy, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy);
// End snippet
}
/// <summary>Snippet for DeleteAlertPolicy</summary>
public void DeleteAlertPolicyRequestObject()
{
// Snippet: DeleteAlertPolicy(DeleteAlertPolicyRequest, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
// Make the request
alertPolicyServiceClient.DeleteAlertPolicy(request);
// End snippet
}
/// <summary>Snippet for DeleteAlertPolicyAsync</summary>
public async Task DeleteAlertPolicyRequestObjectAsync()
{
// Snippet: DeleteAlertPolicyAsync(DeleteAlertPolicyRequest, CallSettings)
// Additional: DeleteAlertPolicyAsync(DeleteAlertPolicyRequest, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
// Make the request
await alertPolicyServiceClient.DeleteAlertPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteAlertPolicy</summary>
public void DeleteAlertPolicy()
{
// Snippet: DeleteAlertPolicy(string, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/alertPolicies/[ALERT_POLICY]";
// Make the request
alertPolicyServiceClient.DeleteAlertPolicy(name);
// End snippet
}
/// <summary>Snippet for DeleteAlertPolicyAsync</summary>
public async Task DeleteAlertPolicyAsync()
{
// Snippet: DeleteAlertPolicyAsync(string, CallSettings)
// Additional: DeleteAlertPolicyAsync(string, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/alertPolicies/[ALERT_POLICY]";
// Make the request
await alertPolicyServiceClient.DeleteAlertPolicyAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteAlertPolicy</summary>
public void DeleteAlertPolicyResourceNames1()
{
// Snippet: DeleteAlertPolicy(AlertPolicyName, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
AlertPolicyName name = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]");
// Make the request
alertPolicyServiceClient.DeleteAlertPolicy(name);
// End snippet
}
/// <summary>Snippet for DeleteAlertPolicyAsync</summary>
public async Task DeleteAlertPolicyResourceNames1Async()
{
// Snippet: DeleteAlertPolicyAsync(AlertPolicyName, CallSettings)
// Additional: DeleteAlertPolicyAsync(AlertPolicyName, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
AlertPolicyName name = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]");
// Make the request
await alertPolicyServiceClient.DeleteAlertPolicyAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteAlertPolicy</summary>
public void DeleteAlertPolicyResourceNames2()
{
// Snippet: DeleteAlertPolicy(IResourceName, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
// Make the request
alertPolicyServiceClient.DeleteAlertPolicy(name);
// End snippet
}
/// <summary>Snippet for DeleteAlertPolicyAsync</summary>
public async Task DeleteAlertPolicyResourceNames2Async()
{
// Snippet: DeleteAlertPolicyAsync(IResourceName, CallSettings)
// Additional: DeleteAlertPolicyAsync(IResourceName, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
// Make the request
await alertPolicyServiceClient.DeleteAlertPolicyAsync(name);
// End snippet
}
/// <summary>Snippet for UpdateAlertPolicy</summary>
public void UpdateAlertPolicyRequestObject()
{
// Snippet: UpdateAlertPolicy(UpdateAlertPolicyRequest, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new FieldMask(),
AlertPolicy = new AlertPolicy(),
};
// Make the request
AlertPolicy response = alertPolicyServiceClient.UpdateAlertPolicy(request);
// End snippet
}
/// <summary>Snippet for UpdateAlertPolicyAsync</summary>
public async Task UpdateAlertPolicyRequestObjectAsync()
{
// Snippet: UpdateAlertPolicyAsync(UpdateAlertPolicyRequest, CallSettings)
// Additional: UpdateAlertPolicyAsync(UpdateAlertPolicyRequest, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new FieldMask(),
AlertPolicy = new AlertPolicy(),
};
// Make the request
AlertPolicy response = await alertPolicyServiceClient.UpdateAlertPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateAlertPolicy</summary>
public void UpdateAlertPolicy()
{
// Snippet: UpdateAlertPolicy(FieldMask, AlertPolicy, CallSettings)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
FieldMask updateMask = new FieldMask();
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = alertPolicyServiceClient.UpdateAlertPolicy(updateMask, alertPolicy);
// End snippet
}
/// <summary>Snippet for UpdateAlertPolicyAsync</summary>
public async Task UpdateAlertPolicyAsync()
{
// Snippet: UpdateAlertPolicyAsync(FieldMask, AlertPolicy, CallSettings)
// Additional: UpdateAlertPolicyAsync(FieldMask, AlertPolicy, CancellationToken)
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync();
// Initialize request argument(s)
FieldMask updateMask = new FieldMask();
AlertPolicy alertPolicy = new AlertPolicy();
// Make the request
AlertPolicy response = await alertPolicyServiceClient.UpdateAlertPolicyAsync(updateMask, alertPolicy);
// End snippet
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Nancy.Diagnostics;
using Bootstrapper;
using Nancy.TinyIoc;
/// <summary>
/// TinyIoC bootstrapper - registers default route resolver and registers itself as
/// INancyModuleCatalog for resolving modules but behaviour can be overridden if required.
/// </summary>
public class DefaultNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<TinyIoCContainer>
{
/// <summary>
/// Default assemblies that are ignored for autoregister
/// </summary>
public static IEnumerable<Func<Assembly, bool>> DefaultAutoRegisterIgnoredAssemblies = new Func<Assembly, bool>[]
{
asm => asm.FullName.StartsWith("Microsoft.", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("System.", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("System,", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("CR_ExtUnitTest", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("mscorlib,", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("CR_VSTest", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("DevExpress.CodeRush", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("IronPython", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("IronRuby", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("xunit", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("Nancy.Testing", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("MonoDevelop.NUnit", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("SMDiagnostics", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("CppCodeProvider", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("WebDev.WebHost40", StringComparison.Ordinal),
};
/// <summary>
/// Gets the assemblies to ignore when autoregistering the application container
/// Return true from the delegate to ignore that particular assembly, returning false
/// does not mean the assembly *will* be included, a true from another delegate will
/// take precedence.
/// </summary>
protected virtual IEnumerable<Func<Assembly, bool>> AutoRegisterIgnoredAssemblies
{
get { return DefaultAutoRegisterIgnoredAssemblies; }
}
/// <summary>
/// Configures the container using AutoRegister followed by registration
/// of default INancyModuleCatalog and IRouteResolver.
/// </summary>
/// <param name="container">Container instance</param>
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
AutoRegister(container, this.AutoRegisterIgnoredAssemblies);
}
/// <summary>
/// Resolve INancyEngine
/// </summary>
/// <returns>INancyEngine implementation</returns>
protected override sealed INancyEngine GetEngineInternal()
{
return this.ApplicationContainer.Resolve<INancyEngine>();
}
/// <summary>
/// Create a default, unconfigured, container
/// </summary>
/// <returns>Container instance</returns>
protected override TinyIoCContainer GetApplicationContainer()
{
return new TinyIoCContainer();
}
/// <summary>
/// Register the bootstrapper's implemented types into the container.
/// This is necessary so a user can pass in a populated container but not have
/// to take the responsibility of registering things like INancyModuleCatalog manually.
/// </summary>
/// <param name="applicationContainer">Application container to register into</param>
protected override sealed void RegisterBootstrapperTypes(TinyIoCContainer applicationContainer)
{
applicationContainer.Register<INancyModuleCatalog>(this);
}
/// <summary>
/// Register the default implementations of internally used types into the container as singletons
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="typeRegistrations">Type registrations to register</param>
protected override sealed void RegisterTypes(TinyIoCContainer container, IEnumerable<TypeRegistration> typeRegistrations)
{
foreach (var typeRegistration in typeRegistrations)
{
switch (typeRegistration.Lifetime)
{
case Lifetime.Transient:
container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsMultiInstance();
break;
case Lifetime.Singleton:
container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsSingleton();
break;
case Lifetime.PerRequest:
throw new InvalidOperationException("Unable to directly register a per request lifetime.");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Register the various collections into the container as singletons to later be resolved
/// by IEnumerable{Type} constructor dependencies.
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="collectionTypeRegistrations">Collection type registrations to register</param>
protected override sealed void RegisterCollectionTypes(TinyIoCContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations)
{
foreach (var collectionTypeRegistration in collectionTypeRegistrations)
{
switch (collectionTypeRegistration.Lifetime)
{
case Lifetime.Transient:
container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsMultiInstance();
break;
case Lifetime.Singleton:
container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsSingleton();
break;
case Lifetime.PerRequest:
throw new InvalidOperationException("Unable to directly register a per request lifetime.");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Register the given module types into the container
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="moduleRegistrationTypes">NancyModule types</param>
protected override sealed void RegisterRequestContainerModules(TinyIoCContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)
{
foreach (var moduleRegistrationType in moduleRegistrationTypes)
{
container.Register(
typeof(INancyModule),
moduleRegistrationType.ModuleType,
moduleRegistrationType.ModuleType.FullName).
AsSingleton();
}
}
/// <summary>
/// Register the given instances into the container
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="instanceRegistrations">Instance registration types</param>
protected override void RegisterInstances(TinyIoCContainer container, IEnumerable<InstanceRegistration> instanceRegistrations)
{
foreach (var instanceRegistration in instanceRegistrations)
{
container.Register(
instanceRegistration.RegistrationType,
instanceRegistration.Implementation);
}
}
/// <summary>
/// Creates a per request child/nested container
/// </summary>
/// <param name="context">Current context</param>
/// <returns>Request container instance</returns>
protected override TinyIoCContainer CreateRequestContainer(NancyContext context)
{
return this.ApplicationContainer.GetChildContainer();
}
/// <summary>
/// Gets the diagnostics for initialisation
/// </summary>
/// <returns>IDiagnostics implementation</returns>
protected override IDiagnostics GetDiagnostics()
{
return this.ApplicationContainer.Resolve<IDiagnostics>();
}
/// <summary>
/// Gets all registered startup tasks
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns>
protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()
{
return this.ApplicationContainer.ResolveAll<IApplicationStartup>(false);
}
/// <summary>
/// Gets all registered request startup tasks
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns>
protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(TinyIoCContainer container, Type[] requestStartupTypes)
{
container.RegisterMultiple(typeof(IRequestStartup), requestStartupTypes);
return container.ResolveAll<IRequestStartup>(false);
}
/// <summary>
/// Gets all registered application registration tasks
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns>
protected override IEnumerable<IRegistrations> GetRegistrationTasks()
{
return this.ApplicationContainer.ResolveAll<IRegistrations>(false);
}
/// <summary>
/// Retrieve all module instances from the container
/// </summary>
/// <param name="container">Container to use</param>
/// <returns>Collection of NancyModule instances</returns>
protected override sealed IEnumerable<INancyModule> GetAllModules(TinyIoCContainer container)
{
var nancyModules = container.ResolveAll<INancyModule>(false);
return nancyModules;
}
/// <summary>
/// Retrieve a specific module instance from the container
/// </summary>
/// <param name="container">Container to use</param>
/// <param name="moduleType">Type of the module</param>
/// <returns>NancyModule instance</returns>
protected override sealed INancyModule GetModule(TinyIoCContainer container, Type moduleType)
{
container.Register(typeof(INancyModule), moduleType);
return container.Resolve<INancyModule>();
}
/// <summary>
/// Executes auto registation with the given container.
/// </summary>
/// <param name="container">Container instance</param>
private static void AutoRegister(TinyIoCContainer container, IEnumerable<Func<Assembly, bool>> ignoredAssemblies)
{
var assembly = typeof(NancyEngine).Assembly;
container.AutoRegister(AppDomain.CurrentDomain.GetAssemblies().Where(a => !ignoredAssemblies.Any(ia => ia(a))), DuplicateImplementationActions.RegisterMultiple, t => t.Assembly != assembly);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
namespace System.Management.Automation
{
/// <summary>
/// Provides information about a workflow that is stored in session state.
/// </summary>
public class WorkflowInfo : FunctionInfo
{
#region ctor
/// <summary>
/// Creates an instance of the workflowInfo class with the specified name and ScriptBlock.
/// </summary>
/// <param name="name">
/// The name of the workflow.
/// </param>
/// <param name="definition">
/// The script body defining the workflow.
/// </param>
/// <param name="workflow">
/// The ScriptBlock for the workflow
/// </param>
/// <param name="xamlDefinition">
/// The XAML used to define the workflow
/// </param>
/// <param name="workflowsCalled">
/// The workflows referenced within <paramref name="xamlDefinition"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="workflow"/> is null.
/// </exception>
internal WorkflowInfo(string name, string definition, ScriptBlock workflow, string xamlDefinition, WorkflowInfo[] workflowsCalled)
: this(name, workflow, (ExecutionContext)null)
{
if (string.IsNullOrEmpty(xamlDefinition))
{
throw PSTraceSource.NewArgumentNullException("xamlDefinition");
}
_definition = definition;
this.XamlDefinition = xamlDefinition;
if (workflowsCalled != null)
{
_workflowsCalled = new ReadOnlyCollection<WorkflowInfo>(workflowsCalled);
}
}
/// <summary>
/// Creates an instance of the workflowInfo class with the specified name and ScriptBlock.
/// </summary>
/// <param name="name">
/// The name of the workflow.
/// </param>
/// <param name="definition">
/// The script body defining the workflow.
/// </param>
/// <param name="workflow">
/// The ScriptBlock for the workflow
/// </param>
/// <param name="xamlDefinition">
/// The XAML used to define the workflow
/// </param>
/// <param name="workflowsCalled">
/// The workflows referenced within <paramref name="xamlDefinition"/>.
/// </param>
/// <param name="module">Module.</param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="workflow"/> is null.
/// </exception>
internal WorkflowInfo(string name, string definition, ScriptBlock workflow, string xamlDefinition, WorkflowInfo[] workflowsCalled, PSModuleInfo module)
: this(name, definition, workflow, xamlDefinition, workflowsCalled)
{
this.Module = module;
}
/// <summary>
/// Creates an instance of the workflowInfo class with the specified name and ScriptBlock.
/// </summary>
/// <param name="name">
/// The name of the workflow.
/// </param>
/// <param name="workflow">
/// The ScriptBlock for the workflow
/// </param>
/// <param name="context">
/// The ExecutionContext for the workflow.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="workflow"/> is null.
/// </exception>
internal WorkflowInfo(string name, ScriptBlock workflow, ExecutionContext context) : this(name, workflow, context, null)
{
}
/// <summary>
/// Creates an instance of the workflowInfo class with the specified name and ScriptBlock.
/// </summary>
/// <param name="name">
/// The name of the workflow.
/// </param>
/// <param name="workflow">
/// The ScriptBlock for the workflow
/// </param>
/// <param name="context">
/// The ExecutionContext for the workflow.
/// </param>
/// <param name="helpFile">
/// The helpfile for the workflow.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="workflow"/> is null.
/// </exception>
internal WorkflowInfo(string name, ScriptBlock workflow, ExecutionContext context, string helpFile)
: base(name, workflow, context, helpFile)
{
SetCommandType(CommandTypes.Workflow);
}
/// <summary>
/// Creates an instance of the WorkflowInfo class with the specified name and ScriptBlock.
/// </summary>
/// <param name="name">
/// The name of the workflow.
/// </param>
/// <param name="workflow">
/// The ScriptBlock for the workflow
/// </param>
/// <param name="options">
/// The options to set on the function. Note, Constant can only be set at creation time.
/// </param>
/// <param name="context">
/// The execution context for the workflow.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="workflow"/> is null.
/// </exception>
internal WorkflowInfo(string name, ScriptBlock workflow, ScopedItemOptions options, ExecutionContext context) : this(name, workflow, options, context, null)
{
}
/// <summary>
/// Creates an instance of the WorkflowInfo class with the specified name and ScriptBlock.
/// </summary>
/// <param name="name">
/// The name of the workflow.
/// </param>
/// <param name="workflow">
/// The ScriptBlock for the workflow
/// </param>
/// <param name="options">
/// The options to set on the function. Note, Constant can only be set at creation time.
/// </param>
/// <param name="context">
/// The execution context for the workflow.
/// </param>
/// <param name="helpFile">
/// The helpfile for the workflow.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="workflow"/> is null.
/// </exception>
internal WorkflowInfo(string name, ScriptBlock workflow, ScopedItemOptions options, ExecutionContext context, string helpFile)
: base(name, workflow, options, context, helpFile)
{
SetCommandType(CommandTypes.Workflow);
}
/// <summary>
/// This is a copy constructor.
/// </summary>
internal WorkflowInfo(WorkflowInfo other)
: base(other)
{
SetCommandType(CommandTypes.Workflow);
CopyFields(other);
}
/// <summary>
/// This is a copy constructor.
/// </summary>
internal WorkflowInfo(string name, WorkflowInfo other)
: base(name, other)
{
SetCommandType(CommandTypes.Workflow);
CopyFields(other);
}
private void CopyFields(WorkflowInfo other)
{
this.XamlDefinition = other.XamlDefinition;
this.NestedXamlDefinition = other.NestedXamlDefinition;
_workflowsCalled = other.WorkflowsCalled;
_definition = other.Definition;
}
/// <summary>
/// Update a workflow.
/// </summary>
/// <param name="function">
/// The script block that the function should represent.
/// </param>
/// <param name="force">
/// If true, the script block will be applied even if the filter is ReadOnly.
/// </param>
/// <param name="options">
/// Any options to set on the new function, null if none.
/// </param>
/// <param name="helpFile">
/// Helpfile for this function
/// </param>
protected internal override void Update(FunctionInfo function, bool force, ScopedItemOptions options, string helpFile)
{
var other = function as WorkflowInfo;
if (other == null)
{
throw PSTraceSource.NewArgumentException("function");
}
base.Update(function, force, options, helpFile);
CopyFields(other);
}
/// <summary>
/// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
/// sets based on an argument list (so we can get the dynamic parameters.)
/// </summary>
internal override CommandInfo CreateGetCommandCopy(object[] arguments)
{
WorkflowInfo copy = new WorkflowInfo(this);
copy.IsGetCommandCopy = true;
copy.Arguments = arguments;
return copy;
}
#endregion ctor
/// <summary>
/// Returns the definition of the workflow.
/// </summary>
public override string Definition
{
get { return _definition; }
}
private string _definition = string.Empty;
/// <summary>
/// Gets the XAML that represents the definition of the workflow.
/// </summary>
public string XamlDefinition { get; internal set; }
/// <summary>
/// Gets or sets the XAML that represents the definition of the workflow
/// when called from another workflow.
/// </summary>
public string NestedXamlDefinition { get; set; }
/// <summary>
/// Gets the XAML for workflows called by this workflow.
/// </summary>
public ReadOnlyCollection<WorkflowInfo> WorkflowsCalled
{
get { return _workflowsCalled ?? Utils.EmptyReadOnlyCollection<WorkflowInfo>(); }
}
private ReadOnlyCollection<WorkflowInfo> _workflowsCalled;
internal override HelpCategory HelpCategory
{
get { return HelpCategory.Workflow; }
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.Collections.Generic;
namespace AssetBundleGraph {
[Serializable]
public class NodeGUI {
public static float scaleFactor = 1.0f;// 1.0f. 0.7f, 0.4f, 0.3f
public const float SCALE_MIN = 0.3f;
public const float SCALE_MAX = 1.0f;
public const int SCALE_WIDTH = 30;
public const float SCALE_RATIO = 0.3f;
[SerializeField] private int m_nodeWindowId;
[SerializeField] private Rect m_baseRect;
[SerializeField] private NodeData m_data;
[SerializeField] private string m_nodeSyle;
[SerializeField] private NodeGUIInspectorHelper m_nodeInsp;
/*
show error on node functions.
*/
private bool m_hasErrors = false;
/*
show progress on node functions(unused. due to mainthread synchronization problem.)
can not update any visual on Editor while building AssetBundles through AssetBundleGraph.
*/
private float m_progress;
private bool m_running;
/*
* Properties
*/
public string Name {
get {
return m_data.Name;
}
set {
m_data.Name = value;
}
}
public string Id {
get {
return m_data.Id;
}
}
public NodeKind Kind {
get {
return m_data.Kind;
}
}
public NodeData Data {
get {
return m_data;
}
}
public Rect Region {
get {
return m_baseRect;
}
}
private NodeGUIInspectorHelper Inspector {
get {
if(m_nodeInsp == null) {
m_nodeInsp = ScriptableObject.CreateInstance<NodeGUIInspectorHelper>();
m_nodeInsp.hideFlags = HideFlags.DontSave;
}
return m_nodeInsp;
}
}
public void ResetErrorStatus () {
m_hasErrors = false;
Inspector.UpdateNode(this);
Inspector.UpdateErrors(new List<string>());
}
public void AppendErrorSources (List<string> errors) {
this.m_hasErrors = true;
Inspector.UpdateNode(this);
Inspector.UpdateErrors(errors);
}
public int WindowId {
get {
return m_nodeWindowId;
}
set {
m_nodeWindowId = value;
}
}
public NodeGUI (NodeData data) {
m_nodeWindowId = 0;
m_data = data;
m_baseRect = new Rect(m_data.X, m_data.Y, AssetBundleGraphSettings.GUI.NODE_BASE_WIDTH, AssetBundleGraphSettings.GUI.NODE_BASE_HEIGHT);
m_nodeSyle = NodeGUIUtility.UnselectedStyle[m_data.Kind];
}
public NodeGUI Duplicate (float newX, float newY) {
var data = m_data.Duplicate();
data.X = newX;
data.Y = newY;
return new NodeGUI(data);
}
public void SetActive () {
Inspector.UpdateNode(this);
Selection.activeObject = Inspector;
m_nodeSyle = NodeGUIUtility.SelectedStyle[m_data.Kind];
}
public void SetInactive () {
m_nodeSyle = NodeGUIUtility.UnselectedStyle[m_data.Kind];
}
private void RefreshConnectionPos (float yOffset) {
for (int i = 0; i < m_data.InputPoints.Count; i++) {
var point = m_data.InputPoints[i];
point.UpdateRegion(this, yOffset, i, m_data.InputPoints.Count);
}
for (int i = 0; i < m_data.OutputPoints.Count; i++) {
var point = m_data.OutputPoints[i];
point.UpdateRegion(this, yOffset, i, m_data.OutputPoints.Count);
}
}
public static Rect ScaleEffect (Rect nonScaledRect) {
var scaledRect = new Rect(nonScaledRect);
scaledRect.x = scaledRect.x * scaleFactor;
scaledRect.y = scaledRect.y * scaleFactor;
scaledRect.width = scaledRect.width * scaleFactor;
scaledRect.height = scaledRect.height * scaleFactor;
return scaledRect;
}
public static Vector2 ScaleEffect (Vector2 nonScaledVector2) {
var scaledVector2 = new Vector2(nonScaledVector2.x, nonScaledVector2.y);
scaledVector2.x = scaledVector2.x * scaleFactor;
scaledVector2.y = scaledVector2.y * scaleFactor;
return scaledVector2;
}
private bool IsValidInputConnectionPoint(ConnectionPointData point) {
if(m_data.Kind == NodeKind.BUNDLECONFIG_GUI && !m_data.BundleConfigUseGroupAsVariants) {
if(m_data.Variants.Count > 0 && m_data.Variants.Find(v => v.ConnectionPoint.Id == point.Id) == null)
{
return false;
}
}
return true;
}
/**
retrieve mouse events for this node in this AssetGraoh window.
*/
private void HandleNodeEvent () {
switch (Event.current.type) {
/*
handling release of mouse drag from this node to another node.
this node doesn't know about where the other node is. the master only knows.
only emit event.
*/
case EventType.Ignore: {
NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_CONNECTION_OVERED, this, Event.current.mousePosition, null));
break;
}
/*
handling drag.
*/
case EventType.MouseDrag: {
NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_MOVING, this, Event.current.mousePosition, null));
break;
}
/*
check if the mouse-down point is over one of the connectionPoint in this node.
then emit event.
*/
case EventType.MouseDown: {
ConnectionPointData result = IsOverConnectionPoint(Event.current.mousePosition);
if (result != null) {
if (scaleFactor == SCALE_MAX) {
NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_CONNECT_STARTED, this, Event.current.mousePosition, result));
}
break;
}
break;
}
}
/*
retrieve mouse events for this node in|out of this AssetGraoh window.
*/
switch (Event.current.rawType) {
case EventType.MouseUp: {
bool eventRaised = false;
// if mouse position is on the connection point, emit mouse raised event.
Action<ConnectionPointData> raiseEventIfHit = (ConnectionPointData point) => {
// Only one connectionPoint raise event at one mouseup event
if(eventRaised) {
return;
}
if(!IsValidInputConnectionPoint(point)) {
return;
}
if (point.Region.Contains(Event.current.mousePosition)) {
NodeGUIUtility.NodeEventHandler(
new NodeEvent(NodeEvent.EventType.EVENT_NODE_CONNECTION_RAISED,
this, Event.current.mousePosition, point));
eventRaised = true;
return;
}
};
m_data.InputPoints.ForEach(raiseEventIfHit);
m_data.OutputPoints.ForEach(raiseEventIfHit);
if(!eventRaised) {
NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_TOUCHED,
this, Event.current.mousePosition, null));
}
break;
}
}
/*
right click to open Context menu
*/
if (scaleFactor == SCALE_MAX) {
if (Event.current.type == EventType.ContextClick || (Event.current.type == EventType.MouseUp && Event.current.button == 1))
{
var menu = new GenericMenu();
MonoScript s = TypeUtility.LoadMonoScript(Data.ScriptClassName);
if(s != null) {
menu.AddItem(
new GUIContent("Edit Script"),
false,
() => {
AssetDatabase.OpenAsset(s, 0);
}
);
}
menu.AddItem(
new GUIContent("Delete"),
false,
() => {
NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_CLOSE_TAPPED, this, Vector2.zero, null));
}
);
menu.ShowAsContext();
Event.current.Use();
}
}
}
public void DrawConnectionInputPointMark (NodeEvent eventSource, bool justConnecting) {
if (scaleFactor != SCALE_MAX) return;
var defaultPointTex = NodeGUIUtility.inputPointMarkTex;
bool shouldDrawEnable =
!( eventSource != null && eventSource.eventSourceNode != null &&
!ConnectionData.CanConnect(eventSource.eventSourceNode.Data, m_data)
);
if (shouldDrawEnable && justConnecting && eventSource != null) {
if (eventSource.eventSourceNode.Id != this.Id) {
var connectionPoint = eventSource.point;
if (connectionPoint.IsOutput) {
defaultPointTex = NodeGUIUtility.enablePointMarkTex;
}
}
}
foreach (var point in m_data.InputPoints) {
if(IsValidInputConnectionPoint(point)) {
GUI.DrawTexture(point.GetGlobalPointRegion(this), defaultPointTex);
}
}
}
public void DrawConnectionOutputPointMark (NodeEvent eventSource, bool justConnecting, Event current) {
if (scaleFactor != SCALE_MAX) return;
var defaultPointTex = NodeGUIUtility.outputPointMarkConnectedTex;
bool shouldDrawEnable =
!( eventSource != null && eventSource.eventSourceNode != null &&
!ConnectionData.CanConnect(m_data, eventSource.eventSourceNode.Data)
);
if (shouldDrawEnable && justConnecting && eventSource != null) {
if (eventSource.eventSourceNode.Id != this.Id) {
var connectionPoint = eventSource.point;
if (connectionPoint.IsInput) {
defaultPointTex = NodeGUIUtility.enablePointMarkTex;
}
}
}
var globalMousePosition = current.mousePosition;
foreach (var point in m_data.OutputPoints) {
var pointRegion = point.GetGlobalPointRegion(this);
GUI.DrawTexture(
pointRegion,
defaultPointTex
);
// eventPosition is contained by outputPointRect.
if (pointRegion.Contains(globalMousePosition)) {
if (current.type == EventType.MouseDown) {
NodeGUIUtility.NodeEventHandler(
new NodeEvent(NodeEvent.EventType.EVENT_NODE_CONNECT_STARTED, this, current.mousePosition, point));
}
}
}
}
public void DrawNode () {
var scaledBaseRect = ScaleEffect(m_baseRect);
var movedRect = GUI.Window(m_nodeWindowId, scaledBaseRect, DrawThisNode, string.Empty, m_nodeSyle);
m_baseRect.position = m_baseRect.position + (movedRect.position - scaledBaseRect.position);
}
private void DrawThisNode(int id) {
UpdateNodeRect ();
HandleNodeEvent ();
DrawNodeContents();
GUI.DragWindow();
}
private void DrawNodeContents () {
var oldColor = GUI.color;
var textColor = (EditorGUIUtility.isProSkin)? Color.black : oldColor;
var style = new GUIStyle(EditorStyles.label);
style.alignment = TextAnchor.MiddleCenter;
var connectionNodeStyleOutput = new GUIStyle(EditorStyles.label);
connectionNodeStyleOutput.alignment = TextAnchor.MiddleRight;
var connectionNodeStyleInput = new GUIStyle(EditorStyles.label);
connectionNodeStyleInput.alignment = TextAnchor.MiddleLeft;
var titleHeight = style.CalcSize(new GUIContent(Name)).y + AssetBundleGraphSettings.GUI.NODE_TITLE_HEIGHT_MARGIN;
var nodeTitleRect = new Rect(0, 0, m_baseRect.width * scaleFactor, titleHeight);
GUI.color = textColor;
GUI.Label(nodeTitleRect, Name, style);
GUI.color = oldColor;
if (m_running) {
EditorGUI.ProgressBar(new Rect(10f, m_baseRect.height - 20f, m_baseRect.width - 20f, 10f), m_progress, string.Empty);
}
if (m_hasErrors) {
GUIStyle errorStyle = new GUIStyle("CN EntryError");
errorStyle.alignment = TextAnchor.MiddleCenter;
var labelSize = GUI.skin.label.CalcSize(new GUIContent(Name));
EditorGUI.LabelField(new Rect((nodeTitleRect.width - labelSize.x )/2.0f - 28f, (nodeTitleRect.height-labelSize.y)/2.0f - 7f, 20f, 20f), string.Empty, errorStyle);
}
// draw & update connectionPoint button interface.
if (scaleFactor == SCALE_MAX) {
Action<ConnectionPointData> drawConnectionPoint = (ConnectionPointData point) =>
{
var label = point.Label;
if( label != AssetBundleGraphSettings.DEFAULT_INPUTPOINT_LABEL &&
label != AssetBundleGraphSettings.DEFAULT_OUTPUTPOINT_LABEL)
{
var region = point.Region;
// if point is output node, then label position offset is minus. otherwise plus.
var xOffset = (point.IsOutput) ? - m_baseRect.width : AssetBundleGraphSettings.GUI.INPUT_POINT_WIDTH;
var labelStyle = (point.IsOutput) ? connectionNodeStyleOutput : connectionNodeStyleInput;
var labelRect = new Rect(region.x + xOffset, region.y - (region.height/2), m_baseRect.width, region.height*2);
GUI.color = textColor;
GUI.Label(labelRect, label, labelStyle);
GUI.color = oldColor;
}
GUI.backgroundColor = Color.clear;
Texture2D tex = (point.IsInput)? NodeGUIUtility.inputPointTex : NodeGUIUtility.outputPointTex;
GUI.Button(point.Region, tex, "AnimationKeyframeBackground");
};
m_data.InputPoints.ForEach(drawConnectionPoint);
m_data.OutputPoints.ForEach(drawConnectionPoint);
}
}
public void UpdateNodeRect () {
// UpdateNodeRect will be called outside OnGUI(), so it use inacurate but simple way to calcurate label width
// instead of CalcSize()
float labelWidth = GUI.skin.label.CalcSize(new GUIContent(this.Name)).x;
float outputLabelWidth = 0f;
float inputLabelWidth = 0f;
if(m_data.InputPoints.Count > 0) {
var inputLabels = m_data.InputPoints.OrderByDescending(p => p.Label.Length).Select(p => p.Label);
if (inputLabels.Any()) {
inputLabelWidth = GUI.skin.label.CalcSize(new GUIContent(inputLabels.First())).x;
}
}
if(m_data.OutputPoints.Count > 0) {
var outputLabels = m_data.OutputPoints.OrderByDescending(p => p.Label.Length).Select(p => p.Label);
if (outputLabels.Any()) {
outputLabelWidth = GUI.skin.label.CalcSize(new GUIContent(outputLabels.First())).x;
}
}
var titleHeight = GUI.skin.label.CalcSize(new GUIContent(Name)).y + AssetBundleGraphSettings.GUI.NODE_TITLE_HEIGHT_MARGIN;
// update node height by number of output connectionPoint.
var nPoints = Mathf.Max(m_data.OutputPoints.Count, m_data.InputPoints.Count);
this.m_baseRect = new Rect(m_baseRect.x, m_baseRect.y,
m_baseRect.width,
AssetBundleGraphSettings.GUI.NODE_BASE_HEIGHT + titleHeight + (AssetBundleGraphSettings.GUI.FILTER_OUTPUT_SPAN * Mathf.Max(0, (nPoints - 1)))
);
var newWidth = Mathf.Max(AssetBundleGraphSettings.GUI.NODE_BASE_WIDTH, outputLabelWidth + inputLabelWidth + AssetBundleGraphSettings.GUI.NODE_WIDTH_MARGIN);
newWidth = Mathf.Max(newWidth, labelWidth + AssetBundleGraphSettings.GUI.NODE_WIDTH_MARGIN);
m_baseRect = new Rect(m_baseRect.x, m_baseRect.y, newWidth, m_baseRect.height);
RefreshConnectionPos(titleHeight);
}
private ConnectionPointData IsOverConnectionPoint (Vector2 touchedPoint) {
foreach(var p in m_data.InputPoints) {
var region = p.Region;
if(!IsValidInputConnectionPoint(p)) {
continue;
}
if (region.x <= touchedPoint.x &&
touchedPoint.x <= region.x + region.width &&
region.y <= touchedPoint.y &&
touchedPoint.y <= region.y + region.height
) {
return p;
}
}
foreach(var p in m_data.OutputPoints) {
var region = p.Region;
if (region.x <= touchedPoint.x &&
touchedPoint.x <= region.x + region.width &&
region.y <= touchedPoint.y &&
touchedPoint.y <= region.y + region.height
) {
return p;
}
}
return null;
}
public Rect GetRect () {
return m_baseRect;
}
public Vector2 GetPos () {
return m_baseRect.position;
}
public int GetX () {
return (int)m_baseRect.x;
}
public int GetY () {
return (int)m_baseRect.y;
}
public int GetRightPos () {
return (int)(m_baseRect.x + m_baseRect.width);
}
public int GetBottomPos () {
return (int)(m_baseRect.y + m_baseRect.height);
}
public void SetPos (Vector2 position) {
m_baseRect.position = position;
m_data.X = position.x;
m_data.Y = position.y;
}
public void SetProgress (float val) {
m_progress = val;
}
public void MoveRelative (Vector2 diff) {
m_baseRect.position = m_baseRect.position - diff;
}
public void ShowProgress () {
m_running = true;
}
public void HideProgress () {
m_running = false;
}
public bool Conitains (Vector2 globalPos) {
if (m_baseRect.Contains(globalPos)) {
return true;
}
foreach (var point in m_data.OutputPoints) {
if (point.GetGlobalPointRegion(this).Contains(globalPos)) {
return true;
}
}
return false;
}
public ConnectionPointData FindConnectionPointByPosition (Vector2 globalPos) {
foreach (var point in m_data.InputPoints) {
if(!IsValidInputConnectionPoint(point)) {
continue;
}
if (point.GetGlobalRegion(this).Contains(globalPos) ||
point.GetGlobalPointRegion(this).Contains(globalPos))
{
return point;
}
}
foreach (var point in m_data.OutputPoints) {
if (point.GetGlobalRegion(this).Contains(globalPos) ||
point.GetGlobalPointRegion(this).Contains(globalPos))
{
return point;
}
}
return null;
}
public static void ShowTypeNamesMenu (string current, List<string> contents, Action<string> ExistSelected) {
var menu = new GenericMenu();
for (var i = 0; i < contents.Count; i++) {
var type = contents[i];
var selected = false;
if (type == current) selected = true;
menu.AddItem(
new GUIContent(type),
selected,
() => {
ExistSelected(type);
}
);
}
menu.ShowAsContext();
}
public static void ShowFilterKeyTypeMenu (string current, Action<string> Selected) {
var menu = new GenericMenu();
menu.AddDisabledItem(new GUIContent(current));
menu.AddSeparator(string.Empty);
for (var i = 0; i < TypeUtility.KeyTypes.Count; i++) {
var type = TypeUtility.KeyTypes[i];
if (type == current) continue;
menu.AddItem(
new GUIContent(type),
false,
() => {
Selected(type);
}
);
}
menu.ShowAsContext();
}
}
}
| |
/*
* Copyright (c) 2013-2014 Behrooz Amoozad
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the bd2 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 Behrooz Amoozad 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 BD2.Core;
namespace BD2.CLI
{
class MainClass
{
static object lock_query = new object ();
static Queue<string> initial = new Queue<string> ();
public static string Query (string message)
{
//yes, it's just this simple for now.
lock (lock_query) {
Console.Write (message + " ");
if (initial.Count != 0) {
Console.WriteLine (initial.Peek ());
return initial.Dequeue ();
}
return Console.ReadLine ();
}
}
static SortedSet<string> Modifiers = new SortedSet<string> ();
public static int ExtractModifiers (string[] parts)
{
for (int n = 0; n != parts.Length; n++) {
if (!Modifiers.Contains (parts [n]))
return n;
}
return -1;
}
static SortedDictionary<string, BD2.Chunk.ChunkRepository> repositories;
static void OpenNetworkRepository (string[] commandParts)
{
string nick = commandParts [2];
string ip = commandParts [3];
string port = commandParts [4];
System.Net.Sockets.TcpClient TC = new System.Net.Sockets.TcpClient ();
TC.Connect (new System.Net.IPEndPoint (System.Net.IPAddress.Parse (ip), int.Parse (port)));
BD2.Chunk.ChunkRepository LRepo = new BD2.Repo.Net.Repository (TC.GetStream ());
lock (repositories)
repositories.Add (nick, LRepo);
}
static void OpenLevelDBRepository (string[] commandParts)
{
string nick = commandParts [2];
string path = commandParts [3];
ChunkRepository LRepo = new ChunkRepository (path);
lock (repositories)
repositories.Add (nick, LRepo);
}
public static void Main (string[] args)
{
System.Threading.ThreadPool.SetMinThreads (64, 16);
if (args.Length == 1)
foreach (string str in System.IO.File.ReadAllLines (args[0]))
initial.Enqueue (str);
SortedDictionary<int, System.Threading.Thread> jobs = new SortedDictionary<int, System.Threading.Thread> ();
repositories = new SortedDictionary<string, ChunkRepository> ();
Modifiers.Add ("async");
//BD2.Core.Database DB = new BD2.Core.Database ();
string command;
do {
command = Query ("Command>");
if (command == null)
return;
OffsetedArray<string> commandparts = command.Split (' ');
string[] CommandParts = (string[])((string[])commandparts).Clone ();
commandparts.Offset = ExtractModifiers (CommandParts);
SortedSet<string> CommandModifiers = new SortedSet<string> (commandparts.GetStrippedPart ());
switch (CommandParts [0]) {
case "Run":
if (CommandParts.Length < 2) {
Console.Error.WriteLine ("Run requires at least two parameter: [async] Run <Type>");
continue;
}
switch (CommandParts [1]) {
case "Daemon":
if (CommandParts.Length < 3) {
Console.Error.WriteLine ("Run Daemon requires at least one parameter: [async] Run Daemon <Daemon Type>");
continue;
}
switch (CommandParts [2]) {
case "SQL":
if (CommandModifiers.Contains ("async")) {
System.Threading.Thread t_runSourceDaemon = new System.Threading.Thread (RunSourceDaemon);
jobs.Add (t_runSourceDaemon.ManagedThreadId, t_runSourceDaemon);
t_runSourceDaemon.Start ();
} else
RunSourceDaemon ();
break;//source
default:
Console.Error.WriteLine ("Invalid Daemon Type.");
break;
}
break;
}
break;//daemon
case "Open":
if (CommandParts.Length < 2) {
Console.Error.WriteLine ("Open requires at least one parameter: [async] Open <Repository Type>");
continue;
}
switch (CommandParts [1]) {
case "LevelDB":
if (CommandParts.Length < 4) {
Console.Error.WriteLine ("LevelDB repository requires at least two parameter: [async] Open File <Repository Nick> <Repository> <Path>");
continue;
}
if (CommandModifiers.Contains ("async")) {
System.Threading.Thread t_addrepo = new System.Threading.Thread (() => {
OpenLevelDBRepository (CommandParts);
});
t_addrepo.Start ();
Console.WriteLine ("[{0}]", t_addrepo.ManagedThreadId);
} else {
OpenLevelDBRepository (CommandParts);
}
break;//file
case "Network":
if (CommandParts.Length < 5) {
Console.Error.WriteLine ("Network repository requires at least three parameter: [async] Open File <Repository Nick> <Repository> <IPAddress> <Port>");
continue;
}
if (CommandModifiers.Contains ("async")) {
System.Threading.Thread t_addrepo = new System.Threading.Thread (() => {
OpenNetworkRepository (CommandParts);
});
t_addrepo.Start ();
Console.WriteLine ("[{0}]", t_addrepo.ManagedThreadId);
} else {
OpenNetworkRepository (CommandParts);
}
break;
case "Socket":
break;
}
break;
case "Close":
break;
case "Execute":
break;
case "Convert":
if (CommandParts.Length < 2) {
Console.Error.WriteLine ("Open requires at least one parameter: [async] Open <Repository Type> [Parameters]");
continue;
}
switch (CommandParts [1]) {
case "Table":
string daemonIPAddress = Query ("Daemon IP Address");
string DaemonPort = Query ("Daemon Port");
System.Net.IPAddress IPA = System.Net.IPAddress.Parse (daemonIPAddress);
System.Net.IPEndPoint IPEP = new System.Net.IPEndPoint (IPA, int.Parse (DaemonPort));
System.Net.Sockets.TcpClient TC = new System.Net.Sockets.TcpClient ();
TC.Connect (IPEP);
System.Net.Sockets.NetworkStream NS = TC.GetStream ();
BD2.Daemon.StreamHandler SH = new BD2.Daemon.StreamHandler (NS);
BD2.Daemon.ObjectBus OB = new BD2.Daemon.ObjectBus (SH);
BD2.Daemon.ServiceManager SM = new BD2.Daemon.ServiceManager (OB);
SM.AnounceReady ();
SM.WaitForRemoteReady ();
Guid serviceType_SQL = Guid.Parse ("57ce8883-1010-41ec-96da-41d36c64d65d");
var RS = SM.EnumerateRemoteServices ();
BD2.Daemon.ServiceAnnounceMessage TSA = null;
foreach (var SA in RS) {
if (SA.Type == serviceType_SQL) {
TSA = SA;
}
}
if (TSA == null) {
Console.WriteLine ("Required services for Table Conversion not found on remote host.");
}
BD2.Daemon.TransparentAgent agent =
(BD2.Daemon.TransparentAgent)
SM.RequestService (TSA, (new BD2.Conv.Daemon.MSSQL.ServiceParameters (Query ("Connection String"))).Serialize (),
BD2.Daemon.TransparentAgent.CreateAgent, null);
Client CL = new Client (agent, repositories [Query ("Repository Name")], Query ("Database Name"));
CL.Convert ();
break;
}
break;
case "await":
string jobID = commandparts [1];
int intJobID = int.Parse (jobID);
jobs [intJobID].Join ();
break;
case "Exit":
return;
default:
Console.Error.WriteLine (string.Format ("{0} is not a valid command.", CommandParts [0]));
break;
}
} while(true);
}
static void SourceDaemonListen (object para)
{
System.Net.Sockets.TcpListener TL = (System.Net.Sockets.TcpListener)para;
System.Net.Sockets.Socket sock;
while ((sock = TL.AcceptSocket ()) != null) {
System.Net.Sockets.NetworkStream NS = new System.Net.Sockets.NetworkStream (sock);
BD2.Daemon.StreamHandler SH = new BD2.Daemon.StreamHandler (NS);
BD2.Daemon.ObjectBus OB = new BD2.Daemon.ObjectBus (SH);
BD2.Daemon.ServiceManager SM = new BD2.Daemon.ServiceManager (OB);
Guid serviceType_SQL = Guid.Parse ("57ce8883-1010-41ec-96da-41d36c64d65d");
SM.AnnounceService (new BD2.Daemon.ServiceAnnounceMessage (Guid.NewGuid (), serviceType_SQL, "Source"), BD2.Conv.Daemon.MSSQL.ServiceAgent.CreateAgent);
SM.AnounceReady ();
}
}
static void RunSourceDaemon ()
{
string listenAddress = Query ("Listen Address");
string listenPort = Query ("listen Port");
System.Net.IPAddress IPA = System.Net.IPAddress.Parse (listenAddress);
System.Net.IPEndPoint IPEP = new System.Net.IPEndPoint (IPA, int.Parse (listenPort));
System.Net.Sockets.TcpListener TL = new System.Net.Sockets.TcpListener (IPEP);
TL.Start ();
System.Threading.Thread listenThread = new System.Threading.Thread (SourceDaemonListen);
listenThread.Start (TL);
}
}
}
| |
// 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 Debug = System.Diagnostics.Debug;
using IEnumerable = System.Collections.IEnumerable;
using StringBuilder = System.Text.StringBuilder;
using Interlocked = System.Threading.Interlocked;
namespace System.Xml.Linq
{
/// <summary>
/// Represents a node that can contain other nodes.
/// </summary>
/// <remarks>
/// The two classes that derive from <see cref="XContainer"/> are
/// <see cref="XDocument"/> and <see cref="XElement"/>.
/// </remarks>
public abstract class XContainer : XNode
{
internal object content;
internal XContainer() { }
internal XContainer(XContainer other)
{
if (other == null) throw new ArgumentNullException("other");
if (other.content is string)
{
this.content = other.content;
}
else
{
XNode n = (XNode)other.content;
if (n != null)
{
do
{
n = n.next;
AppendNodeSkipNotify(n.CloneNode());
} while (n != other.content);
}
}
}
/// <summary>
/// Get the first child node of this node.
/// </summary>
public XNode FirstNode
{
get
{
XNode last = LastNode;
return last != null ? last.next : null;
}
}
/// <summary>
/// Get the last child node of this node.
/// </summary>
public XNode LastNode
{
get
{
if (content == null) return null;
XNode n = content as XNode;
if (n != null) return n;
string s = content as string;
if (s != null)
{
if (s.Length == 0) return null;
XText t = new XText(s);
t.parent = this;
t.next = t;
Interlocked.CompareExchange<object>(ref content, t, s);
}
return (XNode)content;
}
}
/// <overloads>
/// Adds the specified content as a child (or as children) to this <see cref="XContainer"/>. The
/// content can be simple content, a collection of content objects, a parameter list
/// of content objects, or null.
/// </overloads>
/// <summary>
/// Adds the specified content as a child (or children) of this <see cref="XContainer"/>.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added.
/// </param>
/// <remarks>
/// When adding simple content, a number of types may be passed to this method.
/// Valid types include:
/// <list>
/// <item>string</item>
/// <item>double</item>
/// <item>float</item>
/// <item>decimal</item>
/// <item>bool</item>
/// <item>DateTime</item>
/// <item>DateTimeOffset</item>
/// <item>TimeSpan</item>
/// <item>Any type implementing ToString()</item>
/// <item>Any type implementing IEnumerable</item>
///
/// </list>
/// When adding complex content, a number of types may be passed to this method.
/// <list>
/// <item>XObject</item>
/// <item>XNode</item>
/// <item>XAttribute</item>
/// <item>Any type implementing IEnumerable</item>
/// </list>
///
/// If an object implements IEnumerable, then the collection in the object is enumerated,
/// and all items in the collection are added. If the collection contains simple content,
/// then the simple content in the collection is concatenated and added as a single
/// string of simple content. If the collection contains complex content, then each item
/// in the collection is added separately.
///
/// If content is null, nothing is added. This allows the results of a query to be passed
/// as content. If the query returns null, no contents are added, and this method does not
/// throw a NullReferenceException.
///
/// Attributes and simple content can't be added to a document.
///
/// An added attribute must have a unique name within the element to
/// which it is being added.
/// </remarks>
public void Add(object content)
{
if (SkipNotify())
{
AddContentSkipNotify(content);
return;
}
if (content == null) return;
XNode n = content as XNode;
if (n != null)
{
AddNode(n);
return;
}
string s = content as string;
if (s != null)
{
AddString(s);
return;
}
XAttribute a = content as XAttribute;
if (a != null)
{
AddAttribute(a);
return;
}
XStreamingElement x = content as XStreamingElement;
if (x != null)
{
AddNode(new XElement(x));
return;
}
object[] o = content as object[];
if (o != null)
{
foreach (object obj in o) Add(obj);
return;
}
IEnumerable e = content as IEnumerable;
if (e != null)
{
foreach (object obj in e) Add(obj);
return;
}
AddString(GetStringValue(content));
}
/// <summary>
/// Adds the specified content as a child (or children) of this <see cref="XContainer"/>.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void Add(params object[] content)
{
Add((object)content);
}
/// <overloads>
/// Adds the specified content as the first child (or children) of this document or element. The
/// content can be simple content, a collection of content objects, a parameter
/// list of content objects, or null.
/// </overloads>
/// <summary>
/// Adds the specified content as the first child (or children) of this document or element.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added.
/// </param>
/// <remarks>
/// See <see cref="XContainer.Add(object)"/> for details about the content that can be added
/// using this method.
/// </remarks>
public void AddFirst(object content)
{
new Inserter(this, null).Add(content);
}
/// <summary>
/// Adds the specified content as the first children of this document or element.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void AddFirst(params object[] content)
{
AddFirst((object)content);
}
/// <summary>
/// Creates an <see cref="XmlWriter"/> used to add either nodes
/// or attributes to the <see cref="XContainer"/>. The later option
/// applies only for <see cref="XElement"/>.
/// </summary>
/// <returns>An <see cref="XmlWriter"/></returns>
public XmlWriter CreateWriter()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = this is XDocument ? ConformanceLevel.Document : ConformanceLevel.Fragment;
return XmlWriter.Create(new XNodeBuilder(this), settings);
}
/// <summary>
/// Get descendant elements plus leaf nodes contained in an <see cref="XContainer"/>
/// </summary>
/// <returns><see cref="IEnumerable{XNode}"/> over all descendants</returns>
public IEnumerable<XNode> DescendantNodes()
{
return GetDescendantNodes(false);
}
/// <summary>
/// Returns the descendant <see cref="XElement"/>s of this <see cref="XContainer"/>. Note this method will
/// not return itself in the resulting IEnumerable. See <see cref="XElement.DescendantsAndSelf()"/> if you
/// need to include the current <see cref="XElement"/> in the results.
/// <seealso cref="XElement.DescendantsAndSelf()"/>
/// </summary>
/// <returns>
/// An IEnumerable of <see cref="XElement"/> with all of the descendants below this <see cref="XContainer"/> in the XML tree.
/// </returns>
public IEnumerable<XElement> Descendants()
{
return GetDescendants(null, false);
}
/// <summary>
/// Returns the Descendant <see cref="XElement"/>s with the passed in <see cref="XName"/> as an IEnumerable
/// of XElement.
/// </summary>
/// <param name="name">The <see cref="XName"/> to match against descendant <see cref="XElement"/>s.</param>
/// <returns>An <see cref="IEnumerable"/> of <see cref="XElement"/></returns>
public IEnumerable<XElement> Descendants(XName name)
{
return name != null ? GetDescendants(name, false) : XElement.EmptySequence;
}
/// <summary>
/// Returns the child element with this <see cref="XName"/> or null if there is no child element
/// with a matching <see cref="XName"/>.
/// <seealso cref="XContainer.Elements()"/>
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> to match against this <see cref="XContainer"/>s child elements.
/// </param>
/// <returns>
/// An <see cref="XElement"/> child that matches the <see cref="XName"/> passed in, or null.
/// </returns>
public XElement Element(XName name)
{
XNode n = content as XNode;
if (n != null)
{
do
{
n = n.next;
XElement e = n as XElement;
if (e != null && e.name == name) return e;
} while (n != content);
}
return null;
}
///<overloads>
/// Returns the child <see cref="XElement"/>s of this <see cref="XContainer"/>.
/// </overloads>
/// <summary>
/// Returns all of the child elements of this <see cref="XContainer"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> over all of this <see cref="XContainer"/>'s child <see cref="XElement"/>s.
/// </returns>
public IEnumerable<XElement> Elements()
{
return GetElements(null);
}
/// <summary>
/// Returns the child elements of this <see cref="XContainer"/> that match the <see cref="XName"/> passed in.
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> to match against the <see cref="XElement"/> children of this <see cref="XContainer"/>.
/// </param>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> children of this <see cref="XContainer"/> that have
/// a matching <see cref="XName"/>.
/// </returns>
public IEnumerable<XElement> Elements(XName name)
{
return name != null ? GetElements(name) : XElement.EmptySequence;
}
///<overloads>
/// Returns the content of this <see cref="XContainer"/>. Note that the content does not
/// include <see cref="XAttribute"/>s.
/// <seealso cref="XElement.Attributes()"/>
/// </overloads>
/// <summary>
/// Returns the content of this <see cref="XContainer"/> as an <see cref="IEnumerable"/> of <see cref="object"/>. Note
/// that the content does not include <see cref="XAttribute"/>s.
/// <seealso cref="XElement.Attributes()"/>
/// </summary>
/// <returns>The contents of this <see cref="XContainer"/></returns>
public IEnumerable<XNode> Nodes()
{
XNode n = LastNode;
if (n != null)
{
do
{
n = n.next;
yield return n;
} while (n.parent == this && n != content);
}
}
/// <summary>
/// Removes the nodes from this <see cref="XContainer"/>. Note this
/// methods does not remove attributes. See <see cref="XElement.RemoveAttributes()"/>.
/// <seealso cref="XElement.RemoveAttributes()"/>
/// </summary>
public void RemoveNodes()
{
if (SkipNotify())
{
RemoveNodesSkipNotify();
return;
}
while (content != null)
{
string s = content as string;
if (s != null)
{
if (s.Length > 0)
{
ConvertTextToNode();
}
else
{
if (this is XElement)
{
// Change in the serialization of an empty element:
// from start/end tag pair to empty tag
NotifyChanging(this, XObjectChangeEventArgs.Value);
if ((object)s != (object)content) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
content = null;
NotifyChanged(this, XObjectChangeEventArgs.Value);
}
else
{
content = null;
}
}
}
XNode last = content as XNode;
if (last != null)
{
XNode n = last.next;
NotifyChanging(n, XObjectChangeEventArgs.Remove);
if (last != content || n != last.next) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
if (n != last)
{
last.next = n.next;
}
else
{
content = null;
}
n.parent = null;
n.next = null;
NotifyChanged(n, XObjectChangeEventArgs.Remove);
}
}
}
/// <overloads>
/// Replaces the children nodes of this document or element with the specified content. The
/// content can be simple content, a collection of content objects, a parameter
/// list of content objects, or null.
/// </overloads>
/// <summary>
/// Replaces the children nodes of this document or element with the specified content.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// that replace the children nodes.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void ReplaceNodes(object content)
{
content = GetContentSnapshot(content);
RemoveNodes();
Add(content);
}
/// <summary>
/// Replaces the children nodes of this document or element with the specified content.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void ReplaceNodes(params object[] content)
{
ReplaceNodes((object)content);
}
internal virtual void AddAttribute(XAttribute a)
{
}
internal virtual void AddAttributeSkipNotify(XAttribute a)
{
}
internal void AddContentSkipNotify(object content)
{
if (content == null) return;
XNode n = content as XNode;
if (n != null)
{
AddNodeSkipNotify(n);
return;
}
string s = content as string;
if (s != null)
{
AddStringSkipNotify(s);
return;
}
XAttribute a = content as XAttribute;
if (a != null)
{
AddAttributeSkipNotify(a);
return;
}
XStreamingElement x = content as XStreamingElement;
if (x != null)
{
AddNodeSkipNotify(new XElement(x));
return;
}
object[] o = content as object[];
if (o != null)
{
foreach (object obj in o) AddContentSkipNotify(obj);
return;
}
IEnumerable e = content as IEnumerable;
if (e != null)
{
foreach (object obj in e) AddContentSkipNotify(obj);
return;
}
AddStringSkipNotify(GetStringValue(content));
}
internal void AddNode(XNode n)
{
ValidateNode(n, this);
if (n.parent != null)
{
n = n.CloneNode();
}
else
{
XNode p = this;
while (p.parent != null) p = p.parent;
if (n == p) n = n.CloneNode();
}
ConvertTextToNode();
AppendNode(n);
}
internal void AddNodeSkipNotify(XNode n)
{
ValidateNode(n, this);
if (n.parent != null)
{
n = n.CloneNode();
}
else
{
XNode p = this;
while (p.parent != null) p = p.parent;
if (n == p) n = n.CloneNode();
}
ConvertTextToNode();
AppendNodeSkipNotify(n);
}
internal void AddString(string s)
{
ValidateString(s);
if (content == null)
{
if (s.Length > 0)
{
AppendNode(new XText(s));
}
else
{
if (this is XElement)
{
// Change in the serialization of an empty element:
// from empty tag to start/end tag pair
NotifyChanging(this, XObjectChangeEventArgs.Value);
if (content != null) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
content = s;
NotifyChanged(this, XObjectChangeEventArgs.Value);
}
else
{
content = s;
}
}
}
else if (s.Length > 0)
{
ConvertTextToNode();
XText tn = content as XText;
if (tn != null && !(tn is XCData))
{
tn.Value += s;
}
else
{
AppendNode(new XText(s));
}
}
}
internal void AddStringSkipNotify(string s)
{
ValidateString(s);
if (content == null)
{
content = s;
}
else if (s.Length > 0)
{
if (content is string)
{
content = (string)content + s;
}
else
{
XText tn = content as XText;
if (tn != null && !(tn is XCData))
{
tn.text += s;
}
else
{
AppendNodeSkipNotify(new XText(s));
}
}
}
}
internal void AppendNode(XNode n)
{
bool notify = NotifyChanging(n, XObjectChangeEventArgs.Add);
if (n.parent != null) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
AppendNodeSkipNotify(n);
if (notify) NotifyChanged(n, XObjectChangeEventArgs.Add);
}
internal void AppendNodeSkipNotify(XNode n)
{
n.parent = this;
if (content == null || content is string)
{
n.next = n;
}
else
{
XNode x = (XNode)content;
n.next = x.next;
x.next = n;
}
content = n;
}
internal override void AppendText(StringBuilder sb)
{
string s = content as string;
if (s != null)
{
sb.Append(s);
}
else
{
XNode n = (XNode)content;
if (n != null)
{
do
{
n = n.next;
n.AppendText(sb);
} while (n != content);
}
}
}
string GetTextOnly()
{
if (content == null) return null;
string s = content as string;
if (s == null)
{
XNode n = (XNode)content;
do
{
n = n.next;
if (n.NodeType != XmlNodeType.Text) return null;
s += ((XText)n).Value;
} while (n != content);
}
return s;
}
string CollectText(ref XNode n)
{
string s = "";
while (n != null && n.NodeType == XmlNodeType.Text)
{
s += ((XText)n).Value;
n = n != content ? n.next : null;
}
return s;
}
internal bool ContentsEqual(XContainer e)
{
if (content == e.content) return true;
string s = GetTextOnly();
if (s != null) return s == e.GetTextOnly();
XNode n1 = content as XNode;
XNode n2 = e.content as XNode;
if (n1 != null && n2 != null)
{
n1 = n1.next;
n2 = n2.next;
while (true)
{
if (CollectText(ref n1) != e.CollectText(ref n2)) break;
if (n1 == null && n2 == null) return true;
if (n1 == null || n2 == null || !n1.DeepEquals(n2)) break;
n1 = n1 != content ? n1.next : null;
n2 = n2 != e.content ? n2.next : null;
}
}
return false;
}
internal int ContentsHashCode()
{
string s = GetTextOnly();
if (s != null) return s.GetHashCode();
int h = 0;
XNode n = content as XNode;
if (n != null)
{
do
{
n = n.next;
string text = CollectText(ref n);
if (text.Length > 0)
{
h ^= text.GetHashCode();
}
if (n == null) break;
h ^= n.GetDeepHashCode();
} while (n != content);
}
return h;
}
internal void ConvertTextToNode()
{
string s = content as string;
if (s != null && s.Length > 0)
{
XText t = new XText(s);
t.parent = this;
t.next = t;
content = t;
}
}
internal IEnumerable<XNode> GetDescendantNodes(bool self)
{
if (self) yield return this;
XNode n = this;
while (true)
{
XContainer c = n as XContainer;
XNode first;
if (c != null && (first = c.FirstNode) != null)
{
n = first;
}
else
{
while (n != null && n != this && n == n.parent.content) n = n.parent;
if (n == null || n == this) break;
n = n.next;
}
yield return n;
}
}
internal IEnumerable<XElement> GetDescendants(XName name, bool self)
{
if (self)
{
XElement e = (XElement)this;
if (name == null || e.name == name) yield return e;
}
XNode n = this;
XContainer c = this;
while (true)
{
if (c != null && c.content is XNode)
{
n = ((XNode)c.content).next;
}
else
{
while (n != this && n == n.parent.content) n = n.parent;
if (n == this) break;
n = n.next;
}
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
c = e;
}
}
IEnumerable<XElement> GetElements(XName name)
{
XNode n = content as XNode;
if (n != null)
{
do
{
n = n.next;
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
} while (n.parent == this && n != content);
}
}
internal static string GetStringValue(object value)
{
string s;
if (value is string)
{
s = (string)value;
}
else if (value is double)
{
s = XmlConvert.ToString((double)value);
}
else if (value is float)
{
s = XmlConvert.ToString((float)value);
}
else if (value is decimal)
{
s = XmlConvert.ToString((decimal)value);
}
else if (value is bool)
{
s = XmlConvert.ToString((bool)value);
}
else if (value is DateTime)
{
s = ((DateTime)value).ToString("o"); // Round-trip date/time pattern.
}
else if (value is DateTimeOffset)
{
s = XmlConvert.ToString((DateTimeOffset)value);
}
else if (value is TimeSpan)
{
s = XmlConvert.ToString((TimeSpan)value);
}
else if (value is XObject)
{
throw new ArgumentException(SR.Argument_XObjectValue);
}
else
{
s = value.ToString();
}
if (s == null) throw new ArgumentException(SR.Argument_ConvertToString);
return s;
}
internal void ReadContentFrom(XmlReader r)
{
if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
XContainer c = this;
NamespaceCache eCache = new NamespaceCache();
NamespaceCache aCache = new NamespaceCache();
do
{
switch (r.NodeType)
{
case XmlNodeType.Element:
XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName));
if (r.MoveToFirstAttribute())
{
do
{
e.AppendAttributeSkipNotify(new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value));
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
c.AddNodeSkipNotify(e);
if (!r.IsEmptyElement)
{
c = e;
}
break;
case XmlNodeType.EndElement:
if (c.content == null)
{
c.content = string.Empty;
}
if (c == this) return;
c = c.parent;
break;
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
c.AddStringSkipNotify(r.Value);
break;
case XmlNodeType.CDATA:
c.AddNodeSkipNotify(new XCData(r.Value));
break;
case XmlNodeType.Comment:
c.AddNodeSkipNotify(new XComment(r.Value));
break;
case XmlNodeType.ProcessingInstruction:
c.AddNodeSkipNotify(new XProcessingInstruction(r.Name, r.Value));
break;
case XmlNodeType.DocumentType:
c.AddNodeSkipNotify(new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value));
break;
case XmlNodeType.EntityReference:
if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
r.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
}
} while (r.Read());
}
internal void ReadContentFrom(XmlReader r, LoadOptions o)
{
if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
{
ReadContentFrom(r);
return;
}
if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
XContainer c = this;
XNode n = null;
NamespaceCache eCache = new NamespaceCache();
NamespaceCache aCache = new NamespaceCache();
string baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null;
IXmlLineInfo li = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null;
do
{
string uri = r.BaseURI;
switch (r.NodeType)
{
case XmlNodeType.Element:
{
XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName));
if (baseUri != null && baseUri != uri)
{
e.SetBaseUri(uri);
}
if (li != null && li.HasLineInfo())
{
e.SetLineInfo(li.LineNumber, li.LinePosition);
}
if (r.MoveToFirstAttribute())
{
do
{
XAttribute a = new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
if (li != null && li.HasLineInfo())
{
a.SetLineInfo(li.LineNumber, li.LinePosition);
}
e.AppendAttributeSkipNotify(a);
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
c.AddNodeSkipNotify(e);
if (!r.IsEmptyElement)
{
c = e;
if (baseUri != null)
{
baseUri = uri;
}
}
break;
}
case XmlNodeType.EndElement:
{
if (c.content == null)
{
c.content = string.Empty;
}
// Store the line info of the end element tag.
// Note that since we've got EndElement the current container must be an XElement
XElement e = c as XElement;
Debug.Assert(e != null, "EndElement received but the current container is not an element.");
if (e != null && li != null && li.HasLineInfo())
{
e.SetEndElementLineInfo(li.LineNumber, li.LinePosition);
}
if (c == this) return;
if (baseUri != null && c.HasBaseUri)
{
baseUri = c.parent.BaseUri;
}
c = c.parent;
break;
}
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
if ((baseUri != null && baseUri != uri) ||
(li != null && li.HasLineInfo()))
{
n = new XText(r.Value);
}
else
{
c.AddStringSkipNotify(r.Value);
}
break;
case XmlNodeType.CDATA:
n = new XCData(r.Value);
break;
case XmlNodeType.Comment:
n = new XComment(r.Value);
break;
case XmlNodeType.ProcessingInstruction:
n = new XProcessingInstruction(r.Name, r.Value);
break;
case XmlNodeType.DocumentType:
n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
break;
case XmlNodeType.EntityReference:
if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
r.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
}
if (n != null)
{
if (baseUri != null && baseUri != uri)
{
n.SetBaseUri(uri);
}
if (li != null && li.HasLineInfo())
{
n.SetLineInfo(li.LineNumber, li.LinePosition);
}
c.AddNodeSkipNotify(n);
n = null;
}
} while (r.Read());
}
internal void RemoveNode(XNode n)
{
bool notify = NotifyChanging(n, XObjectChangeEventArgs.Remove);
if (n.parent != this) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
XNode p = (XNode)content;
while (p.next != n) p = p.next;
if (p == n)
{
content = null;
}
else
{
if (content == n) content = p;
p.next = n.next;
}
n.parent = null;
n.next = null;
if (notify) NotifyChanged(n, XObjectChangeEventArgs.Remove);
}
void RemoveNodesSkipNotify()
{
XNode n = content as XNode;
if (n != null)
{
do
{
XNode next = n.next;
n.parent = null;
n.next = null;
n = next;
} while (n != content);
}
content = null;
}
// Validate insertion of the given node. previous is the node after which insertion
// will occur. previous == null means at beginning, previous == this means at end.
internal virtual void ValidateNode(XNode node, XNode previous)
{
}
internal virtual void ValidateString(string s)
{
}
internal void WriteContentTo(XmlWriter writer)
{
if (content != null)
{
if (content is string)
{
if (this is XDocument)
{
writer.WriteWhitespace((string)content);
}
else
{
writer.WriteString((string)content);
}
}
else
{
XNode n = (XNode)content;
do
{
n = n.next;
n.WriteTo(writer);
} while (n != content);
}
}
}
static void AddContentToList(List<object> list, object content)
{
IEnumerable e = content is string ? null : content as IEnumerable;
if (e == null)
{
list.Add(content);
}
else
{
foreach (object obj in e)
{
if (obj != null) AddContentToList(list, obj);
}
}
}
static internal object GetContentSnapshot(object content)
{
if (content is string || !(content is IEnumerable)) return content;
List<object> list = new List<object>();
AddContentToList(list, content);
return list;
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace FickleFrostbite.FIT
{
/// <summary>
/// Implements the CoursePoint profile message.
/// </summary>
public class CoursePointMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public CoursePointMesg() : base(Profile.mesgs[Profile.CoursePointIndex])
{
}
public CoursePointMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the MessageIndex field</summary>
/// <returns>Returns nullable ushort representing the MessageIndex field</returns>
public ushort? GetMessageIndex()
{
return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MessageIndex field</summary>
/// <param name="messageIndex_">Nullable field value to be set</param>
public void SetMessageIndex(ushort? messageIndex_)
{
SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Timestamp field</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(1, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the PositionLat field
/// Units: semicircles</summary>
/// <returns>Returns nullable int representing the PositionLat field</returns>
public int? GetPositionLat()
{
return (int?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set PositionLat field
/// Units: semicircles</summary>
/// <param name="positionLat_">Nullable field value to be set</param>
public void SetPositionLat(int? positionLat_)
{
SetFieldValue(2, 0, positionLat_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the PositionLong field
/// Units: semicircles</summary>
/// <returns>Returns nullable int representing the PositionLong field</returns>
public int? GetPositionLong()
{
return (int?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set PositionLong field
/// Units: semicircles</summary>
/// <param name="positionLong_">Nullable field value to be set</param>
public void SetPositionLong(int? positionLong_)
{
SetFieldValue(3, 0, positionLong_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Distance field
/// Units: m</summary>
/// <returns>Returns nullable float representing the Distance field</returns>
public float? GetDistance()
{
return (float?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Distance field
/// Units: m</summary>
/// <param name="distance_">Nullable field value to be set</param>
public void SetDistance(float? distance_)
{
SetFieldValue(4, 0, distance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Type field</summary>
/// <returns>Returns nullable CoursePoint enum representing the Type field</returns>
new public CoursePoint? GetType()
{
object obj = GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
CoursePoint? value = obj == null ? (CoursePoint?)null : (CoursePoint)obj;
return value;
}
/// <summary>
/// Set Type field</summary>
/// <param name="type_">Nullable field value to be set</param>
public void SetType(CoursePoint? type_)
{
SetFieldValue(5, 0, type_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Name field</summary>
/// <returns>Returns byte[] representing the Name field</returns>
public byte[] GetName()
{
return (byte[])GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Name field</summary>
/// <returns>Returns String representing the Name field</returns>
public String GetNameAsString()
{
return Encoding.UTF8.GetString((byte[])GetFieldValue(6, 0, Fit.SubfieldIndexMainField));
}
///<summary>
/// Set Name field</summary>
/// <returns>Returns String representing the Name field</returns>
public void SetName(String name_)
{
SetFieldValue(6, 0, System.Text.Encoding.UTF8.GetBytes(name_), Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Name field</summary>
/// <param name="name_">field value to be set</param>
public void SetName(byte[] name_)
{
SetFieldValue(6, 0, name_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Favorite field</summary>
/// <returns>Returns nullable Bool enum representing the Favorite field</returns>
public Bool? GetFavorite()
{
object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
Bool? value = obj == null ? (Bool?)null : (Bool)obj;
return value;
}
/// <summary>
/// Set Favorite field</summary>
/// <param name="favorite_">Nullable field value to be set</param>
public void SetFavorite(Bool? favorite_)
{
SetFieldValue(8, 0, favorite_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sce.Atf;
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Atf.Controls;
using Sce.Atf.Dom;
using Sce.Sled.Shared.Controls;
using Sce.Sled.Lua.Dom;
using Sce.Sled.Lua.Resources;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Dom;
using Sce.Sled.Shared.Plugin;
using Sce.Sled.Shared.Services;
using Sce.Sled.Shared.Utilities;
namespace Sce.Sled.Lua
{
[Export(typeof(IInitializable))]
[Export(typeof(ISledProjectSettingsPlugin))]
[Export(typeof(SledLuaProfilerService))]
[PartCreationPolicy(CreationPolicy.Shared)]
sealed class SledLuaProfilerService : IInitializable, ICommandClient, ISledProjectSettingsPlugin
{
[ImportingConstructor]
public SledLuaProfilerService(ICommandService commandService)
{
commandService.RegisterCommand(
Command.Toggle,
SledLuaMenuShared.MenuTag,
SledLuaMenuShared.CommandGroupTag,
Localization.SledLuaToggleLuaProfiler,
Localization.SledLuaToggleLuaProfilerComment,
Keys.None,
SledIcon.ProjectToggleProfiler,
CommandVisibility.All,
this);
}
#region IInitializable Interface
void IInitializable.Initialize()
{
m_luaLanguagePlugin =
SledServiceInstance.Get<SledLuaLanguagePlugin>();
m_debugService =
SledServiceInstance.Get<ISledDebugService>();
m_debugService.DataReady += DebugServiceDataReady;
m_debugService.UpdateEnd += DebugServiceUpdateEnd;
m_debugService.Disconnected += DebugServiceDisconnected;
var projectService =
SledServiceInstance.Get<ISledProjectService>();
projectService.Created += ProjectServiceCreated;
projectService.Opened += ProjectServiceOpened;
projectService.Saved += ProjectServiceSaved;
projectService.Closing += ProjectServiceClosing;
m_editor.MouseDoubleClick += EditorMouseDoubleClick;
m_funcCallsEditor.MouseDoubleClick += FuncCallsEditorMouseDoubleClick;
m_funcCallsEditor.TreeListViewAdapter.ItemLazyLoad += FuncCallsEditorItemLazyLoad;
// Adjust to shortened name if this language plugin is the only one loaded
if (m_languagePluginService.Get.Count != 1)
return;
m_editor.Name = Localization.SledLuaProfileInfoTitleShort;
m_funcCallsEditor.Name = Localization.SledLuaProfileFuncCallsTitleShort;
}
#endregion
#region Commands
enum Command
{
Toggle,
}
#endregion
#region ICommandClient Interface
public bool CanDoCommand(object commandTag)
{
var bEnabled = false;
if (commandTag is Command)
{
switch ((Command)commandTag)
{
case Command.Toggle:
bEnabled = m_bProfilerEnabled && m_debugService.IsConnected;
break;
}
}
return bEnabled;
}
public void DoCommand(object commandTag)
{
if (!(commandTag is Command))
return;
switch ((Command)commandTag)
{
case Command.Toggle:
ToggleProfiler();
break;
}
}
public void UpdateCommand(object commandTag, CommandState state)
{
if (!(commandTag is Command))
return;
switch ((Command)commandTag)
{
case Command.Toggle:
state.Check = m_bProfilerRunning;
break;
}
}
#endregion
#region ISledProjectSettingsPlugin Interface
public bool NeedsSaving()
{
return
m_bDirty &&
(m_collection != null) &&
(m_collection.ProfileInfo.Count > 0);
}
#endregion
#region ISledDebugService Events
private void DebugServiceDataReady(object sender, SledDebugServiceEventArgs e)
{
var typeCode = (Scmp.LuaTypeCodes)e.Scmp.TypeCode;
switch (typeCode)
{
case Scmp.LuaTypeCodes.LuaProfileInfoBegin:
RemoteTargetProfileInfoNew();
break;
case Scmp.LuaTypeCodes.LuaProfileInfo:
{
var scmp =
m_debugService.GetScmpBlob<Scmp.LuaProfileInfo>();
var domNode =
new DomNode(SledSchema.SledProfileInfoType.Type);
var pi = domNode.As<SledProfileInfoType>();
pi.Function = m_luaFunctionParserService.Get.LookUpFunction(scmp.FunctionName);
pi.TimeTotal = scmp.FnTimeElapsed;
pi.TimeAverage = scmp.FnTimeElapsedAvg;
pi.TimeMin = scmp.FnTimeElapsedShortest;
pi.TimeMax = scmp.FnTimeElapsedLongest;
pi.TimeTotalInner = scmp.FnTimeInnerElapsed;
pi.TimeAverageInner = scmp.FnTimeInnerElapsedAvg;
pi.TimeMinInner = scmp.FnTimeInnerElapsedShortest;
pi.TimeMaxInner = scmp.FnTimeInnerElapsedLongest;
pi.NumCalls = (int)scmp.FnCallCount;
pi.Line = scmp.FnLine;
pi.File = scmp.RelScriptPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToLower();
pi.NumFuncsCalled = scmp.FnCalls;
pi.GenerateUniqueName();
RemoteTargetProfileInfoAdd(pi);
RemoteTargetProfileFuncCallAdd((SledProfileInfoType)pi.Clone());
}
break;
case Scmp.LuaTypeCodes.LuaProfileInfoEnd:
RemoteTargetProfileFuncCallEnd();
break;
//case Scmp.LuaTypeCodes.LuaProfileInfoLookupBegin:
// break;
case Scmp.LuaTypeCodes.LuaProfileInfoLookup:
{
var scmp =
m_debugService.GetScmpBlob<Scmp.LuaProfileInfoLookup>();
var domNode =
new DomNode(SledSchema.SledProfileInfoType.Type);
var pi = domNode.As<SledProfileInfoType>();
pi.Function = m_luaFunctionParserService.Get.LookUpFunction(scmp.FunctionName);
pi.TimeTotal = scmp.FnTimeElapsed;
pi.TimeAverage = scmp.FnTimeElapsedAvg;
pi.TimeMin = scmp.FnTimeElapsedShortest;
pi.TimeMax = scmp.FnTimeElapsedLongest;
pi.TimeTotalInner = scmp.FnTimeInnerElapsed;
pi.TimeAverageInner = scmp.FnTimeInnerElapsedAvg;
pi.TimeMinInner = scmp.FnTimeInnerElapsedShortest;
pi.TimeMaxInner = scmp.FnTimeInnerElapsedLongest;
pi.NumCalls = (int)scmp.FnCallCount;
pi.Line = scmp.FnLine;
pi.File = scmp.RelScriptPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToLower();
pi.NumFuncsCalled = scmp.FnCalls;
pi.GenerateUniqueName();
RemoteTargetProfileFuncCallLookUpAdd(pi);
}
break;
case Scmp.LuaTypeCodes.LuaProfileInfoLookupEnd:
RemoteTargetProfileLookUpFinished();
break;
case Scmp.LuaTypeCodes.LuaLimits:
{
var scmp = m_debugService.GetScmpBlob<Scmp.LuaLimits>();
m_bProfilerEnabled = scmp.ProfilerEnabled;
if (!m_bProfilerEnabled)
{
SledOutDevice.OutLine(
SledMessageType.Info,
"[Lua] Profiler is disabled due to target settings.");
}
}
break;
}
}
private void DebugServiceUpdateEnd(object sender, SledDebugServiceBreakpointEventArgs e)
{
m_editor.View = m_collection;
m_funcCallsEditor.View = m_funcCallsCollection;
}
private void DebugServiceDisconnected(object sender, SledDebugServiceEventArgs e)
{
if (m_bProfilerRunning)
ToggleProfiler();
m_bProfilerEnabled = false;
}
#endregion
#region ISledProjectService Events
private void ProjectServiceCreated(object sender, SledProjectServiceProjectEventArgs e)
{
CreateProfileInfoCollection();
CreateProfileFuncCallCollection();
}
private void ProjectServiceOpened(object sender, SledProjectServiceProjectEventArgs e)
{
CreateProfileInfoCollection();
CreateProfileFuncCallCollection();
}
private void ProjectServiceSaved(object sender, SledProjectServiceProjectEventArgs e)
{
WriteToDisk();
}
private void ProjectServiceClosing(object sender, SledProjectServiceProjectEventArgs e)
{
DestroyProfileInfoCollection();
DestroyProfileFuncCallsCollection();
}
#endregion
#region Member Methods
private void ToggleProfiler()
{
m_debugService.SendScmp(
new Scmp.LuaProfilerToggle(
m_luaLanguagePlugin.LanguageId));
m_bProfilerRunning = !m_bProfilerRunning;
if (!m_bProfilerRunning)
return;
m_editor.View = null;
m_collection.ProfileInfo.Clear();
m_editor.View = m_collection;
m_funcCallsEditor.View = null;
m_funcCallsCollection.ProfileInfo.Clear();
m_funcCallsEditor.View = m_funcCallsCollection;
}
private void CreateProfileInfoCollection()
{
var root =
new DomNode(
SledSchema.SledProfileInfoListType.Type,
SledLuaSchema.SledLuaProfileInfoRootElement);
m_collection =
root.As<SledProfileInfoListType>();
m_collection.Name =
string.Format(
"{0}{1}{2}",
m_projectService.Get.ProjectName,
Resources.Resource.Space,
Resources.Resource.LuaProfileInfo);
m_collection.DisplayMode =
SledProfileInfoListType.Display.Normal;
m_bDirty = false;
}
private void CreateProfileFuncCallCollection()
{
var root =
new DomNode(
SledSchema.SledProfileInfoListType.Type,
SledLuaSchema.SledLuaProfileFuncCallsRootElement);
m_funcCallsCollection =
root.As<SledProfileInfoListType>();
m_funcCallsCollection.Name =
string.Format(
"{0}{1}{2}",
m_projectService.Get.ProjectName,
Resources.Resource.Space,
Resources.Resource.LuaProfileFuncCalls);
m_funcCallsCollection.DisplayMode =
SledProfileInfoListType.Display.CallGraph;
}
private void DestroyProfileInfoCollection()
{
// Clear GUI
m_editor.View = null;
m_collection.ProfileInfo.Clear();
m_collection = null;
}
private void DestroyProfileFuncCallsCollection()
{
// Clear GUI
m_funcCallsEditor.View = null;
m_funcCallsCollection.ProfileInfo.Clear();
m_funcCallsCollection = null;
}
private void RemoteTargetProfileInfoNew()
{
m_editor.View = null;
m_collection.ProfileInfo.Clear();
m_editor.View = m_collection;
m_funcCallsEditor.View = null;
m_funcCallsCollection.ProfileInfo.Clear();
m_funcCallsEditor.View = m_funcCallsCollection;
}
private void RemoteTargetProfileLookUpFinished()
{
if (m_lstQueuedProfileLookUps.Count <= 0)
return;
m_lstQueuedProfileLookUps.RemoveAt(0);
}
private void RemoteTargetProfileInfoAdd(SledProfileInfoType pi)
{
m_collection.ProfileInfo.Add(pi);
m_bDirty = true;
}
private void RemoteTargetProfileFuncCallAdd(SledProfileInfoType pi)
{
m_funcCallsCollection.ProfileInfo.Add(pi);
}
private void RemoteTargetProfileFuncCallEnd()
{
m_funcCallsEditor.View = m_funcCallsCollection;
}
private void RemoteTargetProfileFuncCallLookUpAdd(SledProfileInfoType pi)
{
if (m_lstQueuedProfileLookUps.Count > 0)
m_lstQueuedProfileLookUps[0].ProfileInfo.Add(pi);
}
private void EditorMouseDoubleClick(object sender, MouseEventArgs e)
{
var editor = sender.As<SledLuaProfileEditor>();
if (editor == null)
return;
if (editor.LastHit == null)
return;
var pi = editor.LastHit.As<SledProfileInfoType>();
if (pi == null)
return;
var szAbsPath =
SledUtil.GetAbsolutePath(
pi.File,
m_projectService.Get.AssetDirectory);
if (!File.Exists(szAbsPath))
return;
m_gotoService.Get.GotoLine(szAbsPath, pi.Line, false);
}
private void FuncCallsEditorMouseDoubleClick(object sender, MouseEventArgs e)
{
var editor = sender.As<SledLuaProfileFuncCallsEditor>();
if (editor == null)
return;
if (editor.LastHit == null)
return;
var pi = editor.LastHit.As<SledProfileInfoType>();
if (pi == null)
return;
var szAbsPath =
SledUtil.GetAbsolutePath(
pi.File,
m_projectService.Get.AssetDirectory);
if (!File.Exists(szAbsPath))
return;
m_gotoService.Get.GotoLine(szAbsPath, pi.Line, false);
}
private void FuncCallsEditorItemLazyLoad(object sender, TreeListViewAdapter.ItemLazyLoadEventArgs e)
{
if (!m_debugService.IsConnected)
return;
if (m_debugService.IsDebugging)
return;
if (e.Item == null)
return;
var pi = e.Item.As<SledProfileInfoType>();
if (pi == null)
return;
if (m_lstQueuedProfileLookUps.Contains(pi))
return;
// TODO: FIX ME
var lookup = string.Empty;
//m_luaGenerateLookUpStringService.Get.GenerateLookUpString(pi);
if (string.IsNullOrEmpty(lookup))
return;
m_lstQueuedProfileLookUps.Add(pi);
//SledOutDevice.OutLine(
// SledMessageType.Error,
// string.Format("[Lookup] {0}", lookup));
// Send off message
m_debugService.SendScmp(
new Scmp.LuaProfileInfoLookupPerform(
m_luaLanguagePlugin.LanguageId,
lookup));
}
private void WriteToDisk()
{
if (!m_bDirty)
return;
try
{
if (m_collection == null)
return;
if (m_collection.ProfileInfo.Count <= 0)
return;
var schemaLoader =
SledServiceInstance.Get<SledSharedSchemaLoader>();
if (schemaLoader == null)
return;
var projDir =
m_projectService.Get.ProjectDirectory;
var filePath =
Path.Combine(
projDir + Path.DirectorySeparatorChar,
m_collection.Name + ".xml");
var uri = new Uri(filePath);
using (var stream =
new FileStream(uri.LocalPath, FileMode.Create, FileAccess.Write))
{
var writer =
new DomXmlWriter(schemaLoader.TypeCollection);
writer.Write(m_collection.DomNode, stream, uri);
}
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
"[SledLuaProfilerService] Failure to " +
"save profiler data to disk: {0}",
ex.Message);
}
finally
{
m_bDirty = false;
}
}
#endregion
private ISledDebugService m_debugService;
private SledLuaLanguagePlugin m_luaLanguagePlugin;
private bool m_bDirty;
private bool m_bProfilerEnabled;
private bool m_bProfilerRunning;
#pragma warning disable 649 // Field is never assigned
[Import]
private SledLuaProfileEditor m_editor;
[Import]
private SledLuaProfileFuncCallsEditor m_funcCallsEditor;
#pragma warning restore 649
private SledProfileInfoListType m_collection;
private SledProfileInfoListType m_funcCallsCollection;
private readonly List<SledProfileInfoType> m_lstQueuedProfileLookUps =
new List<SledProfileInfoType>();
private readonly SledServiceReference<ISledGotoService> m_gotoService =
new SledServiceReference<ISledGotoService>();
private readonly SledServiceReference<ISledProjectService> m_projectService =
new SledServiceReference<ISledProjectService>();
private readonly SledServiceReference<ISledLanguagePluginService> m_languagePluginService =
new SledServiceReference<ISledLanguagePluginService>();
private readonly SledServiceReference<ISledLuaFunctionParserService> m_luaFunctionParserService =
new SledServiceReference<ISledLuaFunctionParserService>();
#region Private Classes
private class MySorter : IComparer<TreeListView.Node>
{
public MySorter(TreeListView control)
{
m_control = control;
}
public int Compare(TreeListView.Node x, TreeListView.Node y)
{
if ((x == null) && (y == null))
return 0;
if (x == null)
return 1;
if (y == null)
return -1;
if (ReferenceEquals(x, y))
return 0;
if ((x.Tag.Is<SledProfileInfoType>()) &&
(y.Tag.Is<SledProfileInfoType>()))
{
return
SledProfileInfoType.Compare(
x.Tag.As<SledProfileInfoType>(),
y.Tag.As<SledProfileInfoType>(),
m_control.SortColumn,
m_control.SortOrder);
}
return string.Compare(x.Label, y.Label, StringComparison.Ordinal);
}
private readonly TreeListView m_control;
}
[Export(typeof(SledLuaProfileEditor))]
[Export(typeof(IContextMenuCommandProvider))]
[PartCreationPolicy(CreationPolicy.Shared)]
private class SledLuaProfileEditor : SledTreeListViewEditor, IContextMenuCommandProvider
{
[ImportingConstructor]
public SledLuaProfileEditor()
: base(
Localization.SledLuaProfileInfoTitle,
SledIcon.ProjectToggleProfiler,
SledProfileInfoType.NormalColumnNames,
TreeListView.Style.List,
StandardControlGroup.Right)
{
AllowDebugFreeze = true;
TreeListView.NodeSorter = new MySorter(TreeListView);
}
#region Implementation of IContextMenuCommandProvider
public IEnumerable<object> GetCommands(object context, object target)
{
if (!ReferenceEquals(context, TreeListViewAdapter.View))
yield break;
var clicked = target.As<SledProfileInfoType>();
if (clicked == null)
yield break;
yield return StandardCommand.EditCopy;
}
#endregion
#region SledTreeListViewEditor Overrides
protected override string GetCopyText()
{
if ((TreeListViewAdapter == null) ||
(!TreeListViewAdapter.Selection.Any()))
return string.Empty;
const string tab = "\t";
var sb = new StringBuilder();
var items = TreeListViewAdapter.Selection.AsIEnumerable<SledProfileInfoType>();
foreach (var item in items)
{
sb.Append(item.Function);
sb.Append(tab);
sb.Append(item.NumCalls);
sb.Append(tab);
sb.Append(item.TimeTotal);
sb.Append(tab);
sb.Append(item.TimeAverage);
sb.Append(tab);
sb.Append(item.TimeMin);
sb.Append(tab);
sb.Append(item.TimeMax);
sb.Append(tab);
sb.Append(item.TimeTotalInner);
sb.Append(tab);
sb.Append(item.TimeAverageInner);
sb.Append(tab);
sb.Append(item.TimeMinInner);
sb.Append(tab);
sb.Append(item.TimeMaxInner);
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
#endregion
}
[Export(typeof(SledLuaProfileFuncCallsEditor))]
[Export(typeof(IContextMenuCommandProvider))]
[PartCreationPolicy(CreationPolicy.Shared)]
private class SledLuaProfileFuncCallsEditor : SledTreeListViewEditor, IContextMenuCommandProvider
{
[ImportingConstructor]
public SledLuaProfileFuncCallsEditor()
: base(
Localization.SledLuaProfileFuncCallsTitle,
SledIcon.ProjectToggleProfiler,
SledProfileInfoType.CallGraphColumnNames,
TreeListView.Style.TreeList,
StandardControlGroup.Right)
{
AllowDebugFreeze = true;
TreeListView.NodeSorter = new MySorter(TreeListView);
//UseManualQueue = true;
//ManualQueuePulsed += SledListTreeViewEditorManualQueuePulsed;
}
#region Implementation of IContextMenuCommandProvider
public IEnumerable<object> GetCommands(object context, object target)
{
if (!ReferenceEquals(context, TreeListViewAdapter.View))
yield break;
var clicked = target.As<SledProfileInfoType>();
if (clicked == null)
yield break;
yield return StandardCommand.EditCopy;
}
#endregion
#region SledTreeListViewEditor Overrides
protected override string GetCopyText()
{
if ((TreeListViewAdapter == null) ||
(!TreeListViewAdapter.Selection.Any()))
return string.Empty;
var sb = new StringBuilder();
var items = TreeListViewAdapter.Selection.AsIEnumerable<SledProfileInfoType>();
foreach (var item in items)
{
sb.Append(item.Function);
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
#endregion
//public void Finish()
//{
// PulseManualQueue();
//}
//private void SledListTreeViewEditorManualQueuePulsed(object sender, EventArgs e)
//{
// FinishNotify();
//}
//[System.Diagnostics.Conditional("DEBUG")]
//private static void FinishNotify()
//{
// var szWhat = Resources.Resource.LuaProfileFuncCalls;
// SledOutDevice.OutLine(SledMessageType.Info, string.Format("[{0}] Finish() Called", szWhat));
//}
}
//private class SledLuaProfileListTreeViewAdapter : SledListTreeViewAdapter
//{
// public override IEnumerable<object> Items
// {
// get
// {
// if (Root == null)
// yield break;
// foreach (var child in Root.Subtree)
// {
// if (child.Is<SledProfileInfoType>())
// yield return child.As<SledProfileInfoType>();
// }
// }
// }
//}
#endregion
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Describes a long-running process that represents a change to your Auto Scaling group,
/// such as changing its size. This can also be a process to replace an instance, or a
/// process to perform any other long-running operations.
/// </summary>
public partial class Activity
{
private string _activityId;
private string _autoScalingGroupName;
private string _cause;
private string _description;
private string _details;
private DateTime? _endTime;
private int? _progress;
private DateTime? _startTime;
private ScalingActivityStatusCode _statusCode;
private string _statusMessage;
/// <summary>
/// Gets and sets the property ActivityId.
/// <para>
/// The ID of the activity.
/// </para>
/// </summary>
public string ActivityId
{
get { return this._activityId; }
set { this._activityId = value; }
}
// Check to see if ActivityId property is set
internal bool IsSetActivityId()
{
return this._activityId != null;
}
/// <summary>
/// Gets and sets the property AutoScalingGroupName.
/// <para>
/// The name of the Auto Scaling group.
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this._autoScalingGroupName; }
set { this._autoScalingGroupName = value; }
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this._autoScalingGroupName != null;
}
/// <summary>
/// Gets and sets the property Cause.
/// <para>
/// The reason the activity was begun.
/// </para>
/// </summary>
public string Cause
{
get { return this._cause; }
set { this._cause = value; }
}
// Check to see if Cause property is set
internal bool IsSetCause()
{
return this._cause != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A friendly, more verbose description of the scaling activity.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property Details.
/// <para>
/// The details about the scaling activity.
/// </para>
/// </summary>
public string Details
{
get { return this._details; }
set { this._details = value; }
}
// Check to see if Details property is set
internal bool IsSetDetails()
{
return this._details != null;
}
/// <summary>
/// Gets and sets the property EndTime.
/// <para>
/// The end time of this activity.
/// </para>
/// </summary>
public DateTime EndTime
{
get { return this._endTime.GetValueOrDefault(); }
set { this._endTime = value; }
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this._endTime.HasValue;
}
/// <summary>
/// Gets and sets the property Progress.
/// <para>
/// A value between 0 and 100 that indicates the progress of the activity.
/// </para>
/// </summary>
public int Progress
{
get { return this._progress.GetValueOrDefault(); }
set { this._progress = value; }
}
// Check to see if Progress property is set
internal bool IsSetProgress()
{
return this._progress.HasValue;
}
/// <summary>
/// Gets and sets the property StartTime.
/// <para>
/// The start time of this activity.
/// </para>
/// </summary>
public DateTime StartTime
{
get { return this._startTime.GetValueOrDefault(); }
set { this._startTime = value; }
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this._startTime.HasValue;
}
/// <summary>
/// Gets and sets the property StatusCode.
/// <para>
/// The current status of the activity.
/// </para>
/// </summary>
public ScalingActivityStatusCode StatusCode
{
get { return this._statusCode; }
set { this._statusCode = value; }
}
// Check to see if StatusCode property is set
internal bool IsSetStatusCode()
{
return this._statusCode != null;
}
/// <summary>
/// Gets and sets the property StatusMessage.
/// <para>
/// A friendly, more verbose description of the activity status.
/// </para>
/// </summary>
public string StatusMessage
{
get { return this._statusMessage; }
set { this._statusMessage = value; }
}
// Check to see if StatusMessage property is set
internal bool IsSetStatusMessage()
{
return this._statusMessage != null;
}
}
}
| |
using Aspose.Tasks;
using Aspose.Tasks.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Aspose.Tasks.Live.Demos.UI.Models;
using System.Reflection;
namespace Aspose.Tasks.Live.Demos.UI.Controllers
{
/// <summary>
/// AsposeTasksMetadataController class
/// </summary>
public class AsposeTasksMetadataController : TasksBase
{
///<Summary>
/// Properties method to get metadata
///</Summary>
///
[HttpPost]
public HttpResponseMessage Properties(string folderName, string fileName)
{
try
{
Project project = new Project(Path.Combine(Config.Configuration.WorkingDirectory, folderName, fileName));
return Request.CreateResponse(HttpStatusCode.OK, new PropertiesResponse(project));
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
}
}
///<Summary>
/// Properties method. Should include 'FileName', 'id', 'properties' as params
///</Summary>
[HttpPost]
[AcceptVerbs("GET", "POST")]
public Response Download()
{
Aspose.Tasks.Live.Demos.UI.Models.License.SetAsposeTasksLicense();
Opts.AppName = "MetadataApp";
Opts.MethodName = "Download";
try
{
var request = Request.Content.ReadAsAsync<JObject>().Result;
Opts.FileName = Convert.ToString(request["FileName"]);
Opts.ResultFileName = Opts.FileName;
Opts.FolderName = Convert.ToString(request["id"]);
Project project = new Project(Opts.WorkingFileName);
var pars = request["properties"]["BuiltIn"].ToObject<List<DocProperty>>();
SetBuiltInProperties(project, pars);
pars = request["properties"]["Custom"].ToObject<List<DocProperty>>();
SetCustomProperties(project, pars);
return Process((inFilePath, outPath, zipOutFolder) => { project.Save(outPath, Aspose.Tasks.Saving.SaveFileFormat.MPP); });
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new Response
{
Status = "500 " + ex.Message,
StatusCode = 500
};
}
}
//<Summary>
// Properties method.Should include 'FileName', 'id' as params
//</Summary>
[HttpPost]
[AcceptVerbs("GET", "POST")]
public Response Clear()
{
Opts.AppName = "MetadataApp";
Opts.MethodName = "Clear";
try
{
var request = Request.Content.ReadAsAsync<JObject>().Result;
Opts.FileName = Convert.ToString(request["FileName"]);
Opts.ResultFileName = Opts.FileName;
Opts.FolderName = Convert.ToString(request["id"]);
Project project = new Project(Opts.WorkingFileName);
project.CustomProps.Clear();
return Process((inFilePath, outPath, zipOutFolder) => { project.Save(outPath, Aspose.Tasks.Saving.SaveFileFormat.MPP); });
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new Response
{
Status = "500 " + ex.Message,
StatusCode = 500
};
}
}
/// <summary>
/// SetBuiltInProperties
/// </summary>
/// <param name="workbook"></param>
/// <param name="pars"></param>
private void SetBuiltInProperties(Project project, List<DocProperty> pars)
{
var builtin = project.BuiltInProps;
var t = builtin.GetType();
foreach (var par in pars)
{
var prop = t.GetProperty(par.Name);
if (prop != null)
switch (par.Type)
{
case PropertyType.String:
prop.SetValue(builtin, Convert.ToString(par.Value));
break;
case PropertyType.Boolean:
prop.SetValue(builtin, Convert.ToBoolean(par.Value));
break;
case PropertyType.Number:
prop.SetValue(builtin, Convert.ToInt32(par.Value));
break;
case PropertyType.DateTime:
prop.SetValue(builtin, Convert.ToDateTime(par.Value));
break;
case PropertyType.Double:
prop.SetValue(builtin, Convert.ToDouble(par.Value));
break;
}
}
}
/// <summary>
/// SetCustomProperties
/// </summary>
/// <param name="workbook"></param>
/// <param name="pars"></param>
private void SetCustomProperties(Project project, List<DocProperty> pars)
{
var custom = project.CustomProps;
custom.Clear();
foreach (var par in pars)
switch (par.Type)
{
case PropertyType.String:
custom.Add(par.Name, Convert.ToString(par.Value));
break;
case PropertyType.Boolean:
custom.Add(par.Name, Convert.ToBoolean(par.Value));
break;
case PropertyType.Number:
custom.Add(par.Name, Convert.ToInt32(par.Value));
break;
case PropertyType.DateTime:
custom.Add(par.Name, Convert.ToDateTime(par.Value));
break;
case PropertyType.Double:
custom.Add(par.Name, Convert.ToDouble(par.Value));
break;
}
}
/// <summary>
/// PropertiesResponse
/// </summary>
private class PropertiesResponse
{
//public BuiltInProjectPropertyCollection BuiltIn { get; set; }
//public CustomProjectPropertyCollection Custom { get; set; }
public List<DocProperty> BuiltIn { get; set; }
public List<DocProperty> Custom { get; set; }
public PropertiesResponse(Project project)
{
BuiltIn = new List<DocProperty>();
Custom = new List<DocProperty>();
foreach (var obj in project.BuiltInProps)
{
DocProperty metadataObject = new DocProperty
{
Name = obj.Name,
Value = obj.Value,
Type = PropertyType.String
};
BuiltIn.Add(metadataObject);
}
foreach (var obj in project.CustomProps)
{
string value = obj.Type.ToString();
PropertyType propertyType = PropertyType.None;
switch (value.ToLower())
{
case "string":
propertyType = PropertyType.String;
break;
case "datetime":
propertyType = PropertyType.DateTime;
break;
case "number":
propertyType = PropertyType.Number;
break;
case "boolean":
propertyType = PropertyType.Boolean;
break;
}
DocProperty metadataObject = new DocProperty
{
Name = obj.Name,
Value = obj.Value,
Type = propertyType
};
Custom.Add(metadataObject);
}
}
}
/// <summary>
/// The same fields as in DocumentProperty
/// </summary>
private class DocProperty
{
public string Name { get; set; }
public object Value { get; set; }
public PropertyType Type { get; set; }
}
public enum PropertyType
{
/// <summary>The property is a None value.</summary>
None,
/// <summary>The property is a String value.</summary>
String,
/// <summary>The property is a Date Time Value.</summary>
DateTime,
/// <summary>The property is an integer number.</summary>
Number,
/// <summary>The property is a Boolean.</summary>
Boolean,
/// <summary>The property is a Double.</summary>
Double,
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.Security.Principal;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Profile;
namespace RestMvc
{
/// <summary>
/// To handle HEAD requests, we need to capture the output of a GET
/// without sending the result to the user. The only way I could think
/// of handling that was by proxying the HttpContext, and replacing
/// the Response.Output.
/// </summary>
public class HttpContextWithReadableOutputStream : HttpContextBase, IDisposable
{
private readonly Controller controller;
private readonly HttpContextBase proxiedContext;
private readonly ResponseWithReadableOutputStream response;
public HttpContextWithReadableOutputStream(Controller controller)
{
this.controller = controller;
proxiedContext = controller.ControllerContext.HttpContext;
response = new ResponseWithReadableOutputStream(proxiedContext.Response);
controller.ControllerContext.HttpContext = this;
}
public virtual string GetResponseText()
{
return response.OutputText;
}
public override HttpResponseBase Response
{
get { return response; }
}
#region Proxied Methods
public override void AddError(Exception errorInfo)
{
proxiedContext.AddError(errorInfo);
}
public override Exception[] AllErrors
{
get { return proxiedContext.AllErrors; }
}
public override HttpApplicationStateBase Application
{
get { return proxiedContext.Application; }
}
public override HttpApplication ApplicationInstance
{
get { return proxiedContext.ApplicationInstance; }
set { proxiedContext.ApplicationInstance = value; }
}
public override Cache Cache
{
get { return proxiedContext.Cache; }
}
public override void ClearError()
{
proxiedContext.ClearError();
}
public override IHttpHandler CurrentHandler
{
get { return proxiedContext.CurrentHandler; }
}
public override RequestNotification CurrentNotification
{
get { return proxiedContext.CurrentNotification; }
}
public override Exception Error
{
get { return proxiedContext.Error; }
}
public override object GetGlobalResourceObject(string classKey, string resourceKey)
{
return proxiedContext.GetGlobalResourceObject(classKey, resourceKey);
}
public override object GetGlobalResourceObject(string classKey, string resourceKey, CultureInfo culture)
{
return proxiedContext.GetGlobalResourceObject(classKey, resourceKey, culture);
}
public override object GetLocalResourceObject(string virtualPath, string resourceKey)
{
return proxiedContext.GetLocalResourceObject(virtualPath, resourceKey);
}
public override object GetLocalResourceObject(string virtualPath, string resourceKey, CultureInfo culture)
{
return proxiedContext.GetLocalResourceObject(virtualPath, resourceKey, culture);
}
public override object GetSection(string sectionName)
{
return proxiedContext.GetSection(sectionName);
}
public override object GetService(Type serviceType)
{
return proxiedContext.GetService(serviceType);
}
public override IHttpHandler Handler
{
get { return proxiedContext.Handler; }
set { proxiedContext.Handler = value; }
}
public override bool IsCustomErrorEnabled
{
get { return proxiedContext.IsCustomErrorEnabled; }
}
public override bool IsDebuggingEnabled
{
get { return proxiedContext.IsDebuggingEnabled; }
}
public override bool IsPostNotification
{
get { return proxiedContext.IsPostNotification; }
}
public override IDictionary Items
{
get { return proxiedContext.Items; }
}
public override IHttpHandler PreviousHandler
{
get { return proxiedContext.PreviousHandler; }
}
public override ProfileBase Profile
{
get { return proxiedContext.Profile; }
}
public override HttpRequestBase Request
{
get { return proxiedContext.Request; }
}
public override void RewritePath(string filePath, string pathInfo, string queryString)
{
proxiedContext.RewritePath(filePath, pathInfo, queryString);
}
public override void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath)
{
proxiedContext.RewritePath(filePath, pathInfo, queryString, setClientFilePath);
}
public override void RewritePath(string path)
{
proxiedContext.RewritePath(path);
}
public override void RewritePath(string path, bool rebaseClientPath)
{
proxiedContext.RewritePath(path, rebaseClientPath);
}
public override HttpServerUtilityBase Server
{
get { return proxiedContext.Server; }
}
public override HttpSessionStateBase Session
{
get { return proxiedContext.Session; }
}
public override bool SkipAuthorization
{
get { return proxiedContext.SkipAuthorization; }
set { proxiedContext.SkipAuthorization = value; }
}
public override DateTime Timestamp
{
get { return proxiedContext.Timestamp; }
}
public override TraceContext Trace
{
get { return proxiedContext.Trace; }
}
public override IPrincipal User
{
get { return proxiedContext.User; }
set { proxiedContext.User = value; }
}
#endregion
public void Dispose()
{
controller.ControllerContext.HttpContext = proxiedContext;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ImageIndexConverter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Windows.Forms {
using Microsoft.Win32;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Collections.Specialized;
/// <include file='doc\ImageKeyConverter.uex' path='docs/doc[@for="ImageKeyConverter"]/*' />
/// <devdoc>
/// ImageIndexConverter is a class that can be used to convert
/// image index values one data type to another.
/// </devdoc>
public class ImageKeyConverter : StringConverter {
private string parentImageListProperty = "Parent";
/// <include file='doc\ImageKeyConverter.uex' path='docs/doc[@for="ImageKeyConverter.IncludeNoneAsStandardValue"]/*' />
protected virtual bool IncludeNoneAsStandardValue {
get {
return true;
}
}
/// <devdoc>
/// this is the property to look at when there is no ImageList property
/// on the current object. For example, in ToolBarButton - the ImageList is
/// on the ToolBarButton.Parent property. In WinBarItem, the ImageList is on
/// the WinBarItem.Owner property.
/// </devdoc>
internal string ParentImageListProperty {
get {
return parentImageListProperty;
}
set {
parentImageListProperty = value;
}
}
/// <include file='doc\ImageKeyConverter.uex' path='docs/doc[@for="ImageKeyConverter.CanConvertFrom"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether this converter can convert an object in the
/// given source type to a string using the specified context.</para>
/// </devdoc>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <include file='doc\ImageKeyConverter.uex' path='docs/doc[@for="ImageKeyConverter.ConvertFrom"]/*' />
/// <devdoc>
/// <para>Converts the specified value object to a string object.</para>
/// </devdoc>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
if (value is string) {
return (string)value;
}
if (value == null) {
return "";
}
return base.ConvertFrom(context, culture, value);
}
/// <include file='doc\ImageKeyConverter.uex' path='docs/doc[@for="ImageKeyConverter.ConvertTo"]/*' />
/// <devdoc>
/// Converts the given object to another type. The most common types to convert
/// are to and from a string object. The default implementation will make a call
/// to ToString on the object if the object is valid and if the destination
/// type is string. If this cannot convert to the desitnation type, this will
/// throw a NotSupportedException.
/// </devdoc>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw new ArgumentNullException("destinationType");
}
if (destinationType == typeof(string) && value != null && value is string && ((string)value).Length == 0) {
return SR.GetString(SR.toStringNone);
}
else if (destinationType == typeof(string) && (value == null)) {
return SR.GetString(SR.toStringNone);
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <include file='doc\ImageKeyConverter.uex' path='docs/doc[@for="ImageKeyConverter.GetStandardValues"]/*' />
/// <devdoc>
/// Retrieves a collection containing a set of standard values
/// for the data type this validator is designed for. This
/// will return null if the data type does not support a
/// standard set of values.
/// </devdoc>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
if (context != null && context.Instance != null) {
object instance = context.Instance;
PropertyDescriptor imageListProp = ImageListUtils.GetImageListProperty(context.PropertyDescriptor, ref instance);
while (instance != null && imageListProp == null) {
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(instance);
foreach (PropertyDescriptor prop in props) {
if (typeof(ImageList).IsAssignableFrom(prop.PropertyType)) {
imageListProp = prop;
break;
}
}
if (imageListProp == null) {
// We didn't find the image list in this component. See if the
// component has a "parent" property. If so, walk the tree...
//
PropertyDescriptor parentProp = props[ParentImageListProperty];
if (parentProp != null) {
instance = parentProp.GetValue(instance);
}
else {
// Stick a fork in us, we're done.
//
instance = null;
}
}
}
if (imageListProp != null) {
ImageList imageList = (ImageList)imageListProp.GetValue(instance);
if (imageList != null) {
// Create array to contain standard values
//
object[] values;
int nImages = imageList.Images.Count;
if (IncludeNoneAsStandardValue) {
values = new object[nImages + 1];
values[nImages] = "";
}
else {
values = new object[nImages];
}
// Fill in the array
//
StringCollection imageKeys = imageList.Images.Keys;
for (int i = 0; i < imageKeys.Count; i++) {
if ((imageKeys[i] != null) && (imageKeys[i].Length != 0))
values[i] = imageKeys[i];
}
return new StandardValuesCollection(values);
}
}
}
if (IncludeNoneAsStandardValue) {
return new StandardValuesCollection(new object[] {""});
}
else {
return new StandardValuesCollection(new object[0]);
}
}
/// <include file='doc\ImageKeyConverter.uex' path='docs/doc[@for="ImageKeyConverter.GetStandardValuesExclusive"]/*' />
/// <devdoc>
/// Determines if the list of standard values returned from
/// GetStandardValues is an exclusive list. If the list
/// is exclusive, then no other values are valid, such as
/// in an enum data type. If the list is not exclusive,
/// then there are other valid values besides the list of
/// standard values GetStandardValues provides.
/// </devdoc>
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
return true;
}
/// <include file='doc\ImageKeyConverter.uex' path='docs/doc[@for="ImageKeyConverter.GetStandardValuesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports a standard set of values
/// that can be picked from a list.
/// </devdoc>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Principal;
namespace System.Security.Claims
{
/// <summary>
/// An Identity that is represented by a set of claims.
/// </summary>
public class ClaimsIdentity : IIdentity
{
private enum SerializationMask
{
None = 0,
AuthenticationType = 1,
BootstrapConext = 2,
NameClaimType = 4,
RoleClaimType = 8,
HasClaims = 16,
HasLabel = 32,
Actor = 64,
UserData = 128,
}
private byte[] _userSerializationData;
private ClaimsIdentity _actor;
private string _authenticationType;
private object _bootstrapContext;
private List<List<Claim>> _externalClaims;
private string _label;
private readonly List<Claim> _instanceClaims = new List<Claim>();
private string _nameClaimType = DefaultNameClaimType;
private string _roleClaimType = DefaultRoleClaimType;
public const string DefaultIssuer = @"LOCAL AUTHORITY";
public const string DefaultNameClaimType = ClaimTypes.Name;
public const string DefaultRoleClaimType = ClaimTypes.Role;
// NOTE about _externalClaims.
// GenericPrincpal and RolePrincipal set role claims here so that .IsInRole will be consistent with a 'role' claim found by querying the identity or principal.
// _externalClaims are external to the identity and assumed to be dynamic, they not serialized or copied through Clone().
// Access through public method: ClaimProviders.
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
public ClaimsIdentity()
: this((IIdentity)null, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IIdentity identity)
: this(identity, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <remarks>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
/// </remarks>
public ClaimsIdentity(IEnumerable<Claim> claims)
: this((IIdentity)null, claims, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
public ClaimsIdentity(string authenticationType)
: this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType)
: this((IIdentity)null, claims, authenticationType, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims)
: this(identity, claims, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(string authenticationType, string nameType, string roleType)
: this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, nameType, roleType)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
: this((IIdentity)null, claims, authenticationType, nameType, roleType)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks>If 'identity' is a <see cref="ClaimsIdentity"/>, then there are potentially multiple sources for AuthenticationType, NameClaimType, RoleClaimType.
/// <para>Priority is given to the parameters: authenticationType, nameClaimType, roleClaimType.</para>
/// <para>All <see cref="Claim"/>s are copied into this instance in a <see cref="List{Claim}"/>. Each Claim is examined and if Claim.Subject != this, then Claim.Clone(this) is called before the claim is added.</para>
/// <para>Any 'External' claims are ignored.</para>
/// </remarks>
/// <exception cref="InvalidOperationException">if 'identity' is a <see cref="ClaimsIdentity"/> and <see cref="ClaimsIdentity.Actor"/> results in a circular reference back to 'this'.</exception>
public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
{
ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
_authenticationType = (identity != null && string.IsNullOrEmpty(authenticationType)) ? identity.AuthenticationType : authenticationType;
_nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity != null ? claimsIdentity._nameClaimType : DefaultNameClaimType);
_roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity != null ? claimsIdentity._roleClaimType : DefaultRoleClaimType);
if (claimsIdentity != null)
{
_label = claimsIdentity._label;
_bootstrapContext = claimsIdentity._bootstrapContext;
if (claimsIdentity.Actor != null)
{
//
// Check if the Actor is circular before copying. That check is done while setting
// the Actor property and so not really needed here. But checking just for sanity sake
//
if (!IsCircular(claimsIdentity.Actor))
{
_actor = claimsIdentity.Actor;
}
else
{
throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular);
}
}
SafeAddClaims(claimsIdentity._instanceClaims);
}
else
{
if (identity != null && !string.IsNullOrEmpty(identity.Name))
{
SafeAddClaim(new Claim(_nameClaimType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this));
}
}
if (claims != null)
{
SafeAddClaims(claims);
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> using a <see cref="BinaryReader"/>.
/// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public ClaimsIdentity(BinaryReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
Initialize(reader);
}
/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="other"><see cref="ClaimsIdentity"/> to copy.</param>
/// <exception cref="ArgumentNullException">if 'other' is null.</exception>
protected ClaimsIdentity(ClaimsIdentity other)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
if (other._actor != null)
{
_actor = other._actor.Clone();
}
_authenticationType = other._authenticationType;
_bootstrapContext = other._bootstrapContext;
_label = other._label;
_nameClaimType = other._nameClaimType;
_roleClaimType = other._roleClaimType;
if (other._userSerializationData != null)
{
_userSerializationData = other._userSerializationData.Clone() as byte[];
}
SafeAddClaims(other._instanceClaims);
}
protected ClaimsIdentity(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> from a serialized stream created via
/// <see cref="ISerializable"/>.
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> to read from.
/// </param>
/// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception>
protected ClaimsIdentity(SerializationInfo info)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// Gets the authentication type that can be used to determine how this <see cref="ClaimsIdentity"/> authenticated to an authority.
/// </summary>
public virtual string AuthenticationType
{
get { return _authenticationType; }
}
/// <summary>
/// Gets a value that indicates if the user has been authenticated.
/// </summary>
public virtual bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(_authenticationType); }
}
/// <summary>
/// Gets or sets a <see cref="ClaimsIdentity"/> that was granted delegation rights.
/// </summary>
/// <exception cref="InvalidOperationException">if 'value' results in a circular reference back to 'this'.</exception>
public ClaimsIdentity Actor
{
get { return _actor; }
set
{
if (value != null)
{
if (IsCircular(value))
{
throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular);
}
}
_actor = value;
}
}
/// <summary>
/// Gets or sets a context that was used to create this <see cref="ClaimsIdentity"/>.
/// </summary>
public object BootstrapContext
{
get { return _bootstrapContext; }
set { _bootstrapContext = value; }
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsIdentity"/>.
/// </summary>
/// <remarks>May contain nulls.</remarks>
public virtual IEnumerable<Claim> Claims
{
get
{
if (_externalClaims == null)
{
return _instanceClaims;
}
return CombinedClaimsIterator();
}
}
private IEnumerable<Claim> CombinedClaimsIterator()
{
for (int i = 0; i < _instanceClaims.Count; i++)
{
yield return _instanceClaims[i];
}
for (int j = 0; j < _externalClaims.Count; j++)
{
if (_externalClaims[j] != null)
{
foreach (Claim claim in _externalClaims[j])
{
yield return claim;
}
}
}
}
/// <summary>
/// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.
/// </summary>
protected virtual byte[] CustomSerializationData
{
get
{
return _userSerializationData;
}
}
/// <summary>
/// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>.
/// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>.
/// </summary>
internal List<List<Claim>> ExternalClaims
{
get
{
if (_externalClaims == null)
{
_externalClaims = new List<List<Claim>>();
}
return _externalClaims;
}
}
/// <summary>
/// Gets or sets the label for this <see cref="ClaimsIdentity"/>
/// </summary>
public string Label
{
get { return _label; }
set { _label = value; }
}
/// <summary>
/// Gets the Name of this <see cref="ClaimsIdentity"/>.
/// </summary>
/// <remarks>Calls <see cref="FindFirst(string)"/> where string == NameClaimType, if found, returns <see cref="Claim.Value"/> otherwise null.</remarks>
public virtual string Name
{
// just an accessor for getting the name claim
get
{
Claim claim = FindFirst(_nameClaimType);
if (claim != null)
{
return claim.Value;
}
return null;
}
}
/// <summary>
/// Gets the value that identifies 'Name' claims. This is used when returning the property <see cref="ClaimsIdentity.Name"/>.
/// </summary>
public string NameClaimType
{
get { return _nameClaimType; }
}
/// <summary>
/// Gets the value that identifies 'Role' claims. This is used when calling <see cref="ClaimsPrincipal.IsInRole"/>.
/// </summary>
public string RoleClaimType
{
get { return _roleClaimType; }
}
/// <summary>
/// Creates a new instance of <see cref="ClaimsIdentity"/> with values copied from this object.
/// </summary>
public virtual ClaimsIdentity Clone()
{
return new ClaimsIdentity(this);
}
/// <summary>
/// Adds a single <see cref="Claim"/> to an internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/>add.</param>
/// <remarks>If <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks>
/// <exception cref="ArgumentNullException">if 'claim' is null.</exception>
public virtual void AddClaim(Claim claim)
{
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
/// <summary>
/// Adds a <see cref="IEnumerable{Claim}"/> to the internal list.
/// </summary>
/// <param name="claims">Enumeration of claims to add.</param>
/// <remarks>Each claim is examined and if <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks>
/// <exception cref="ArgumentNullException">if 'claims' is null.</exception>
public virtual void AddClaims(IEnumerable<Claim> claims)
{
if (claims == null)
{
throw new ArgumentNullException(nameof(claims));
}
foreach (Claim claim in claims)
{
if (claim == null)
{
continue;
}
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
}
/// <summary>
/// Attempts to remove a <see cref="Claim"/> the internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/> to match.</param>
/// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference.
/// <para>object.ReferenceEquals is used to 'match'.</para>
/// </remarks>
public virtual bool TryRemoveClaim(Claim claim)
{
if (claim == null)
{
return false;
}
bool removed = false;
for (int i = 0; i < _instanceClaims.Count; i++)
{
if (object.ReferenceEquals(_instanceClaims[i], claim))
{
_instanceClaims.RemoveAt(i);
removed = true;
break;
}
}
return removed;
}
/// <summary>
/// Removes a <see cref="Claim"/> from the internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/> to match.</param>
/// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference.
/// <para>object.ReferenceEquals is used to 'match'.</para>
/// </remarks>
/// <exception cref="InvalidOperationException">if 'claim' cannot be removed.</exception>
public virtual void RemoveClaim(Claim claim)
{
if (!TryRemoveClaim(claim))
{
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim));
}
}
/// <summary>
/// Adds claims to internal list. Calling Claim.Clone if Claim.Subject != this.
/// </summary>
/// <param name="claims">a <see cref="IEnumerable{Claim}"/> to add to </param>
/// <remarks>private only call from constructor, adds to internal list.</remarks>
private void SafeAddClaims(IEnumerable<Claim> claims)
{
foreach (Claim claim in claims)
{
if (claim == null)
continue;
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
}
/// <summary>
/// Adds claim to internal list. Calling Claim.Clone if Claim.Subject != this.
/// </summary>
/// <remarks>private only call from constructor, adds to internal list.</remarks>
private void SafeAddClaim(Claim claim)
{
if (claim == null)
return;
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <paramref name="match"/>.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
foreach (Claim claim in Claims)
{
if (match(claim))
{
yield return claim;
}
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual IEnumerable<Claim> FindAll(string type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> that is matched by <paramref name="match"/>.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual Claim FindFirst(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
foreach (Claim claim in Claims)
{
if (match(claim))
{
return claim;
}
}
return null;
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual Claim FindFirst(string type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase))
{
return claim;
}
}
}
return null;
}
/// <summary>
/// Determines if a claim is contained within this ClaimsIdentity.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>true if a claim is found, false otherwise.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual bool HasClaim(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
foreach (Claim claim in Claims)
{
if (match(claim))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if a claim with type AND value is contained within this ClaimsIdentity.
/// </summary>
/// <param name="type">the type of the claim to match.</param>
/// <param name="value">the value of the claim to match.</param>
/// <returns>true if a claim is matched, false otherwise.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase for Claim.Type, StringComparison.Ordinal for Claim.Value.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public virtual bool HasClaim(string type, string value)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
foreach (Claim claim in Claims)
{
if (claim != null
&& string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)
&& string.Equals(claim.Value, value, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
/// <summary>
/// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/>
/// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
private void Initialize(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
SerializationMask mask = (SerializationMask)reader.ReadInt32();
int numPropertiesRead = 0;
int numPropertiesToRead = reader.ReadInt32();
if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType)
{
_authenticationType = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext)
{
_bootstrapContext = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType)
{
_nameClaimType = reader.ReadString();
numPropertiesRead++;
}
else
{
_nameClaimType = ClaimsIdentity.DefaultNameClaimType;
}
if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType)
{
_roleClaimType = reader.ReadString();
numPropertiesRead++;
}
else
{
_roleClaimType = ClaimsIdentity.DefaultRoleClaimType;
}
if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel)
{
_label = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims)
{
int numberOfClaims = reader.ReadInt32();
for (int index = 0; index < numberOfClaims; index++)
{
_instanceClaims.Add(CreateClaim(reader));
}
numPropertiesRead++;
}
if ((mask & SerializationMask.Actor) == SerializationMask.Actor)
{
_actor = new ClaimsIdentity(reader);
numPropertiesRead++;
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
int cb = reader.ReadInt32();
_userSerializationData = reader.ReadBytes(cb);
numPropertiesRead++;
}
for (int i = numPropertiesRead; i < numPropertiesToRead; i++)
{
reader.ReadString();
}
}
/// <summary>
/// Provides an extensibility point for derived types to create a custom <see cref="Claim"/>.
/// </summary>
/// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param>
/// <returns>a new <see cref="Claim"/>.</returns>
protected virtual Claim CreateClaim(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
return new Claim(reader, this);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
public virtual void WriteTo(BinaryWriter writer)
{
WriteTo(writer, null);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <param name="userData">additional data provided by derived type.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
int numberOfPropertiesWritten = 0;
var mask = SerializationMask.None;
if (_authenticationType != null)
{
mask |= SerializationMask.AuthenticationType;
numberOfPropertiesWritten++;
}
if (_bootstrapContext != null)
{
string rawData = _bootstrapContext as string;
if (rawData != null)
{
mask |= SerializationMask.BootstrapConext;
numberOfPropertiesWritten++;
}
}
if (!string.Equals(_nameClaimType, ClaimsIdentity.DefaultNameClaimType, StringComparison.Ordinal))
{
mask |= SerializationMask.NameClaimType;
numberOfPropertiesWritten++;
}
if (!string.Equals(_roleClaimType, ClaimsIdentity.DefaultRoleClaimType, StringComparison.Ordinal))
{
mask |= SerializationMask.RoleClaimType;
numberOfPropertiesWritten++;
}
if (!string.IsNullOrWhiteSpace(_label))
{
mask |= SerializationMask.HasLabel;
numberOfPropertiesWritten++;
}
if (_instanceClaims.Count > 0)
{
mask |= SerializationMask.HasClaims;
numberOfPropertiesWritten++;
}
if (_actor != null)
{
mask |= SerializationMask.Actor;
numberOfPropertiesWritten++;
}
if (userData != null && userData.Length > 0)
{
numberOfPropertiesWritten++;
mask |= SerializationMask.UserData;
}
writer.Write((int)mask);
writer.Write(numberOfPropertiesWritten);
if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType)
{
writer.Write(_authenticationType);
}
if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext)
{
writer.Write(_bootstrapContext as string);
}
if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType)
{
writer.Write(_nameClaimType);
}
if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType)
{
writer.Write(_roleClaimType);
}
if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel)
{
writer.Write(_label);
}
if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims)
{
writer.Write(_instanceClaims.Count);
foreach (var claim in _instanceClaims)
{
claim.WriteTo(writer);
}
}
if ((mask & SerializationMask.Actor) == SerializationMask.Actor)
{
_actor.WriteTo(writer);
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
writer.Write(userData.Length);
writer.Write(userData);
}
writer.Flush();
}
/// <summary>
/// Checks if a circular reference exists to 'this'
/// </summary>
/// <param name="subject"></param>
/// <returns></returns>
private bool IsCircular(ClaimsIdentity subject)
{
if (ReferenceEquals(this, subject))
{
return true;
}
ClaimsIdentity currSubject = subject;
while (currSubject.Actor != null)
{
if (ReferenceEquals(this, currSubject.Actor))
{
return true;
}
currSubject = currSubject.Actor;
}
return false;
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the serialization data for the ClaimsIdentity
/// </summary>
/// <param name="info">The serialization information stream to write to. Satisfies ISerializable contract.</param>
/// <param name="context">Context for serialization. Can be null.</param>
/// <exception cref="ArgumentNullException">Thrown if the info parameter is null.</exception>
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Policy;
using System.Threading;
using Bedrock.Modularity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Bedrock.Tests.Modularity
{
[TestClass]
public class DirectoryModuleCatalogFixture
{
private const string ModulesDirectory1 = @".\DynamicModules\MocksModules1";
private const string ModulesDirectory2 = @".\DynamicModules\AttributedModules";
private const string ModulesDirectory3 = @".\DynamicModules\DependantModules";
private const string ModulesDirectory4 = @".\DynamicModules\MocksModules2";
private const string ModulesDirectory5 = @".\DynamicModules\ModulesMainDomain\";
private const string InvalidModulesDirectory = @".\Modularity";
public DirectoryModuleCatalogFixture()
{
}
[TestInitialize]
[TestCleanup]
public void CleanUpDirectories()
{
CompilerHelper.CleanUpDirectory(ModulesDirectory1);
CompilerHelper.CleanUpDirectory(ModulesDirectory2);
CompilerHelper.CleanUpDirectory(ModulesDirectory3);
CompilerHelper.CleanUpDirectory(ModulesDirectory4);
CompilerHelper.CleanUpDirectory(ModulesDirectory5);
CompilerHelper.CleanUpDirectory(InvalidModulesDirectory);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void NullPathThrows()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.Load();
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void EmptyPathThrows()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.Load();
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void NonExistentPathThrows()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = "NonExistentPath";
catalog.Load();
}
[TestMethod]
public void ShouldReturnAListOfModuleInfo()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual(1, modules.Length);
Assert.IsNotNull(modules[0].Ref);
StringAssert.StartsWith(modules[0].Ref, "file://");
Assert.IsTrue(modules[0].Ref.Contains(@"MockModuleA.dll"));
Assert.IsNotNull(modules[0].ModuleType);
StringAssert.Contains(modules[0].ModuleType, "Bedrock.Tests.Mocks.Modules.MockModuleA");
}
[TestMethod]
[DeploymentItem(@"Modularity\NotAValidDotNetDll.txt.dll", @".\Modularity")]
public void ShouldNotThrowWithNonValidDotNetAssembly()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = InvalidModulesDirectory;
try
{
catalog.Load();
}
catch (Exception)
{
Assert.Fail("Should not have thrown.");
}
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual(0, modules.Length);
}
[TestMethod]
[DeploymentItem(@"Modularity\NotAValidDotNetDll.txt.dll", InvalidModulesDirectory)]
public void LoadsValidAssembliesWhenInvalidDllsArePresent()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleA.cs",
InvalidModulesDirectory + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = InvalidModulesDirectory;
try
{
catalog.Load();
}
catch (Exception)
{
Assert.Fail("Should not have thrown.");
}
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual(1, modules.Length);
Assert.IsNotNull(modules[0].Ref);
StringAssert.StartsWith(modules[0].Ref, "file://");
Assert.IsTrue(modules[0].Ref.Contains(@"MockModuleA.dll"));
Assert.IsNotNull(modules[0].ModuleType);
StringAssert.Contains(modules[0].ModuleType, "Bedrock.Tests.Mocks.Modules.MockModuleA");
}
[TestMethod]
public void ShouldNotThrowWithLoadFromByteAssemblies()
{
CompilerHelper.CleanUpDirectory(@".\CompileOutput\");
CompilerHelper.CleanUpDirectory(@".\IgnoreLoadFromByteAssembliesTestDir\");
var results = CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleA.cs",
@".\CompileOutput\MockModuleA.dll");
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockAttributedModule.cs",
@".\IgnoreLoadFromByteAssembliesTestDir\MockAttributedModule.dll");
string path = @".\IgnoreLoadFromByteAssembliesTestDir";
AppDomain testDomain = null;
try
{
testDomain = CreateAppDomain();
RemoteDirectoryLookupCatalog remoteEnum = CreateRemoteDirectoryModuleCatalogInAppDomain(testDomain);
remoteEnum.LoadDynamicEmittedModule();
remoteEnum.LoadAssembliesByByte(@".\CompileOutput\MockModuleA.dll");
ModuleInfo[] infos = remoteEnum.DoEnumeration(path);
Assert.IsNotNull(
infos.FirstOrDefault(x => x.ModuleType.IndexOf("Bedrock.Tests.Mocks.Modules.MockAttributedModule") >= 0)
);
}
finally
{
if (testDomain != null)
AppDomain.Unload(testDomain);
}
}
[TestMethod]
public void ShouldGetModuleNameFromAttribute()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockAttributedModule.cs",
ModulesDirectory2 + @"\MockAttributedModule.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory2;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
Assert.AreEqual("TestModule", modules[0].ModuleName);
}
[TestMethod]
public void ShouldGetDependantModulesFromAttribute()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockDependencyModule.cs",
ModulesDirectory3 + @"\DependencyModule.dll");
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockDependantModule.cs",
ModulesDirectory3 + @"\DependantModule.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory3;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(2, modules.Length);
var dependantModule = modules.First(module => module.ModuleName == "DependantModule");
var dependencyModule = modules.First(module => module.ModuleName == "DependencyModule");
Assert.IsNotNull(dependantModule);
Assert.IsNotNull(dependencyModule);
Assert.IsNotNull(dependantModule.DependsOn);
Assert.AreEqual(1, dependantModule.DependsOn.Count);
Assert.AreEqual(dependencyModule.ModuleName, dependantModule.DependsOn[0]);
}
[TestMethod]
public void UseClassNameAsModuleNameWhenNotSpecifiedInAttribute()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual("MockModuleA", modules[0].ModuleName);
}
[TestMethod]
public void ShouldDefaultInitializationModeToWhenAvailable()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.IsNotNull(modules);
Assert.AreEqual(InitializationMode.WhenAvailable, modules[0].InitializationMode);
}
[TestMethod]
public void ShouldGetOnDemandFromAttribute()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockAttributedModule.cs",
ModulesDirectory3 + @"\MockAttributedModule.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory3;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
Assert.AreEqual(InitializationMode.OnDemand, modules[0].InitializationMode);
}
[TestMethod]
public void ShouldHonorStartupLoadedAttribute()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockStartupLoadedAttributedModule.cs",
ModulesDirectory3 + @"\MockStartupLoadedAttributedModule.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory3;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
Assert.AreEqual(InitializationMode.OnDemand, modules[0].InitializationMode);
}
[TestMethod]
public void ShouldNotLoadAssembliesInCurrentAppDomain()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory4 + @"\MockModuleA.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory4;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
// filtering out dynamic assemblies due to using a dynamic mocking framework.
Assembly loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.IsDynamic)
.Where(assembly => assembly.Location.Equals(modules[0].Ref, StringComparison.InvariantCultureIgnoreCase))
.FirstOrDefault();
Assert.IsNull(loadedAssembly);
}
[TestMethod]
public void ShouldNotGetModuleInfoForAnAssemblyAlreadyLoadedInTheMainDomain()
{
var assemblyPath = Assembly.GetCallingAssembly().Location;
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory5;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(0, modules.Length);
}
[TestMethod]
public void ShouldLoadAssemblyEvenIfTheyAreReferencingEachOther()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory4 + @"\MockModuleZZZ.dll");
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleReferencingOtherModule.cs",
ModulesDirectory4 + @"\MockModuleReferencingOtherModule.dll", ModulesDirectory4 + @"\MockModuleZZZ.dll");
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory4;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(2, modules.Count());
}
//Disabled Warning
// 'System.Security.Policy.Evidence.Count' is obsolete: '
// "Evidence should not be treated as an ICollection. Please use GetHostEnumerator and GetAssemblyEnumerator to
// iterate over the evidence to collect a count."'
#pragma warning disable 0618
[TestMethod]
public void CreateChildAppDomainHasParentEvidenceAndSetup()
{
TestableDirectoryModuleCatalog catalog = new TestableDirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory4;
catalog.Load();
Evidence parentEvidence = new Evidence();
AppDomainSetup parentSetup = new AppDomainSetup();
parentSetup.ApplicationName = "Test Parent";
AppDomain parentAppDomain = AppDomain.CreateDomain("Parent", parentEvidence, parentSetup);
AppDomain childDomain = catalog.BuildChildDomain(parentAppDomain);
Assert.AreEqual(parentEvidence.Count, childDomain.Evidence.Count);
Assert.AreEqual("Test Parent", childDomain.SetupInformation.ApplicationName);
Assert.AreNotEqual(AppDomain.CurrentDomain.Evidence.Count, childDomain.Evidence.Count);
Assert.AreNotEqual(AppDomain.CurrentDomain.SetupInformation.ApplicationName, childDomain.SetupInformation.ApplicationName);
}
#pragma warning restore 0618
[TestMethod]
public void ShouldLoadFilesEvenIfDynamicAssemblyExists()
{
CompilerHelper.CleanUpDirectory(@".\CompileOutput\");
CompilerHelper.CleanUpDirectory(@".\IgnoreDynamicGeneratedFilesTestDir\");
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockAttributedModule.cs",
@".\IgnoreDynamicGeneratedFilesTestDir\MockAttributedModule.dll");
string path = @".\IgnoreDynamicGeneratedFilesTestDir";
AppDomain testDomain = null;
try
{
testDomain = CreateAppDomain();
RemoteDirectoryLookupCatalog remoteEnum = CreateRemoteDirectoryModuleCatalogInAppDomain(testDomain);
remoteEnum.LoadDynamicEmittedModule();
ModuleInfo[] infos = remoteEnum.DoEnumeration(path);
Assert.IsNotNull(
infos.FirstOrDefault(x => x.ModuleType.IndexOf("Bedrock.Tests.Mocks.Modules.MockAttributedModule") >= 0)
);
}
finally
{
if (testDomain != null)
AppDomain.Unload(testDomain);
}
}
[TestMethod]
public void ShouldNotFailWhenAlreadyLoadedAssembliesAreAlsoFoundOnTargetDirectory()
{
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
string filename = typeof(DirectoryModuleCatalog).Assembly.Location;
string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename));
File.Copy(filename, destinationFileName);
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
}
[TestMethod]
public void ShouldIgnoreAbstractClassesThatImplementIModule()
{
CompilerHelper.CleanUpDirectory(ModulesDirectory1);
CompilerHelper.CompileFile(@"Bedrock.Tests.Mocks.Modules.MockAbstractModule.cs",
ModulesDirectory1 + @"\MockAbstractModule.dll");
string filename = typeof(DirectoryModuleCatalog).Assembly.Location;
string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename));
File.Copy(filename, destinationFileName);
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = ModulesDirectory1;
catalog.Load();
ModuleInfo[] modules = catalog.Modules.ToArray();
Assert.AreEqual(1, modules.Length);
Assert.AreEqual("MockInheritingModule", modules[0].ModuleName);
CompilerHelper.CleanUpDirectory(ModulesDirectory1);
}
private AppDomain CreateAppDomain()
{
Evidence evidence = AppDomain.CurrentDomain.Evidence;
AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
return AppDomain.CreateDomain("TestDomain", evidence, setup);
}
private RemoteDirectoryLookupCatalog CreateRemoteDirectoryModuleCatalogInAppDomain(AppDomain testDomain)
{
RemoteDirectoryLookupCatalog remoteEnum;
Type remoteEnumType = typeof(RemoteDirectoryLookupCatalog);
remoteEnum = (RemoteDirectoryLookupCatalog)testDomain.CreateInstanceFrom(
remoteEnumType.Assembly.Location, remoteEnumType.FullName).Unwrap();
return remoteEnum;
}
private class TestableDirectoryModuleCatalog : DirectoryModuleCatalog
{
public new AppDomain BuildChildDomain(AppDomain currentDomain)
{
return base.BuildChildDomain(currentDomain);
}
}
private class RemoteDirectoryLookupCatalog : MarshalByRefObject
{
public void LoadAssembliesByByte(string assemblyPath)
{
byte[] assemblyBytes = File.ReadAllBytes(assemblyPath);
AppDomain.CurrentDomain.Load(assemblyBytes);
}
public ModuleInfo[] DoEnumeration(string path)
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = path;
catalog.Load();
return catalog.Modules.ToArray();
}
public void LoadDynamicEmittedModule()
{
// create a dynamic assembly and module
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "DynamicBuiltAssembly";
AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder module = assemblyBuilder.DefineDynamicModule("DynamicBuiltAssembly.dll");
// create a new type
TypeBuilder typeBuilder = module.DefineType("DynamicBuiltType", TypeAttributes.Public | TypeAttributes.Class);
// Create the type
Type helloWorldType = typeBuilder.CreateType();
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExitActions.cs" company="Appccelerate">
// Copyright (c) 2008-2015
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Appccelerate.StateMachine
{
using System;
using System.Collections.Generic;
using FluentAssertions;
using Xbehave;
public class ExitActions
{
private const int State = 1;
private const int AnotherState = 2;
private const int Event = 2;
[Scenario]
public void ExitAction(
PassiveStateMachine<int, int> machine,
bool exitActionExecuted)
{
"establish a state machine with exit action on a state"._(() =>
{
machine = new PassiveStateMachine<int, int>();
machine.In(State)
.ExecuteOnExit(() => exitActionExecuted = true)
.On(Event).Goto(AnotherState);
});
"when leaving the state"._(() =>
{
machine.Initialize(State);
machine.Start();
machine.Fire(Event);
});
"it should execute the exit action"._(() =>
exitActionExecuted.Should().BeTrue());
}
[Scenario]
public void ExitActionWithParameter(
PassiveStateMachine<int, int> machine,
string parameter)
{
const string Parameter = "parameter";
"establish a state machine with exit action with parameter on a state"._(() =>
{
machine = new PassiveStateMachine<int, int>();
machine.In(State)
.ExecuteOnExitParametrized(p => parameter = p, Parameter)
.On(Event).Goto(AnotherState);
});
"when leaving the state"._(() =>
{
machine.Initialize(State);
machine.Start();
machine.Fire(Event);
});
"it should execute the exit action"._(() =>
parameter.Should().NotBeNull());
"it should pass parameter to the exit action"._(() =>
parameter.Should().Be(Parameter));
}
[Scenario]
public void MultipleExitActions(
PassiveStateMachine<int, int> machine,
bool exitAction1Executed,
bool exitAction2Executed)
{
"establish a state machine with several exit actions on a state"._(() =>
{
machine = new PassiveStateMachine<int, int>();
machine.In(State)
.ExecuteOnExit(() => exitAction1Executed = true)
.ExecuteOnExit(() => exitAction2Executed = true)
.On(Event).Goto(AnotherState);
});
"when leaving the state"._(() =>
{
machine.Initialize(State);
machine.Start();
machine.Fire(Event);
});
"It should execute all exit actions"._(() =>
{
exitAction1Executed
.Should().BeTrue("first action should be executed");
exitAction2Executed
.Should().BeTrue("second action should be executed");
});
}
[Scenario]
public void ExceptionHandling(
PassiveStateMachine<int, int> machine,
bool exitAction1Executed,
bool exitAction2Executed,
bool exitAction3Executed)
{
var exception2 = new Exception();
var exception3 = new Exception();
var receivedException = new List<Exception>();
"establish a state machine with several exit actions on a state and some of them throw an exception"._(() =>
{
machine = new PassiveStateMachine<int, int>();
machine.In(State)
.ExecuteOnExit(() => exitAction1Executed = true)
.ExecuteOnExit(() =>
{
exitAction2Executed = true;
throw exception2;
})
.ExecuteOnExit(() =>
{
exitAction3Executed = true;
throw exception3;
})
.On(Event).Goto(AnotherState);
machine.TransitionExceptionThrown += (s, e) => receivedException.Add(e.Exception);
});
"when entering the state"._(() =>
{
machine.Initialize(State);
machine.Start();
machine.Fire(Event);
});
"it should execute all entry actions on entry"._(() =>
{
exitAction1Executed
.Should().BeTrue("action 1 should be executed");
exitAction2Executed
.Should().BeTrue("action 2 should be executed");
exitAction3Executed
.Should().BeTrue("action 3 should be executed");
});
"it should handle all exceptions of all throwing entry actions by firing the TransitionExceptionThrown event"._(() =>
receivedException
.Should().BeEquivalentTo(new object[]
{
exception2, exception3
}));
}
[Scenario]
public void EventArgument(
PassiveStateMachine<int, int> machine,
int passedArgument)
{
const int Argument = 17;
"establish a state machine with an exit action taking an event argument"._(() =>
{
machine = new PassiveStateMachine<int, int>();
machine.In(State)
.ExecuteOnExit((int argument) => passedArgument = argument)
.On(Event).Goto(AnotherState);
machine.In(AnotherState)
.ExecuteOnEntry((int argument) => passedArgument = argument);
});
"when leaving the state"._(() =>
{
machine.Initialize(State);
machine.Start();
machine.Fire(Event, Argument);
});
"it should pass event argument to exit action"._(() =>
passedArgument.Should().Be(Argument));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class DataMaskingOperationsExtensions
{
/// <summary>
/// Creates or updates an Azure SQL Database data masking policy
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// firewall rule.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateOrUpdatePolicy(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, DataMaskingPolicyCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataMaskingOperations)s).CreateOrUpdatePolicyAsync(resourceGroupName, serverName, databaseName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an Azure SQL Database data masking policy
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// firewall rule.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateOrUpdatePolicyAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, DataMaskingPolicyCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdatePolicyAsync(resourceGroupName, serverName, databaseName, parameters, CancellationToken.None);
}
/// <summary>
/// Creates or updates an Azure SQL Database Server Firewall rule.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='dataMaskingRule'>
/// Required. The name of the Azure SQL Database data masking rule.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a data
/// masking rule.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateOrUpdateRule(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, DataMaskingRuleCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataMaskingOperations)s).CreateOrUpdateRuleAsync(resourceGroupName, serverName, databaseName, dataMaskingRule, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an Azure SQL Database Server Firewall rule.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='dataMaskingRule'>
/// Required. The name of the Azure SQL Database data masking rule.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a data
/// masking rule.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateOrUpdateRuleAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, DataMaskingRuleCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateRuleAsync(resourceGroupName, serverName, databaseName, dataMaskingRule, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes an Azure SQL Server data masking rule.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='dataMaskingRule'>
/// Required. The name of the Azure SQL Database data masking rule.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataMaskingOperations)s).DeleteAsync(resourceGroupName, serverName, databaseName, dataMaskingRule);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an Azure SQL Server data masking rule.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='dataMaskingRule'>
/// Required. The name of the Azure SQL Database data masking rule.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule)
{
return operations.DeleteAsync(resourceGroupName, serverName, databaseName, dataMaskingRule, CancellationToken.None);
}
/// <summary>
/// Returns an Azure SQL Database data masking policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking policy applies.
/// </param>
/// <returns>
/// Represents the response to a data masking policy get request.
/// </returns>
public static DataMaskingPolicyGetResponse GetPolicy(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataMaskingOperations)s).GetPolicyAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Azure SQL Database data masking policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking policy applies.
/// </param>
/// <returns>
/// Represents the response to a data masking policy get request.
/// </returns>
public static Task<DataMaskingPolicyGetResponse> GetPolicyAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.GetPolicyAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Returns a list of Azure SQL Database data masking rules.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rules applies.
/// </param>
/// <returns>
/// Represents the response to a List data masking rules request.
/// </returns>
public static DataMaskingRuleListResponse List(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataMaskingOperations)s).ListAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of Azure SQL Database data masking rules.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IDataMaskingOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rules applies.
/// </param>
/// <returns>
/// Represents the response to a List data masking rules request.
/// </returns>
public static Task<DataMaskingRuleListResponse> ListAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.ListAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Security.Auth.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 Javax.Security.Auth
{
/// <summary>
/// <para>Allows for special treatment of sensitive information, when it comes to destroying or clearing of the data. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/Destroyable
/// </java-name>
[Dot42.DexImport("javax/security/auth/Destroyable", AccessFlags = 1537)]
public partial interface IDestroyable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Erases the sensitive information. Once an object is destroyed any calls to its methods will throw an <c> IllegalStateException </c> . If it does not succeed a DestroyFailedException is thrown.</para><para></para>
/// </summary>
/// <java-name>
/// destroy
/// </java-name>
[Dot42.DexImport("destroy", "()V", AccessFlags = 1025)]
void Destroy() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <c> true </c> once an object has been safely destroyed.</para><para></para>
/// </summary>
/// <returns>
/// <para>whether the object has been safely destroyed. </para>
/// </returns>
/// <java-name>
/// isDestroyed
/// </java-name>
[Dot42.DexImport("isDestroyed", "()Z", AccessFlags = 1025)]
bool IsDestroyed() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Legacy security code; do not use. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/SubjectDomainCombiner
/// </java-name>
[Dot42.DexImport("javax/security/auth/SubjectDomainCombiner", AccessFlags = 33)]
public partial class SubjectDomainCombiner : global::Java.Security.IDomainCombiner
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljavax/security/auth/Subject;)V", AccessFlags = 1)]
public SubjectDomainCombiner(global::Javax.Security.Auth.Subject subject) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getSubject
/// </java-name>
[Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)]
public virtual global::Javax.Security.Auth.Subject GetSubject() /* MethodBuilder.Create */
{
return default(global::Javax.Security.Auth.Subject);
}
/// <summary>
/// <para>Returns a combination of the two provided <c> ProtectionDomain </c> arrays. Implementers can simply merge the two arrays into one, remove duplicates and perform other optimizations.</para><para></para>
/// </summary>
/// <returns>
/// <para>a single <c> ProtectionDomain </c> array computed from the two provided arrays. </para>
/// </returns>
/// <java-name>
/// combine
/// </java-name>
[Dot42.DexImport("combine", "([Ljava/security/ProtectionDomain;[Ljava/security/ProtectionDomain;)[Ljava/securi" +
"ty/ProtectionDomain;", AccessFlags = 1)]
public virtual global::Java.Security.ProtectionDomain[] Combine(global::Java.Security.ProtectionDomain[] current, global::Java.Security.ProtectionDomain[] assigned) /* MethodBuilder.Create */
{
return default(global::Java.Security.ProtectionDomain[]);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal SubjectDomainCombiner() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getSubject
/// </java-name>
public global::Javax.Security.Auth.Subject Subject
{
[Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)]
get{ return GetSubject(); }
}
}
/// <summary>
/// <para>Signals that the Destroyable#destroy() method failed. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/DestroyFailedException
/// </java-name>
[Dot42.DexImport("javax/security/auth/DestroyFailedException", AccessFlags = 33)]
public partial class DestroyFailedException : global::System.Exception
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates an exception of type <c> DestroyFailedException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public DestroyFailedException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates an exception of type <c> DestroyFailedException </c> .</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public DestroyFailedException(string message) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Legacy security code; do not use. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/AuthPermission
/// </java-name>
[Dot42.DexImport("javax/security/auth/AuthPermission", AccessFlags = 49)]
public sealed partial class AuthPermission : global::Java.Security.BasicPermission
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public AuthPermission(string name) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public AuthPermission(string name, string actions) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal AuthPermission() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Legacy security code; do not use. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/PrivateCredentialPermission
/// </java-name>
[Dot42.DexImport("javax/security/auth/PrivateCredentialPermission", AccessFlags = 49)]
public sealed partial class PrivateCredentialPermission : global::Java.Security.Permission
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public PrivateCredentialPermission(string name, string action) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getPrincipals
/// </java-name>
[Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)]
public string[][] GetPrincipals() /* MethodBuilder.Create */
{
return default(string[][]);
}
/// <java-name>
/// getActions
/// </java-name>
[Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetActions() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getCredentialClass
/// </java-name>
[Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetCredentialClass() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object @object) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// implies
/// </java-name>
[Dot42.DexImport("implies", "(Ljava/security/Permission;)Z", AccessFlags = 1)]
public override bool Implies(global::Java.Security.Permission permission) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// newPermissionCollection
/// </java-name>
[Dot42.DexImport("newPermissionCollection", "()Ljava/security/PermissionCollection;", AccessFlags = 1)]
public override global::Java.Security.PermissionCollection NewPermissionCollection() /* MethodBuilder.Create */
{
return default(global::Java.Security.PermissionCollection);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PrivateCredentialPermission() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getPrincipals
/// </java-name>
public string[][] Principals
{
[Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPrincipals(); }
}
/// <java-name>
/// getActions
/// </java-name>
public string Actions
{
[Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetActions(); }
}
/// <java-name>
/// getCredentialClass
/// </java-name>
public string CredentialClass
{
[Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetCredentialClass(); }
}
}
/// <summary>
/// <para>The central class of the <c> javax.security.auth </c> package representing an authenticated user or entity (both referred to as "subject"). IT defines also the static methods that allow code to be run, and do modifications according to the subject's permissions. </para><para>A subject has the following features: <ul><li><para>A set of <c> Principal </c> objects specifying the identities bound to a <c> Subject </c> that distinguish it. </para></li><li><para>Credentials (public and private) such as certificates, keys, or authentication proofs such as tickets </para></li></ul></para>
/// </summary>
/// <java-name>
/// javax/security/auth/Subject
/// </java-name>
[Dot42.DexImport("javax/security/auth/Subject", AccessFlags = 49)]
public sealed partial class Subject : global::Java.Io.ISerializable
/* scope: __dot42__ */
{
/// <summary>
/// <para>The default constructor initializing the sets of public and private credentials and principals with the empty set. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Subject() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>The constructor for the subject, setting its public and private credentials and principals according to the arguments.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(ZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;)V", AccessFlags = 1, Signature = "(ZLjava/util/Set<+Ljava/security/Principal;>;Ljava/util/Set<*>;Ljava/util/Set<*>;" +
")V")]
public Subject(bool readOnly, global::Java.Util.ISet<global::Java.Security.IPrincipal> subjPrincipals, global::Java.Util.ISet<object> pubCredentials, global::Java.Util.ISet<object> privCredentials) /* MethodBuilder.Create */
{
}
/// <java-name>
/// doAs
/// </java-name>
[Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;)Ljava/lang/Object;" +
"", AccessFlags = 9)]
public static object DoAs(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<object> privilegedAction) /* MethodBuilder.Create */
{
return default(object);
}
/// <java-name>
/// doAsPrivileged
/// </java-name>
[Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;Ljava/security/Acce" +
"ssControlContext;)Ljava/lang/Object;", AccessFlags = 9)]
public static object DoAsPrivileged(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<object> privilegedAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */
{
return default(object);
}
/// <java-name>
/// doAs
/// </java-name>
[Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;)Ljava/lan" +
"g/Object;", AccessFlags = 9)]
public static object DoAs(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<object> privilegedExceptionAction) /* MethodBuilder.Create */
{
return default(object);
}
/// <java-name>
/// doAsPrivileged
/// </java-name>
[Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;Ljava/secu" +
"rity/AccessControlContext;)Ljava/lang/Object;", AccessFlags = 9)]
public static object DoAsPrivileged(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<object> privilegedExceptionAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Checks two Subjects for equality. More specifically if the principals, public and private credentials are equal, equality for two <c> Subjects </c> is implied.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if the specified <c> Subject </c> is equal to this one. </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's Principal.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's Principal. </para>
/// </returns>
/// <java-name>
/// getPrincipals
/// </java-name>
[Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")]
public global::Java.Util.ISet<global::Java.Security.IPrincipal> GetPrincipals() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<global::Java.Security.IPrincipal>);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's Principal which is a subclass of the <c> Class </c> provided.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's Principal. Modifications to the returned set of <c> Principal </c> s do not affect this <c> Subject </c> 's set. </para>
/// </returns>
/// <java-name>
/// getPrincipals
/// </java-name>
[Dot42.DexImport("getPrincipals", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T::Ljava/security/Principal;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
public global::Java.Util.ISet<T> GetPrincipals<T>(global::System.Type c) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<T>);
}
/// <summary>
/// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the private credentials associated with this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// getPrivateCredentials
/// </java-name>
[Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
public global::Java.Util.ISet<object> GetPrivateCredentials() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<object>);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's private credentials which are a subclass of the <c> Class </c> provided.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's private credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para>
/// </returns>
/// <java-name>
/// getPrivateCredentials
/// </java-name>
[Dot42.DexImport("getPrivateCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
public global::Java.Util.ISet<T> GetPrivateCredentials<T>(global::System.Type c) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<T>);
}
/// <summary>
/// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the public credentials associated with this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// getPublicCredentials
/// </java-name>
[Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
public global::Java.Util.ISet<object> GetPublicCredentials() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<object>);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's public credentials which are a subclass of the <c> Class </c> provided.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's public credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para>
/// </returns>
/// <java-name>
/// getPublicCredentials
/// </java-name>
[Dot42.DexImport("getPublicCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
public global::Java.Util.ISet<T> GetPublicCredentials<T>(global::System.Type c) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<T>);
}
/// <summary>
/// <para>Returns a hash code of this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>a hash code of this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Prevents from modifications being done to the credentials and Principal sets. After setting it to read-only this <c> Subject </c> can not be made writable again. The destroy method on the credentials still works though. </para>
/// </summary>
/// <java-name>
/// setReadOnly
/// </java-name>
[Dot42.DexImport("setReadOnly", "()V", AccessFlags = 1)]
public void SetReadOnly() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns whether this <c> Subject </c> is read-only or not.</para><para></para>
/// </summary>
/// <returns>
/// <para>whether this <c> Subject </c> is read-only or not. </para>
/// </returns>
/// <java-name>
/// isReadOnly
/// </java-name>
[Dot42.DexImport("isReadOnly", "()Z", AccessFlags = 1)]
public bool IsReadOnly() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns a <c> String </c> representation of this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>a <c> String </c> representation of this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the <c> Subject </c> that was last associated with the <c> context </c> provided as argument.</para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> Subject </c> that was last associated with the <c> context </c> provided as argument. </para>
/// </returns>
/// <java-name>
/// getSubject
/// </java-name>
[Dot42.DexImport("getSubject", "(Ljava/security/AccessControlContext;)Ljavax/security/auth/Subject;", AccessFlags = 9)]
public static global::Javax.Security.Auth.Subject GetSubject(global::Java.Security.AccessControlContext context) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Auth.Subject);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's Principal.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's Principal. </para>
/// </returns>
/// <java-name>
/// getPrincipals
/// </java-name>
public global::Java.Util.ISet<global::Java.Security.IPrincipal> Principals
{
[Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")]
get{ return GetPrincipals(); }
}
/// <summary>
/// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the private credentials associated with this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// getPrivateCredentials
/// </java-name>
public global::Java.Util.ISet<object> PrivateCredentials
{
[Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
get{ return GetPrivateCredentials(); }
}
/// <summary>
/// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the public credentials associated with this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// getPublicCredentials
/// </java-name>
public global::Java.Util.ISet<object> PublicCredentials
{
[Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
get{ return GetPublicCredentials(); }
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/* Manager class for handling sounds. Currently
* only implement simple functions.
* */
public class SoundManager : MonoBehaviour {
/* Static attributes */
//Resource path
private const string BGM_PATH = "Sounds/BGM/";
private const string SFX_PATH = "Sounds/SFX/";
private const int MAX_ACTIVE_SFX = 25;
private const int MAX_ACTIVE_SFX_PER_SOUND = 10;
//Singleton
private static SoundManager m_Instance = null;
/* Attributes */
//Mute
private static bool m_GlobalMuteBGM = false;
public static bool GlobalMuteBGM
{
get { return m_GlobalMuteBGM; }
set {
if (value && IsBackgroundMusicPlaying())
StopBackgroundMusic(true);
m_GlobalMuteBGM = value;
}
}
private static bool m_GlobalMuteSFX = false;
public static bool GlobalMuteSFX
{
get { return m_GlobalMuteSFX; }
set {
if (value)
StopAllSoundEffects();
m_GlobalMuteSFX = value;
}
}
//Background music
private SoundClip m_BackgroundMusic = null;
private float m_BackgroundMusicVolume = 1.0f;
public static float BackgroundMusicVolume {
get { return m_Instance.m_BackgroundMusicVolume; }
set {
m_Instance.m_BackgroundMusicVolume = value;
if (m_Instance.m_BackgroundMusic != null)
m_Instance.m_BackgroundMusic.Volume = m_Instance.m_BackgroundMusicVolume;
}
}
private bool isFade = false;
private float m_FadeSpeed = 0;
private float m_FadeVolume = 0;
public delegate void OnFadeBackgroundMusicIn();
private OnFadeBackgroundMusicIn m_OnFadeBackgroundMusicIn;
public static OnFadeBackgroundMusicIn onFadeBackgroundMusicIn {
get { return m_Instance.m_OnFadeBackgroundMusicIn; }
set { m_Instance.m_OnFadeBackgroundMusicIn = value;}
}
public delegate void OnFadeBackgroundMusicOut();
private OnFadeBackgroundMusicOut m_OnFadeBackgroundMusicOut;
public static OnFadeBackgroundMusicOut onFadeBackgroundMusicOut {
get { return m_Instance.m_OnFadeBackgroundMusicOut; }
set { m_Instance.m_OnFadeBackgroundMusicOut = value;}
}
//Sound effects
private List<string> m_Sounds = new List<string>();
private Dictionary<string, List<SoundClip>> m_SoundEffectPool = new Dictionary<string, List<SoundClip>>();
private Dictionary<string, List<SoundClip>> m_SoundEffectActive = new Dictionary<string, List<SoundClip>>();
private List<SoundClip> m_SoundEffectOneShot = new List<SoundClip>();
private List<SoundClip> m_SoundEffectToDestroy = new List<SoundClip>();
private float m_SoundEffectVolume = 1.0f;
public static float SoundEffectVolume {
get { return m_Instance.m_SoundEffectVolume; }
set {
m_Instance.m_SoundEffectVolume = value;
//For all sounds
foreach(string s in m_Instance.m_Sounds) {
//Get pool
List<SoundClip> clips = m_Instance.m_SoundEffectPool[s];
List<SoundClip> clips_active = m_Instance.m_SoundEffectActive[s];
//Change all volume in pool
if (clips != null) {
foreach(SoundClip clip in clips) {
clip.Volume = m_Instance.m_SoundEffectVolume;
}
}
//Change all volume in active
if (clips_active != null) {
foreach(SoundClip clip in clips_active) {
clip.Volume = m_Instance.m_SoundEffectVolume;
}
}
}
}
}
private int m_ActiveSound = 0;
/* Protected mono methods */
protected void Awake() {
//Set instance
m_Instance = this;
}
protected void OnDestroy() {
//Remove
RemoveAllResources();
//Nullify singleton
m_Instance = null;
}
protected void Update() {
//Update fading background music
if (isFade) {
//Change background music volume
BackgroundMusicVolume = BackgroundMusicVolume + (m_FadeSpeed * Time.deltaTime);
//Debug.Log("Sound manager now fading.");
//Stop fading if already in or out
if (m_FadeSpeed > 0 && BackgroundMusicVolume >= m_FadeVolume) {
//Debug.Log("Sound manager fade in done.");
//Clamp
BackgroundMusicVolume = m_FadeVolume;
//Reset
isFade = false;
m_FadeSpeed = 0;
//Run delegate
if (m_OnFadeBackgroundMusicIn != null) m_OnFadeBackgroundMusicIn();
} else if (m_FadeSpeed < 0 && BackgroundMusicVolume <= m_FadeVolume) {
//Debug.Log("Sound manager fade out done.");
//Clamp
BackgroundMusicVolume = m_FadeVolume;
//Reset
isFade = false;
m_FadeSpeed = 0;
//Run delegate
if (m_OnFadeBackgroundMusicOut != null) m_OnFadeBackgroundMusicOut();
}
}
//Update sound effect active
foreach(KeyValuePair<string, List<SoundClip>> kv in m_SoundEffectActive) {
List<SoundClip> list = kv.Value;
foreach(SoundClip s in list) {
if (!s.IsPlaying()) {
//Put it back into pool
m_SoundEffectPool[kv.Key].Add(s);
m_SoundEffectToDestroy.Add(s);
}
}
foreach(SoundClip s in m_SoundEffectToDestroy) {
//Delete and make it inactive
list.Remove(s);
s.SoundObject.SetActive(false);
m_ActiveSound--;
}
m_SoundEffectToDestroy.Clear();
}
//Update single shot sound effect
foreach(SoundClip s in m_SoundEffectOneShot) {
if (!s.IsPlaying()) {
m_SoundEffectToDestroy.Add(s);
}
}
foreach(SoundClip s in m_SoundEffectToDestroy) {
m_SoundEffectOneShot.Remove(s);
s.Destroy();
m_ActiveSound--;
}
m_SoundEffectToDestroy.Clear();
}
/* Private methods */
private bool IsSoundExists(string sfx) {
//Search in sound list
foreach(string s in m_Sounds) {
if (s == sfx) return true;
}
//Don't find anything
return false;
}
/* Public static methods */
#region Background Musics
//Play background music
public static bool PlayBackgroundMusic(string name, bool loop) {
//Don't do shit if mute
if (GlobalMuteBGM) return false;
//Check BGM
if (m_Instance.m_BackgroundMusic != null && m_Instance.m_BackgroundMusic.Name != name) {
//Stop and clean
StopBackgroundMusic(true);
}
//Create new bgm if needed
if (m_Instance.m_BackgroundMusic == null) {
//Create
SoundClip s = new SoundClip(name, BGM_PATH);
m_Instance.m_BackgroundMusic = s;
}
//Set attributes
m_Instance.m_BackgroundMusic.Loop = loop;
m_Instance.m_BackgroundMusic.Volume = m_Instance.m_BackgroundMusicVolume;
//Play
m_Instance.m_BackgroundMusic.Play();
//Return
return true;
}
//Check whether background music is currently playing
public static bool IsBackgroundMusicPlaying() {
//Don't do shit if mute
if (GlobalMuteBGM) return false;
if (m_Instance.m_BackgroundMusic != null) {
return m_Instance.m_BackgroundMusic.IsPlaying();
}
return false;
}
//Resume playing background music
public static bool ResumeBackgroundMusic() {
//Don't do shit if mute
if (GlobalMuteBGM) return false;
if (m_Instance.m_BackgroundMusic != null) {
m_Instance.m_BackgroundMusic.Play();
return true;
}
return false;
}
//Pause background music
public static bool PauseBackgroundMusic() {
//Don't do shit if mute
if (GlobalMuteBGM) return false;
if (m_Instance.m_BackgroundMusic != null) {
m_Instance.m_BackgroundMusic.Pause();
return true;
}
return false;
}
//Stop background music and cleanup if needed
public static bool StopBackgroundMusic(bool cleanup) {
if (m_Instance.m_BackgroundMusic != null) {
m_Instance.m_BackgroundMusic.Stop(cleanup);
m_Instance.m_BackgroundMusic = null;
return true;
}
return false;
}
public static bool FadeBackgroundMusicIn(float time) {
return FadeBackgroundMusicIn(time, 1.0f);
}
public static bool FadeBackgroundMusicIn(float time, float volume) {
return FadeBackgroundMusic(time, m_Instance.m_BackgroundMusicVolume, volume);
}
public static bool FadeBackgroundMusicOut(float time) {
return FadeBackgroundMusicOut(time, 0f);
}
public static bool FadeBackgroundMusicOut(float time, float volume) {
return FadeBackgroundMusic(time, m_Instance.m_BackgroundMusicVolume, volume);
}
public static bool FadeBackgroundMusic(float time, float _from, float _to) {
//Debug.Log("BGM will be faded from " + _from + " to " + _to + " in " + time + " seconds.");
//Don't do shit if mute
if (GlobalMuteBGM) return false;
if (m_Instance.m_BackgroundMusic != null) {
m_Instance.m_FadeVolume = _to;
m_Instance.m_FadeSpeed = (_to - _from) / time;
m_Instance.isFade = true;
}
return m_Instance.isFade;
}
#endregion
#region Sound efffects
//Play and destroy
public static bool PlaySoundEffectOneShot(string name) {
return PlaySoundEffectOneShot(name, false, SoundEffectVolume);
}
//Play with loop, must stop manually
public static bool PlaySoundEffectOneShot(string name, bool loop, float volume) {
//Don't do shit if mute
if (GlobalMuteSFX) return false;
//Check total count, play nothing if > max
if (m_Instance.m_ActiveSound >= MAX_ACTIVE_SFX) return false;
//Check first if looping, don't create again if already there
if (loop) {
foreach(SoundClip clip in m_Instance.m_SoundEffectOneShot) {
if (clip.Name == name) {
//Play again
clip.Play();
//Return here
return true;
}
}
}
//Create new sound clip
SoundClip s = new SoundClip(name, SFX_PATH);
s.Volume = volume;
s.Loop = loop;
//Add to list and play
m_Instance.m_SoundEffectOneShot.Add(s);
s.Play();
//Add number
m_Instance.m_ActiveSound++;
return true;
}
//Get latest sound clip oneshot
public static SoundClip GetSoundEffectOneShot(string name) {
int len = m_Instance.m_SoundEffectOneShot.Count - 1;
for(int i=len;i>=0;i--) {
SoundClip s = m_Instance.m_SoundEffectOneShot[i];
if (s.Name == name) return s;
}
return null;
}
//Default is play the effect and put it back into pool
public static bool PlaySoundEffect(string name) {
//Don't do shit if mute
if (GlobalMuteSFX) return false;
//Check total count, play nothing if > max
if (m_Instance.m_ActiveSound >= MAX_ACTIVE_SFX) return false;
//Check first and preload if needed
if (!m_Instance.IsSoundExists(name)) PreloadSoundEffect(name, 1);
//Get list from pool
List<SoundClip> clips = m_Instance.m_SoundEffectPool[name];
List<SoundClip> clips_active = m_Instance.m_SoundEffectActive[name];
//Check total count per active
if (clips_active.Count >= MAX_ACTIVE_SFX_PER_SOUND) return false;
//Add another if needed
if (clips.Count == 0) PreloadSoundEffect(name, 1);
//Get the last one
SoundClip clip = clips[clips.Count - 1];
clips.Remove(clip);
//Set to active
clip.SoundObject.SetActive(true);
clips_active.Add(clip);
//Play
clip.Volume = SoundEffectVolume;
clip.Play();
m_Instance.m_ActiveSound++;
return true;
}
//Prefabricate sound effect object at certain number
public static bool PreloadSoundEffect(string name, int objectCount) {
//Don't do shit if mute
if (GlobalMuteSFX) return false;
//Check
if (!m_Instance.IsSoundExists(name)) {
//Create entry in pool
m_Instance.m_SoundEffectPool.Add(name, new List<SoundClip>());
m_Instance.m_SoundEffectActive.Add(name, new List<SoundClip>());
//Add to sounds
m_Instance.m_Sounds.Add(name);
}
//Get pool
List<SoundClip> pool = m_Instance.m_SoundEffectPool[name];
//Add new soundclip
for(int i=0;i<objectCount;i++) {
//Create
SoundClip s = new SoundClip(name, SFX_PATH);
pool.Add(s);
//Make all inactive
s.SoundObject.SetActive(false);
}
return true;
}
//Using pause, destroy will take place on update
public static void StopSoundEffect(string name) {
//Stop effect in pool
foreach(KeyValuePair<string, List<SoundClip>> kv in m_Instance.m_SoundEffectActive) {
if (kv.Key == name) {
List<SoundClip> list = kv.Value;
foreach(SoundClip s in list) s.Pause();
}
}
//Stop effect one shot
foreach(SoundClip s in m_Instance.m_SoundEffectOneShot)
if (s.Name == name) s.Pause();
}
public static void StopAllSoundEffects() {
//Stop all effect in pool
foreach(KeyValuePair<string, List<SoundClip>> kv in m_Instance.m_SoundEffectActive) {
List<SoundClip> list = kv.Value;
foreach(SoundClip s in list) s.Pause();
}
//Stop all effect one shot
foreach(SoundClip s in m_Instance.m_SoundEffectOneShot) s.Pause();
}
#endregion
#region Resources
//Removing all sound resources
public static void RemoveAllResources() {
//BGM
RemoveBackgroundMusic();
//SFX
RemoveSoundEffects();
}
//Only remove bgm resource
public static void RemoveBackgroundMusic() {
if (m_Instance.m_BackgroundMusic != null) {
m_Instance.m_BackgroundMusic.Destroy();
m_Instance.m_BackgroundMusic = null;
}
}
//Only remove sfx resources
public static void RemoveSoundEffects() {
//Delete all sound clip from pool
if (m_Instance.m_SoundEffectPool != null) {
foreach(KeyValuePair<string, List<SoundClip>> k in m_Instance.m_SoundEffectPool) {
foreach(SoundClip s in k.Value) {
s.Destroy();
}
}
m_Instance.m_SoundEffectPool.Clear();
m_Instance.m_SoundEffectPool = null;
}
//Delete all sound clip from active
if (m_Instance.m_SoundEffectActive != null) {
foreach(KeyValuePair<string, List<SoundClip>> k in m_Instance.m_SoundEffectActive) {
foreach(SoundClip s in k.Value) {
s.Destroy();
}
}
m_Instance.m_SoundEffectActive.Clear();
m_Instance.m_SoundEffectActive = null;
}
//Delete all strings
if (m_Instance.m_Sounds != null) {
m_Instance.m_Sounds.Clear();
m_Instance.m_Sounds = null;
}
}
#endregion
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Events.LdapEventSource.cs
//
// Author:
// Anil Bhatia (banil@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.Threading;
namespace Novell.Directory.Ldap.Events
{
/// <summary>
/// This is the base class for any EventSource.
/// </summary>
/// <seealso cref='Novell.Directory.Ldap.Events.PSearchEventSource'/>
/// <seealso cref='Novell.Directory.Ldap.Events.Edir.EdirEventSource'/>
public abstract class LdapEventSource
{
protected enum LISTENERS_COUNT
{
ZERO,
ONE,
MORE_THAN_ONE
}
internal protected const int EVENT_TYPE_UNKNOWN = -1;
protected const int DEFAULT_SLEEP_TIME = 1000;
protected int sleep_interval = DEFAULT_SLEEP_TIME;
/// <summary>
/// SleepInterval controls the duration after which event polling is repeated.
/// </summary>
public int SleepInterval
{
get
{
return sleep_interval;
}
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("SleepInterval", "cannot take the negative or zero values ");
sleep_interval = value;
}
}
protected abstract int GetListeners();
protected LISTENERS_COUNT GetCurrentListenersState()
{
int nListeners = 0;
// Get Listeners registered with Actual EventSource
nListeners += GetListeners();
// Get Listeners registered for generic events
if (null != directory_event)
nListeners += directory_event.GetInvocationList().Length;
// Get Listeners registered for exception events
if (null != directory_exception_event)
nListeners += directory_exception_event.GetInvocationList().Length;
if (0 == nListeners)
return LISTENERS_COUNT.ZERO;
if (1 == nListeners)
return LISTENERS_COUNT.ONE;
return LISTENERS_COUNT.MORE_THAN_ONE;
}
protected void ListenerAdded()
{
// Get current state
LISTENERS_COUNT lc = GetCurrentListenersState();
switch (lc)
{
case LISTENERS_COUNT.ONE:
// start search and polling if not already started
StartSearchAndPolling();
break;
case LISTENERS_COUNT.ZERO:
case LISTENERS_COUNT.MORE_THAN_ONE:
default:
break;
}
}
protected void ListenerRemoved()
{
// Get current state
LISTENERS_COUNT lc = GetCurrentListenersState();
switch (lc)
{
case LISTENERS_COUNT.ZERO:
// stop search and polling if not already stopped
StopSearchAndPolling();
break;
case LISTENERS_COUNT.ONE:
case LISTENERS_COUNT.MORE_THAN_ONE:
default:
break;
}
}
protected abstract void StartSearchAndPolling();
protected abstract void StopSearchAndPolling();
protected DirectoryEventHandler directory_event;
/// <summary>
/// DirectoryEvent represents a generic Directory event.
/// If any event is not recognized by the actual
/// event sources, an object of corresponding DirectoryEventArgs
/// class is passed as part of the notification.
/// </summary>
public event DirectoryEventHandler DirectoryEvent
{
add
{
directory_event += value;
ListenerAdded();
}
remove
{
directory_event -= value;
ListenerRemoved();
}
}
/// <summary>
/// DirectoryEventHandler is the delegate definition for DirectoryEvent.
/// The client (listener) has to register using this delegate in order to
/// get events that may not be recognized by the actual event source.
/// </summary>
public delegate void DirectoryEventHandler(object source, DirectoryEventArgs objDirectoryEventArgs);
protected DirectoryExceptionEventHandler directory_exception_event;
/// <summary>
/// DirectoryEvent represents a generic Directory exception event.
/// </summary>
public event DirectoryExceptionEventHandler DirectoryExceptionEvent
{
add
{
directory_exception_event += value;
ListenerAdded();
}
remove
{
directory_exception_event -= value;
ListenerRemoved();
}
}
/// <summary>
/// DirectoryEventHandler is the delegate definition for DirectoryExceptionEvent.
/// </summary>
public delegate void DirectoryExceptionEventHandler(object source, DirectoryExceptionEventArgs objDirectoryExceptionEventArgs);
protected EventsGenerator m_objEventsGenerator = null;
protected void StartEventPolling(LdapMessageQueue queue, LdapConnection conn, int msgid)
{
// validate the argument values
if ((queue == null) || (conn == null))
{
throw new ArgumentException("No parameter can be Null.");
}
if (null == m_objEventsGenerator)
{
m_objEventsGenerator = new EventsGenerator(this, queue, conn, msgid);
m_objEventsGenerator.SleepTime = sleep_interval;
m_objEventsGenerator.StartEventPolling();
}
} // end of method StartEventPolling
protected void StopEventPolling()
{
if (null != m_objEventsGenerator)
{
m_objEventsGenerator.StopEventPolling();
m_objEventsGenerator = null;
}
} // end of method StopEventPolling
protected abstract bool NotifyEventListeners(LdapMessage sourceMessage, EventClassifiers aClassification, int nType);
protected void NotifyListeners(LdapMessage sourceMessage, EventClassifiers aClassification, int nType)
{
// first let the actual source Notify the listeners with
// appropriate EventArgs
bool bListenersNotified = NotifyEventListeners(sourceMessage, aClassification, nType);
if (!bListenersNotified)
{
// Actual EventSource could not recognize the event
// Just notify the listeners for generic directory events
NotifyDirectoryListeners(sourceMessage, aClassification);
}
}
protected void NotifyDirectoryListeners(LdapMessage sourceMessage, EventClassifiers aClassification)
{
NotifyDirectoryListeners(new DirectoryEventArgs(sourceMessage, aClassification));
}
protected void NotifyDirectoryListeners(DirectoryEventArgs objDirectoryEventArgs)
{
directory_event?.Invoke(this, objDirectoryEventArgs);
}
protected void NotifyExceptionListeners(LdapMessage sourceMessage, LdapException ldapException)
{
directory_exception_event?.Invoke(this, new DirectoryExceptionEventArgs(sourceMessage, ldapException));
}
/// <summary> This is a nested class that is supposed to monitor
/// LdapMessageQueue for events generated by the LDAP Server.
///
/// </summary>
protected class EventsGenerator
{
private LdapEventSource m_objLdapEventSource;
private LdapMessageQueue searchqueue;
private int messageid;
private LdapConnection ldapconnection;
private volatile bool isrunning = true;
private int sleep_time;
/// <summary>
/// SleepTime controls the duration after which event polling is repeated.
/// </summary>
public int SleepTime
{
get
{
return sleep_time;
}
set
{
sleep_time = value;
}
}
public EventsGenerator(LdapEventSource objEventSource, LdapMessageQueue queue, LdapConnection conn, int msgid)
{
m_objLdapEventSource = objEventSource;
searchqueue = queue;
ldapconnection = conn;
messageid = msgid;
sleep_time = DEFAULT_SLEEP_TIME;
} // end of Constructor
protected void Run()
{
while (isrunning)
{
LdapMessage response = null;
try
{
while ((isrunning)
&& (!searchqueue.isResponseReceived(messageid)))
{
try
{
Thread.Sleep(sleep_time);
}
catch (Exception e)
{
Console.WriteLine("EventsGenerator::Run Got ThreadInterruptedException e = {0}", e);
}
}
if (isrunning)
{
response = searchqueue.getResponse(messageid);
}
if (response != null)
{
processmessage(response);
}
}
catch (LdapException e)
{
m_objLdapEventSource.NotifyExceptionListeners(response, e);
}
}
} // end of method run
protected void processmessage(LdapMessage response)
{
if (response is LdapResponse)
{
try
{
((LdapResponse)response).chkResultCode();
m_objLdapEventSource.NotifyEventListeners(response,
EventClassifiers.CLASSIFICATION_UNKNOWN,
EVENT_TYPE_UNKNOWN);
}
catch (LdapException e)
{
m_objLdapEventSource.NotifyExceptionListeners(response, e);
}
}
else
{
m_objLdapEventSource.NotifyEventListeners(response,
EventClassifiers.CLASSIFICATION_UNKNOWN,
EVENT_TYPE_UNKNOWN);
}
} // end of method processmessage
public void StartEventPolling()
{
isrunning = true;
new Thread(Run).Start();
}
public void StopEventPolling()
{
isrunning = false;
} // end of method stopEventGeneration
} // end of class EventsGenerator
} // end of class LdapEventSource
} // end of namespace
| |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Hotcakes.Commerce.Globalization;
using Hotcakes.CommerceDTO.v1.Contacts;
using Hotcakes.Web.Geography;
namespace Hotcakes.Commerce.Contacts
{
/// <summary>
/// This is the main object that is used for all address management in the main application
/// </summary>
/// <remarks>The main REST API equivalent to this is the AddressDTO object</remarks>
[Serializable]
public class Address : IAddress
{
private readonly XmlWriterSettings _hccXmlWriterSettings = new XmlWriterSettings();
private string _postalCode = string.Empty;
public Address()
{
Init();
}
// removed since resharper says it is not being used
//private XmlReaderSettings _hccXmlReaderSettings = new XmlReaderSettings();
/// <summary>
/// This is the unique ID of the address.
/// </summary>
public string Bvin { get; set; }
/// <summary>
/// The last updated date is used for auditing purposes to know when the address was last updated.
/// </summary>
public DateTime LastUpdatedUtc { get; set; }
/// <summary>
/// This is the ID of the Hotcakes store. Typically, this is 1, except in multi-tenant environments.
/// </summary>
public long StoreId { get; set; }
/// <summary>
/// A user-defined value to name this address for easy identification in the user interface.
/// </summary>
public string NickName { get; set; }
/// <summary>
/// The first name of the recipient at this address.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// The middle iniital of the recipient at this address.
/// </summary>
public string MiddleInitial { get; set; }
/// <summary>
/// The last name or surname of the recipient at this address.
/// </summary>
public string LastName { get; set; }
/// <summary>
/// If this is not a residential address, a company name should be specified.
/// </summary>
public string Company { get; set; }
/// <summary>
/// The first line of the street address, such as 123 Main Street.
/// </summary>
/// <remarks>This property is mapped to the Street property.</remarks>
public string Line1 { get; set; }
/// <summary>
/// The second line of the street address, such as Suite 100.
/// </summary>
/// <remarks>This property is mapped to the Street2 property.</remarks>
public string Line2 { get; set; }
/// <summary>
/// The third line of the street address. Usually used for non-US or military addresses.
/// </summary>
public string Line3 { get; set; }
/// <summary>
/// If RegionData is not null, this property will contain the RegionData.SystemName. Otherwise, this will be an empty
/// string.
/// </summary>
public string RegionSystemName
{
get { return RegionData != null ? RegionData.SystemName : string.Empty; }
}
/// <summary>
/// If RegionData is not null, this property will contain the RegionData.DisplayName. Otherwise, this will be an empty
/// string.
/// </summary>
public string RegionDisplayName
{
get { return RegionData != null ? RegionData.DisplayName : string.Empty; }
}
/// <summary>
/// If CountryData is not null, this property will contain the CountryData.SystemName. Otherwise, this will be an empty
/// string.
/// </summary>
public string CountrySystemName
{
get { return CountryData != null ? CountryData.SystemName : string.Empty; }
}
/// <summary>
/// If CountryData is not null, this property will contain the CountryData.DisplayName. Otherwise, this will be an
/// empty string.
/// </summary>
public string CountryDisplayName
{
get { return CountryData != null ? CountryData.DisplayName : string.Empty; }
}
/// <summary>
/// A telephone number for the address.
/// </summary>
public string Phone { get; set; }
/// <summary>
/// A fax or facsimile number for the address.
/// </summary>
public string Fax { get; set; }
/// <summary>
/// A website URL for the address. Primarily used for vendors and manufacturers.
/// </summary>
public string WebSiteUrl { get; set; }
/// <summary>
/// Addresses are mapped back to a CMS user record, even for vendors and manufacturers. This field is the user ID.
/// </summary>
public string UserBvin { get; set; }
//public bool Residential {get;set;}
/// <summary>
/// Allows you to specify if the address belongs to the merchant or not.
/// </summary>
public AddressTypes AddressType { get; set; }
/// <summary>
/// The name of the city.
/// </summary>
public string City { get; set; }
/// <summary>
/// This should contain a valid ID of the Region, if applicable.
/// </summary>
public string RegionBvin { get; set; }
/// <summary>
/// Contains a localization-friendly mapping of the region information and it's respective country.
/// </summary>
public IRegion RegionData
{
get
{
try
{
var countryRepo = Factory.CreateRepo<CountryRepository>();
return countryRepo.Find(CountryBvin).Regions.
Where(r => r.Abbreviation == RegionBvin).
FirstOrDefault();
}
catch
{
return null;
}
}
}
/// <summary>
/// Contains the zip or postal code of the address, as necessary.
/// </summary>
public string PostalCode
{
get { return _postalCode; }
set { _postalCode = value; }
}
/// <summary>
/// This is the unique ID or bvin of the country related to this address.
/// </summary>
public string CountryBvin { get; set; }
/// <summary>
/// A populated instance of a localized country object matching this address.
/// </summary>
public ICountry CountryData
{
get
{
var countryRepo = Factory.CreateRepo<CountryRepository>();
return countryRepo.Find(CountryBvin);
}
}
private void Init()
{
StoreId = 0;
NickName = string.Empty;
FirstName = string.Empty;
MiddleInitial = string.Empty;
LastName = string.Empty;
Company = string.Empty;
Line1 = string.Empty;
Line2 = string.Empty;
Line3 = string.Empty;
City = string.Empty;
RegionBvin = string.Empty;
PostalCode = string.Empty;
//this.CountryBvin = Country.UnitedStatesCountryBvin;
CountryBvin = string.Empty;
Phone = string.Empty;
Fax = string.Empty;
WebSiteUrl = string.Empty;
UserBvin = string.Empty;
AddressType = AddressTypes.General;
LastUpdatedUtc = DateTime.UtcNow;
}
/// <summary>
/// Allows you to populate this address from an XML data source.
/// </summary>
/// <param name="xr">A loaded instance of an XmlReader containing a serialized address object.</param>
/// <returns>Returns true is the XML is successfully parsed.</returns>
public bool FromXml(ref XmlReader xr)
{
var results = false;
try
{
while (xr.Read())
{
if (xr.IsStartElement())
{
if (!xr.IsEmptyElement)
{
switch (xr.Name)
{
case "Bvin":
xr.Read();
Bvin = xr.ReadString();
break;
case "NickName":
xr.Read();
NickName = xr.ReadString();
break;
case "FirstName":
xr.Read();
FirstName = xr.ReadString();
break;
case "MiddleInitial":
xr.Read();
MiddleInitial = xr.ReadString();
break;
case "LastName":
xr.Read();
LastName = xr.ReadString();
break;
case "Company":
xr.Read();
Company = xr.ReadString();
break;
case "Line1":
xr.Read();
Line1 = xr.ReadString();
break;
case "Line2":
xr.Read();
Line2 = xr.ReadString();
break;
case "Line3":
xr.Read();
Line3 = xr.ReadString();
break;
case "City":
xr.Read();
City = xr.ReadString();
break;
case "RegionBvin":
xr.Read();
RegionBvin = xr.ReadString();
break;
case "PostalCode":
xr.Read();
_postalCode = xr.ReadString();
break;
case "CountryBvin":
xr.Read();
CountryBvin = xr.ReadString();
break;
case "Phone":
xr.Read();
Phone = xr.ReadString();
break;
case "Fax":
xr.Read();
Fax = xr.ReadString();
break;
case "WebSiteUrl":
xr.Read();
WebSiteUrl = xr.ReadString();
break;
case "LastUpdated":
xr.Read();
LastUpdatedUtc = DateTime.Parse(xr.ReadString());
break;
case "UserBvin":
xr.Read();
UserBvin = xr.ReadString();
break;
//case "Residential":
// xr.Read();
// Residential = bool.Parse(xr.ReadString());
// break;
case "AddressType":
xr.Read();
var tempType = int.Parse(xr.ReadString());
AddressType = (AddressTypes) tempType;
break;
}
}
}
}
results = true;
}
catch (XmlException ex)
{
EventLog.LogEvent(ex);
results = false;
}
return results;
}
/// <summary>
/// Allows you to pass in an XmlWriter to emit the current address as XML.
/// </summary>
/// <param name="xw">A byreference instance of an XmlWriter.</param>
public void ToXmlWriter(ref XmlWriter xw)
{
if (xw != null)
{
xw.WriteStartElement("Address");
xw.WriteElementString("Bvin", Bvin);
xw.WriteElementString("NickName", NickName);
xw.WriteElementString("FirstName", FirstName);
xw.WriteElementString("MiddleInitial", MiddleInitial);
xw.WriteElementString("LastName", LastName);
xw.WriteElementString("Company", Company);
xw.WriteElementString("Line1", Line1);
xw.WriteElementString("Line2", Line2);
xw.WriteElementString("Line3", Line3);
xw.WriteElementString("City", City);
xw.WriteElementString("RegionName", RegionSystemName);
xw.WriteElementString("RegionBvin", RegionBvin);
xw.WriteElementString("PostalCode", _postalCode);
xw.WriteElementString("CountryName", CountrySystemName);
xw.WriteElementString("CountryBvin", CountryBvin);
xw.WriteElementString("Phone", Phone);
xw.WriteElementString("Fax", Fax);
xw.WriteElementString("WebSiteUrl", WebSiteUrl);
xw.WriteElementString("UserBvin", UserBvin);
//xw.WriteStartElement("Residential");
//xw.WriteValue(_Residential);
//xw.WriteEndElement();
xw.WriteStartElement("LastUpdated");
xw.WriteValue(LastUpdatedUtc);
xw.WriteEndElement();
xw.WriteElementString("AddressType", ((int) AddressType).ToString());
xw.WriteEndElement();
}
}
/// <summary>
/// Allows you to generate an HTML representation of the current Address object.
/// </summary>
/// <returns>An HTML representation of the current Address object.</returns>
public string ToHtmlString()
{
var sb = new StringBuilder();
if (NickName.Trim().Length > 0)
{
sb.Append("<em>" + NickName + "</em><br />");
}
if (LastName.Length > 0 || FirstName.Length > 0)
{
sb.Append(FirstName);
if (MiddleInitial.Trim().Length > 0)
{
sb.Append(" " + MiddleInitial);
}
sb.Append(" " + LastName + "<br />");
if (Company.Trim().Length > 0)
{
sb.Append(Company + "<br />");
}
}
sb.Append(GetLinesHtml());
return sb.ToString();
}
/// <summary>
/// Returns a List-based representation of the address, including all of the common addres properties, as specified in
/// the parameters.
/// </summary>
/// <param name="appendNameAndCompany">It true, the full name and company name will be included in the list.</param>
/// <param name="appendPhones">If true, the phone, fax, and website URL will be included in the list.</param>
/// <returns>List - an array of the address information in the current object.</returns>
public List<string> GetLines(bool appendNameAndCompany = true, bool appendPhones = true)
{
var lines = new List<string>();
if (appendNameAndCompany)
{
lines.Add(
LastName +
(string.IsNullOrWhiteSpace(MiddleInitial) ? "" : " " + MiddleInitial.Trim()) +
(string.IsNullOrWhiteSpace(FirstName) ? "" : " " + FirstName.Trim())
);
lines.Add(Company);
}
lines.Add(Line1);
lines.Add(Line2);
lines.Add(Line3);
var cityLine = City;
if (RegionData != null)
{
cityLine = string.Concat(cityLine, ", ", RegionData.Abbreviation, " ", _postalCode);
}
else
{
if (!string.IsNullOrEmpty(_postalCode))
{
cityLine = string.Concat(cityLine, ", ", _postalCode);
}
}
if (cityLine.Trim() != ",") lines.Add(cityLine);
if (CountryData != null && !string.IsNullOrEmpty(CountryData.DisplayName))
{
lines.Add(CountryData.DisplayName);
}
if (appendPhones)
{
lines.Add(Phone);
if (!string.IsNullOrWhiteSpace(Fax))
{
lines.Add("Fax: " + Fax);
}
lines.Add(WebSiteUrl);
}
// Remove empty lines
var i = 0;
while (i < lines.Count)
{
if (string.IsNullOrWhiteSpace(lines[i]))
{
lines.RemoveAt(i);
}
else
{
i++;
}
}
return lines;
}
/// <summary>
/// Returns an HTML-based representation of the address, including all of the common addres properties, as specified in
/// the parameters.
/// </summary>
/// <param name="appendNameAndCompany">It true, the full name and company name will be included in the list.</param>
/// <param name="appendPhones">If true, the phone, fax, and website URL will be included in the list.</param>
/// <returns>String - The address information in the current object, with each line specified by a BR tag.</returns>
public string GetLinesHtml(bool appendNameAndCompany = false, bool appendPhones = true)
{
var sb = new StringBuilder();
foreach (var line in GetLines(appendNameAndCompany, appendPhones))
{
sb.Append(line);
sb.AppendLine("<br />");
}
return sb.ToString();
}
/// <summary>
/// Allows you to compare another address object to determine if the two addresses are the same.
/// </summary>
/// <param name="a2">Another address object.</param>
/// <returns>If true, the current address matches the address in the parameter.</returns>
public bool IsEqualTo(Address a2)
{
if (a2 == null)
{
return false;
}
var result = true;
if (string.Compare(NickName.Trim(), a2.NickName.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(FirstName.Trim(), a2.FirstName.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(MiddleInitial.Trim(), a2.MiddleInitial.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(LastName.Trim(), a2.LastName.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(Company.Trim(), a2.Company.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(Line1.Trim(), a2.Line1.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(Line2.Trim(), a2.Line2.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(Line3.Trim(), a2.Line3.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(RegionBvin.Trim(), a2.RegionBvin.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(City.Trim(), a2.City.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(PostalCode.Trim(), a2.PostalCode.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(CountryBvin.Trim(), a2.CountryBvin.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(Phone.Trim(), a2.Phone.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(Fax.Trim(), a2.Fax.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
if (string.Compare(WebSiteUrl.Trim(), a2.WebSiteUrl.Trim(), true, CultureInfo.InvariantCulture) != 0)
{
result = false;
}
//if (this.Residential != a2.Residential) {
// result = false;
//}
return result;
}
/// <summary>
/// Used to copy the current address object to another address object.
/// </summary>
/// <param name="destinationAddress">An instance of Address where you want the address to be copied to</param>
/// <returns>If the copy can execute successfully, true will be returned.</returns>
public bool CopyTo(Address destinationAddress)
{
var result = true;
try
{
destinationAddress.Bvin = Bvin;
destinationAddress.NickName = NickName;
destinationAddress.FirstName = FirstName;
destinationAddress.MiddleInitial = MiddleInitial;
destinationAddress.LastName = LastName;
destinationAddress.Company = Company;
destinationAddress.Line1 = Line1;
destinationAddress.Line2 = Line2;
destinationAddress.Line3 = Line3;
destinationAddress.City = City;
destinationAddress.RegionBvin = RegionBvin;
destinationAddress.PostalCode = PostalCode;
destinationAddress.CountryBvin = CountryBvin;
destinationAddress.Phone = Phone;
destinationAddress.Fax = Fax;
destinationAddress.WebSiteUrl = WebSiteUrl;
//destinationAddress.Residential = this.Residential;
}
catch
{
result = false;
}
return result;
}
/// <summary>
/// Allows you to return a serialized version of this address in XML format.
/// </summary>
/// <param name="omitDeclaration">This value is not used in this method.</param>
/// <returns>A string representation of the Address object in XML format.</returns>
public virtual string ToXml(bool omitDeclaration)
{
var response = string.Empty;
var sb = new StringBuilder();
_hccXmlWriterSettings.ConformanceLevel = ConformanceLevel.Fragment;
var xw = XmlWriter.Create(sb, _hccXmlWriterSettings);
ToXmlWriter(ref xw);
xw.Flush();
xw.Close();
response = sb.ToString();
return response;
}
/// <summary>
/// Used to deserialize an XML string to form a new Address object.
/// </summary>
/// <param name="x">String - the XML used to create an Address object.</param>
/// <returns>If successful, true will be returned.</returns>
public virtual bool FromXmlString(string x)
{
var sw = new StringReader(x);
var xr = XmlReader.Create(sw);
var result = FromXml(ref xr);
sw.Dispose();
xr.Close();
return result;
}
#region DTO
/// <summary>
/// Allows you to convert the current address object to the DTO equivalent for use with the REST API
/// </summary>
/// <returns>A new instance of AddressDTO</returns>
public AddressDTO ToDto()
{
var dto = new AddressDTO();
dto.Bvin = Bvin;
dto.StoreId = StoreId;
dto.NickName = NickName ?? string.Empty;
dto.FirstName = FirstName ?? string.Empty;
dto.MiddleInitial = MiddleInitial ?? string.Empty;
dto.LastName = LastName ?? string.Empty;
dto.Company = Company ?? string.Empty;
dto.Line1 = Line1 ?? string.Empty;
dto.Line2 = Line2 ?? string.Empty;
dto.Line3 = Line3 ?? string.Empty;
dto.City = City ?? string.Empty;
dto.RegionName = RegionSystemName ?? string.Empty;
dto.RegionBvin = RegionBvin ?? string.Empty;
dto.PostalCode = PostalCode ?? string.Empty;
dto.CountryName = CountrySystemName ?? string.Empty;
dto.CountryBvin = CountryBvin ?? string.Empty;
dto.Phone = Phone ?? string.Empty;
dto.Fax = Fax ?? string.Empty;
dto.WebSiteUrl = WebSiteUrl ?? string.Empty;
dto.UserBvin = UserBvin ?? string.Empty;
dto.AddressType = (AddressTypesDTO) (int) AddressType;
dto.LastUpdatedUtc = LastUpdatedUtc;
return dto;
}
/// <summary>
/// Allows you to populate the current address object using an AddressDTO instance
/// </summary>
/// <param name="dto">An instance of the Address from the REST API</param>
public void FromDto(AddressDTO dto)
{
Bvin = dto.Bvin;
StoreId = dto.StoreId;
NickName = dto.NickName ?? string.Empty;
FirstName = dto.FirstName ?? string.Empty;
MiddleInitial = dto.MiddleInitial ?? string.Empty;
LastName = dto.LastName ?? string.Empty;
Company = dto.Company ?? string.Empty;
Line1 = dto.Line1 ?? string.Empty;
Line2 = dto.Line2 ?? string.Empty;
Line3 = dto.Line3 ?? string.Empty;
City = dto.City ?? string.Empty;
RegionBvin = dto.RegionBvin ?? string.Empty;
PostalCode = dto.PostalCode ?? string.Empty;
CountryBvin = dto.CountryBvin ?? string.Empty;
Phone = dto.Phone ?? string.Empty;
Fax = dto.Fax ?? string.Empty;
WebSiteUrl = dto.WebSiteUrl ?? string.Empty;
UserBvin = dto.UserBvin ?? string.Empty;
AddressType = (AddressTypes) (int) dto.AddressType;
LastUpdatedUtc = dto.LastUpdatedUtc;
}
#endregion
#region IAddress Members
/// <summary>
/// The first line of the street address, such as 123 Main Street.
/// </summary>
/// <remarks>This property is mapped to the Line1 property.</remarks>
public string Street
{
get { return Line1; }
set { Line1 = value; }
}
/// <summary>
/// The second line of the street address, such as Suite 100.
/// </summary>
/// <remarks>This property is mapped to the Line2 property.</remarks>
public string Street2
{
get { return Line2; }
set { Line2 = value; }
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace YAF.Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IBits = YAF.Lucene.Net.Util.IBits;
using MultiSortedDocValues = YAF.Lucene.Net.Index.MultiDocValues.MultiSortedDocValues;
using MultiSortedSetDocValues = YAF.Lucene.Net.Index.MultiDocValues.MultiSortedSetDocValues;
using OrdinalMap = YAF.Lucene.Net.Index.MultiDocValues.OrdinalMap;
/// <summary>
/// This class forces a composite reader (eg a
/// <see cref="MultiReader"/> or <see cref="DirectoryReader"/>) to emulate an
/// atomic reader. This requires implementing the postings
/// APIs on-the-fly, using the static methods in
/// <see cref="MultiFields"/>, <see cref="MultiDocValues"/>, by stepping through
/// the sub-readers to merge fields/terms, appending docs, etc.
///
/// <para/><b>NOTE</b>: This class almost always results in a
/// performance hit. If this is important to your use case,
/// you'll get better performance by gathering the sub readers using
/// <see cref="IndexReader.Context"/> to get the
/// atomic leaves and then operate per-AtomicReader,
/// instead of using this class.
/// </summary>
public sealed class SlowCompositeReaderWrapper : AtomicReader
{
private readonly CompositeReader @in;
private readonly Fields fields;
private readonly IBits liveDocs;
/// <summary>
/// This method is sugar for getting an <see cref="AtomicReader"/> from
/// an <see cref="IndexReader"/> of any kind. If the reader is already atomic,
/// it is returned unchanged, otherwise wrapped by this class.
/// </summary>
public static AtomicReader Wrap(IndexReader reader)
{
CompositeReader compositeReader = reader as CompositeReader;
if (compositeReader != null)
{
return new SlowCompositeReaderWrapper(compositeReader);
}
else
{
Debug.Assert(reader is AtomicReader);
return (AtomicReader)reader;
}
}
private SlowCompositeReaderWrapper(CompositeReader reader)
: base()
{
@in = reader;
fields = MultiFields.GetFields(@in);
liveDocs = MultiFields.GetLiveDocs(@in);
@in.RegisterParentReader(this);
}
public override string ToString()
{
return "SlowCompositeReaderWrapper(" + @in + ")";
}
public override Fields Fields
{
get
{
EnsureOpen();
return fields;
}
}
public override NumericDocValues GetNumericDocValues(string field)
{
EnsureOpen();
return MultiDocValues.GetNumericValues(@in, field);
}
public override IBits GetDocsWithField(string field)
{
EnsureOpen();
return MultiDocValues.GetDocsWithField(@in, field);
}
public override BinaryDocValues GetBinaryDocValues(string field)
{
EnsureOpen();
return MultiDocValues.GetBinaryValues(@in, field);
}
public override SortedDocValues GetSortedDocValues(string field)
{
EnsureOpen();
OrdinalMap map = null;
lock (cachedOrdMaps)
{
if (!cachedOrdMaps.TryGetValue(field, out map))
{
// uncached, or not a multi dv
SortedDocValues dv = MultiDocValues.GetSortedValues(@in, field);
MultiSortedDocValues docValues = dv as MultiSortedDocValues;
if (docValues != null)
{
map = docValues.Mapping;
if (map.owner == CoreCacheKey)
{
cachedOrdMaps[field] = map;
}
}
return dv;
}
}
// cached ordinal map
if (FieldInfos.FieldInfo(field).DocValuesType != DocValuesType.SORTED)
{
return null;
}
int size = @in.Leaves.Count;
SortedDocValues[] values = new SortedDocValues[size];
int[] starts = new int[size + 1];
for (int i = 0; i < size; i++)
{
AtomicReaderContext context = @in.Leaves[i];
SortedDocValues v = context.AtomicReader.GetSortedDocValues(field) ?? DocValues.EMPTY_SORTED;
values[i] = v;
starts[i] = context.DocBase;
}
starts[size] = MaxDoc;
return new MultiSortedDocValues(values, starts, map);
}
public override SortedSetDocValues GetSortedSetDocValues(string field)
{
EnsureOpen();
OrdinalMap map = null;
lock (cachedOrdMaps)
{
if (!cachedOrdMaps.TryGetValue(field, out map))
{
// uncached, or not a multi dv
SortedSetDocValues dv = MultiDocValues.GetSortedSetValues(@in, field);
MultiSortedSetDocValues docValues = dv as MultiSortedSetDocValues;
if (docValues != null)
{
map = docValues.Mapping;
if (map.owner == CoreCacheKey)
{
cachedOrdMaps[field] = map;
}
}
return dv;
}
}
// cached ordinal map
if (FieldInfos.FieldInfo(field).DocValuesType != DocValuesType.SORTED_SET)
{
return null;
}
Debug.Assert(map != null);
int size = @in.Leaves.Count;
var values = new SortedSetDocValues[size];
int[] starts = new int[size + 1];
for (int i = 0; i < size; i++)
{
AtomicReaderContext context = @in.Leaves[i];
SortedSetDocValues v = context.AtomicReader.GetSortedSetDocValues(field) ?? DocValues.EMPTY_SORTED_SET;
values[i] = v;
starts[i] = context.DocBase;
}
starts[size] = MaxDoc;
return new MultiSortedSetDocValues(values, starts, map);
}
// TODO: this could really be a weak map somewhere else on the coreCacheKey,
// but do we really need to optimize slow-wrapper any more?
private readonly IDictionary<string, OrdinalMap> cachedOrdMaps = new Dictionary<string, OrdinalMap>();
public override NumericDocValues GetNormValues(string field)
{
EnsureOpen();
return MultiDocValues.GetNormValues(@in, field);
}
public override Fields GetTermVectors(int docID)
{
EnsureOpen();
return @in.GetTermVectors(docID);
}
public override int NumDocs
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return @in.NumDocs;
}
}
public override int MaxDoc
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return @in.MaxDoc;
}
}
public override void Document(int docID, StoredFieldVisitor visitor)
{
EnsureOpen();
@in.Document(docID, visitor);
}
public override IBits LiveDocs
{
get
{
EnsureOpen();
return liveDocs;
}
}
public override FieldInfos FieldInfos
{
get
{
EnsureOpen();
return MultiFields.GetMergedFieldInfos(@in);
}
}
public override object CoreCacheKey
{
get
{
return @in.CoreCacheKey;
}
}
public override object CombinedCoreAndDeletesKey
{
get
{
return @in.CombinedCoreAndDeletesKey;
}
}
protected internal override void DoClose()
{
// TODO: as this is a wrapper, should we really close the delegate?
@in.Dispose();
}
public override void CheckIntegrity()
{
EnsureOpen();
foreach (AtomicReaderContext ctx in @in.Leaves)
{
ctx.AtomicReader.CheckIntegrity();
}
}
}
}
| |
/************************************************************************************
Filename : OVRLipSync.cs
Content : Interface to Oculus Lip Sync engine
Created : August 4th, 2015
Copyright : Copyright Facebook Technologies, LLC and its affiliates.
All rights reserved.
Licensed under the Oculus Audio SDK License Version 3.3 (the "License");
you may not use the Oculus Audio SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/audio-3.3/
Unless required by applicable law or agreed to in writing, the Oculus Audio SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using System;
using System.Runtime.InteropServices;
//-------------------------------------------------------------------------------------
// ***** OVRLipSync
//
/// <summary>
/// OVRLipSync interfaces into the Oculus lip sync engine. This component should be added
/// into the scene once.
///
/// </summary>
public class OVRLipSync : MonoBehaviour
{
// Error codes that may return from Lip Sync engine
public enum Result
{
Success = 0,
Unknown = -2200, //< An unknown error has occurred
CannotCreateContext = -2201, //< Unable to create a context
InvalidParam = -2202, //< An invalid parameter, e.g. NULL pointer or out of range
BadSampleRate = -2203, //< An unsupported sample rate was declared
MissingDLL = -2204, //< The DLL or shared library could not be found
BadVersion = -2205, //< Mismatched versions between header and libs
UndefinedFunction = -2206 //< An undefined function
};
// Audio buffer data type
public enum AudioDataType
{
// Signed 16-bit integer mono audio stream
S16_Mono,
// Signed 16-bit integer stereo audio stream
S16_Stereo,
// Signed 32-bit float mono audio stream
F32_Mono,
// Signed 32-bit float stereo audio stream
F32_Stereo
};
// Various visemes
public enum Viseme
{
sil,
PP,
FF,
TH,
DD,
kk,
CH,
SS,
nn,
RR,
aa,
E,
ih,
oh,
ou
};
public static readonly int VisemeCount = Enum.GetNames(typeof(Viseme)).Length;
// Enum for sending lip-sync engine specific signals
public enum Signals
{
VisemeOn,
VisemeOff,
VisemeAmount,
VisemeSmoothing,
LaughterAmount
};
public static readonly int SignalCount = Enum.GetNames(typeof(Signals)).Length;
// Enum for provider context to create
public enum ContextProviders
{
Original,
Enhanced,
Enhanced_with_Laughter,
};
/// NOTE: Opaque typedef for lip-sync context is an unsigned int (uint)
/// Current phoneme frame results
[System.Serializable]
public class Frame
{
public void CopyInput(Frame input)
{
frameNumber = input.frameNumber;
frameDelay = input.frameDelay;
input.Visemes.CopyTo(Visemes, 0);
laughterScore = input.laughterScore;
}
public void Reset()
{
frameNumber = 0;
frameDelay = 0;
Array.Clear(Visemes, 0, VisemeCount);
laughterScore = 0;
}
public int frameNumber; // count from start of recognition
public int frameDelay; // in ms
public float[] Visemes = new float[VisemeCount]; // Array of floats for viseme frame. Size of Viseme Count, above
public float laughterScore; // probability of laughter presence.
};
// * * * * * * * * * * * * *
// Import functions
#if !UNITY_IOS || UNITY_EDITOR
public const string strOVRLS = "OVRLipSync";
#else
public const string strOVRLS = "__Internal";
#endif
[DllImport(strOVRLS)]
private static extern int ovrLipSyncDll_Initialize(int samplerate, int buffersize);
[DllImport(strOVRLS)]
private static extern void ovrLipSyncDll_Shutdown();
[DllImport(strOVRLS)]
private static extern IntPtr ovrLipSyncDll_GetVersion(ref int Major,
ref int Minor,
ref int Patch);
[DllImport(strOVRLS)]
private static extern int ovrLipSyncDll_CreateContextEx(ref uint context,
ContextProviders provider,
int sampleRate,
bool enableAcceleration);
[DllImport(strOVRLS)]
private static extern int ovrLipSyncDll_CreateContextWithModelFile(ref uint context,
ContextProviders provider,
string modelPath,
int sampleRate,
bool enableAcceleration);
[DllImport(strOVRLS)]
private static extern int ovrLipSyncDll_DestroyContext(uint context);
[DllImport(strOVRLS)]
private static extern int ovrLipSyncDll_ResetContext(uint context);
[DllImport(strOVRLS)]
private static extern int ovrLipSyncDll_SendSignal(uint context,
Signals signal,
int arg1, int arg2);
[DllImport(strOVRLS)]
private static extern int ovrLipSyncDll_ProcessFrameEx(
uint context,
IntPtr audioBuffer,
uint bufferSize,
AudioDataType dataType,
ref int frameNumber,
ref int frameDelay,
float[] visemes,
int visemeCount,
ref float laughterScore,
float[] laughterCategories,
int laughterCategoriesLength);
// * * * * * * * * * * * * *
// Public members
// * * * * * * * * * * * * *
// Static members
private static Result sInitialized = Result.Unknown;
// interface through this static member.
public static OVRLipSync sInstance = null;
// * * * * * * * * * * * * *
// MonoBehaviour overrides
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
// We can only have one instance of OVRLipSync in a scene (use this for local property query)
if (sInstance == null)
{
sInstance = this;
}
else
{
Debug.LogWarning(System.String.Format("OVRLipSync Awake: Only one instance of OVRPLipSync can exist in the scene."));
return;
}
if (IsInitialized() != Result.Success)
{
sInitialized = Initialize();
if (sInitialized != Result.Success)
{
Debug.LogWarning(System.String.Format
("OvrLipSync Awake: Failed to init Speech Rec library"));
}
}
// Important: Use the touchpad mechanism for input, call Create on the OVRTouchpad helper class
OVRTouchpad.Create();
}
/// <summary>
/// Raises the destroy event.
/// </summary>
void OnDestroy()
{
if (sInstance != this)
{
Debug.LogWarning(
"OVRLipSync OnDestroy: This is not the correct OVRLipSync instance.");
return;
}
// Do not shut down at this time
// ovrLipSyncDll_Shutdown();
// sInitialized = (int)Result.Unknown;
}
// * * * * * * * * * * * * *
// Public Functions
public static Result Initialize()
{
int sampleRate;
int bufferSize;
int numbuf;
// Get the current sample rate
sampleRate = AudioSettings.outputSampleRate;
// Get the current buffer size and number of buffers
AudioSettings.GetDSPBufferSize(out bufferSize, out numbuf);
String str = System.String.Format
("OvrLipSync Awake: Queried SampleRate: {0:F0} BufferSize: {1:F0}", sampleRate, bufferSize);
Debug.LogWarning(str);
sInitialized = (Result)ovrLipSyncDll_Initialize(sampleRate, bufferSize);
return sInitialized;
}
public static Result Initialize(int sampleRate, int bufferSize)
{
String str = System.String.Format
("OvrLipSync Awake: Queried SampleRate: {0:F0} BufferSize: {1:F0}", sampleRate, bufferSize);
Debug.LogWarning(str);
sInitialized = (Result)ovrLipSyncDll_Initialize(sampleRate, bufferSize);
return sInitialized;
}
public static void Shutdown()
{
ovrLipSyncDll_Shutdown();
sInitialized = Result.Unknown;
}
/// <summary>
/// Determines if is initialized.
/// </summary>
/// <returns><c>true</c> if is initialized; otherwise, <c>false</c>.</returns>
public static Result IsInitialized()
{
return sInitialized;
}
/// <summary>
/// Creates a lip-sync context.
/// </summary>
/// <returns>error code</returns>
/// <param name="context">Context.</param>
/// <param name="provider">Provider.</param>
/// <param name="enableAcceleration">Enable DSP Acceleration.</param>
public static Result CreateContext(
ref uint context,
ContextProviders provider,
int sampleRate = 0,
bool enableAcceleration = false)
{
if (IsInitialized() != Result.Success && Initialize() != Result.Success)
return Result.CannotCreateContext;
return (Result)ovrLipSyncDll_CreateContextEx(ref context, provider, sampleRate, enableAcceleration);
}
/// <summary>
/// Creates a lip-sync context with specified model file.
/// </summary>
/// <returns>error code</returns>
/// <param name="context">Context.</param>
/// <param name="provider">Provider.</param>
/// <param name="modelPath">Model Dir.</param>
/// <param name="sampleRate">Sampling Rate.</param>
/// <param name="enableAcceleration">Enable DSP Acceleration.</param>
public static Result CreateContextWithModelFile(
ref uint context,
ContextProviders provider,
string modelPath,
int sampleRate = 0,
bool enableAcceleration = false)
{
if (IsInitialized() != Result.Success && Initialize() != Result.Success)
return Result.CannotCreateContext;
return (Result)ovrLipSyncDll_CreateContextWithModelFile(
ref context,
provider,
modelPath,
sampleRate,
enableAcceleration);
}
/// <summary>
/// Destroy a lip-sync context.
/// </summary>
/// <returns>The context.</returns>
/// <param name="context">Context.</param>
public static Result DestroyContext(uint context)
{
if (IsInitialized() != Result.Success)
return Result.Unknown;
return (Result)ovrLipSyncDll_DestroyContext(context);
}
/// <summary>
/// Resets the context.
/// </summary>
/// <returns>error code</returns>
/// <param name="context">Context.</param>
public static Result ResetContext(uint context)
{
if (IsInitialized() != Result.Success)
return Result.Unknown;
return (Result)ovrLipSyncDll_ResetContext(context);
}
/// <summary>
/// Sends a signal to the lip-sync engine.
/// </summary>
/// <returns>error code</returns>
/// <param name="context">Context.</param>
/// <param name="signal">Signal.</param>
/// <param name="arg1">Arg1.</param>
/// <param name="arg2">Arg2.</param>
public static Result SendSignal(uint context, Signals signal, int arg1, int arg2)
{
if (IsInitialized() != Result.Success)
return Result.Unknown;
return (Result)ovrLipSyncDll_SendSignal(context, signal, arg1, arg2);
}
/// <summary>
/// Process float[] audio buffer by lip-sync engine.
/// </summary>
/// <returns>error code</returns>
/// <param name="context">Context.</param>
/// <param name="audioBuffer"> PCM audio buffer.</param>
/// <param name="frame">Lip-sync Frame.</param>
/// <param name="stereo">Whether buffer is part of stereo or mono stream.</param>
public static Result ProcessFrame(
uint context, float[] audioBuffer, Frame frame, bool stereo = true)
{
if (IsInitialized() != Result.Success)
return Result.Unknown;
var dataType = stereo ? AudioDataType.F32_Stereo : AudioDataType.F32_Mono;
var numSamples = (uint)(stereo ? audioBuffer.Length / 2 : audioBuffer.Length);
var handle = GCHandle.Alloc(audioBuffer, GCHandleType.Pinned);
var rc = ovrLipSyncDll_ProcessFrameEx(context,
handle.AddrOfPinnedObject(), numSamples, dataType,
ref frame.frameNumber, ref frame.frameDelay,
frame.Visemes, frame.Visemes.Length,
ref frame.laughterScore,
null, 0
);
handle.Free();
return (Result)rc;
}
/// <summary>
/// Process short[] audio buffer by lip-sync engine.
/// </summary>
/// <returns>error code</returns>
/// <param name="context">Context.</param>
/// <param name="audioBuffer"> PCM audio buffer.</param>
/// <param name="frame">Lip-sync Frame.</param>
/// <param name="stereo">Whether buffer is part of stereo or mono stream.</param>
public static Result ProcessFrame(
uint context, short[] audioBuffer, Frame frame, bool stereo = true)
{
if (IsInitialized() != Result.Success)
return Result.Unknown;
var dataType = stereo ? AudioDataType.S16_Stereo : AudioDataType.S16_Mono;
var numSamples = (uint)(stereo ? audioBuffer.Length / 2 : audioBuffer.Length);
var handle = GCHandle.Alloc(audioBuffer, GCHandleType.Pinned);
var rc = ovrLipSyncDll_ProcessFrameEx(context,
handle.AddrOfPinnedObject(), numSamples, dataType,
ref frame.frameNumber, ref frame.frameDelay,
frame.Visemes, frame.Visemes.Length,
ref frame.laughterScore,
null, 0
);
handle.Free();
return (Result)rc;
}
}
| |
// 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.Linq;
using System.Reflection;
using System.Linq.Expressions;
using System.Diagnostics;
using System.Composition.Debugging;
using System.Composition.TypedParts.ActivationFeatures;
using System.Composition.Hosting.Core;
using System.Composition.Convention;
using System.Composition.Hosting;
namespace System.Composition.TypedParts.Discovery
{
[DebuggerDisplay("{PartType.Name}")]
[DebuggerTypeProxy(typeof(DiscoveredPartDebuggerProxy))]
internal class DiscoveredPart
{
private readonly TypeInfo _partType;
private readonly AttributedModelProvider _attributeContext;
private readonly ICollection<DiscoveredExport> _exports = new List<DiscoveredExport>();
private readonly ActivationFeature[] _activationFeatures;
private readonly Lazy<IDictionary<string, object>> _partMetadata;
// This is unbounded so potentially a source of memory consumption,
// but in reality unlikely to be a problem.
private readonly IList<Type[]> _appliedArguments = new List<Type[]>();
// Lazyily initialised among potentially many exports
private ConstructorInfo _constructor;
private CompositeActivator _partActivator;
private static readonly IDictionary<string, object> s_noMetadata = new Dictionary<string, object>();
private static readonly MethodInfo s_activatorInvoke = typeof(CompositeActivator).GetTypeInfo().GetDeclaredMethod("Invoke");
private DiscoveredPart(
TypeInfo partType,
AttributedModelProvider attributeContext,
ActivationFeature[] activationFeatures,
Lazy<IDictionary<string, object>> partMetadata)
{
_partType = partType;
_attributeContext = attributeContext;
_activationFeatures = activationFeatures;
_partMetadata = partMetadata;
}
public DiscoveredPart(
TypeInfo partType,
AttributedModelProvider attributeContext,
ActivationFeature[] activationFeatures)
{
_partType = partType;
_attributeContext = attributeContext;
_activationFeatures = activationFeatures;
_partMetadata = new Lazy<IDictionary<string, object>>(() => GetPartMetadata(partType));
}
public TypeInfo PartType { get { return _partType; } }
public bool IsShared { get { return ContractHelpers.IsShared(_partMetadata.Value); } }
public void AddDiscoveredExport(DiscoveredExport export)
{
_exports.Add(export);
export.Part = this;
}
public CompositionDependency[] GetDependencies(DependencyAccessor definitionAccessor)
{
return GetPartActivatorDependencies(definitionAccessor)
.Concat(_activationFeatures
.SelectMany(feature => feature.GetDependencies(_partType, definitionAccessor)))
.Where(a => a != null)
.ToArray();
}
private IEnumerable<CompositionDependency> GetPartActivatorDependencies(DependencyAccessor definitionAccessor)
{
var partTypeAsType = _partType.AsType();
if (_constructor == null)
{
foreach (var c in _partType.DeclaredConstructors.Where(ci => ci.IsPublic && !(ci.IsStatic)))
{
if (_attributeContext.GetDeclaredAttribute<ImportingConstructorAttribute>(partTypeAsType, c) != null)
{
if (_constructor != null)
{
var message = string.Format(Properties.Resources.DiscoveredPart_MultipleImportingConstructorsFound, _partType);
throw new CompositionFailedException(message);
}
_constructor = c;
}
}
if (_constructor == null)
_constructor = _partType.DeclaredConstructors
.FirstOrDefault(ci => ci.IsPublic && !(ci.IsStatic || ci.GetParameters().Any()));
if (_constructor == null)
{
var message = string.Format(Properties.Resources.DiscoveredPart_NoImportingConstructorsFound, _partType);
throw new CompositionFailedException(message);
}
}
var cps = _constructor.GetParameters();
for (var i = 0; i < cps.Length; ++i)
{
var pi = cps[i];
var site = new ParameterImportSite(pi);
var importInfo = ContractHelpers.GetImportInfo(pi.ParameterType, _attributeContext.GetDeclaredAttributes(partTypeAsType, pi), site);
if (!importInfo.AllowDefault)
{
yield return definitionAccessor.ResolveRequiredDependency(site, importInfo.Contract, true);
}
else
{
CompositionDependency optional;
if (definitionAccessor.TryResolveOptionalDependency(site, importInfo.Contract, true, out optional))
yield return optional;
}
}
}
public CompositeActivator GetActivator(DependencyAccessor definitionAccessor, IEnumerable<CompositionDependency> dependencies)
{
if (_partActivator != null) return _partActivator;
var contextParam = Expression.Parameter(typeof(LifetimeContext), "cc");
var operationParm = Expression.Parameter(typeof(CompositionOperation), "op");
var cps = _constructor.GetParameters();
Expression[] paramActivatorCalls = new Expression[cps.Length];
var partActivatorDependencies = dependencies
.Where(dep => dep.Site is ParameterImportSite)
.ToDictionary(d => ((ParameterImportSite)d.Site).Parameter);
for (var i = 0; i < cps.Length; ++i)
{
var pi = cps[i];
CompositionDependency dep;
if (partActivatorDependencies.TryGetValue(pi, out dep))
{
var a = dep.Target.GetDescriptor().Activator;
paramActivatorCalls[i] =
Expression.Convert(Expression.Call(Expression.Constant(a), s_activatorInvoke, contextParam, operationParm), pi.ParameterType);
}
else
{
paramActivatorCalls[i] = Expression.Default(pi.ParameterType);
}
}
Expression body = Expression.Convert(Expression.New(_constructor, paramActivatorCalls), typeof(object));
var activator = Expression
.Lambda<CompositeActivator>(body, contextParam, operationParm)
.Compile();
foreach (var activationFeature in _activationFeatures)
activator = activationFeature.RewriteActivator(_partType, activator, _partMetadata.Value, dependencies);
_partActivator = activator;
return _partActivator;
}
public IDictionary<string, object> GetPartMetadata(TypeInfo partType)
{
var partMetadata = new Dictionary<string, object>();
foreach (var attr in _attributeContext.GetDeclaredAttributes(partType.AsType(), partType))
{
if (attr is PartMetadataAttribute)
{
var ma = (PartMetadataAttribute)attr;
partMetadata.Add(ma.Name, ma.Value);
}
}
return partMetadata.Count == 0 ? s_noMetadata : partMetadata;
}
public bool TryCloseGenericPart(Type[] typeArguments, out DiscoveredPart closed)
{
if (_appliedArguments.Any(args => Enumerable.SequenceEqual(args, typeArguments)))
{
closed = null;
return false;
}
_appliedArguments.Add(typeArguments);
var closedType = _partType.MakeGenericType(typeArguments).GetTypeInfo();
var result = new DiscoveredPart(closedType, _attributeContext, _activationFeatures, _partMetadata);
foreach (var export in _exports)
{
var closedExport = export.CloseGenericExport(closedType, typeArguments);
result.AddDiscoveredExport(closedExport);
}
closed = result;
return true;
}
public IEnumerable<DiscoveredExport> DiscoveredExports { get { return _exports; } }
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=WindowsEditBox.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: HWND-based Edit Box proxy
//
// History:
// 01/10/03 : a-jeanp - created
// 08/12/03: alexsn - bug fixes
// 03/02/04: a-davidj - added text pattern
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using System.Windows.Automation.Text;
using MS.Win32;
using NativeMethodsSetLastError = MS.Internal.UIAutomationClientSideProviders.NativeMethodsSetLastError;
namespace MS.Internal.AutomationProxies
{
// TERMINOLOGY: Win32 Edit controls use the term "index" to mean a character position.
// For example the EM_LINEINDEX message converts a line number to it's starting character position.
// Perhaps not the best choice but we use it to be consistent.
class WindowsEditBox : ProxyHwnd, IValueProvider, ITextProvider
{
// ------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// This is the default contructor that calls the base class constructor.
// This function determines the type of the edit control and then calls the default constructor.
internal WindowsEditBox (IntPtr hwnd, ProxyFragment parent, int item)
: base( hwnd, parent, item)
{
_type = GetEditboxtype (hwnd);
if (IsMultiline)
{
_cControlType = ControlType.Document;
}
else
{
_cControlType = ControlType.Edit;
}
// When embedded inside of the combobox, hide the edit portion in the content element tree
_fIsContent = !IsInsideOfCombo();
_fIsKeyboardFocusable = true;
if (IsInsideOfListView(hwnd))
{
_sAutomationId = "edit";
}
// support for events
_createOnEvent = new WinEventTracker.ProxyRaiseEvents (RaiseEvents);
}
#endregion
#region Proxy Create
// Static Create method called by UIAutomation to create this proxy.
// <returns null if unsuccessful
internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild, int idObject)
{
return Create(hwnd, idChild);
}
private static IRawElementProviderSimple Create(IntPtr hwnd, int idChild)
{
// @
if (idChild != 0)
{
System.Diagnostics.Debug.Assert (idChild == 0, "Invalid Child Id, idChild != 0");
throw new ArgumentOutOfRangeException("idChild", idChild, SR.Get(SRID.ShouldBeZero));
}
return new WindowsEditBox(hwnd, null, 0);
}
// Static Create method called by the event tracker system
internal static void RaiseEvents (IntPtr hwnd, int eventId, object idProp, int idObject, int idChild)
{
if (idObject != NativeMethods.OBJID_VSCROLL && idObject != NativeMethods.OBJID_HSCROLL)
{
ProxySimple el;
if (IsInsideOfIPAddress(hwnd))
{
el = new ByteEditBoxOverride(hwnd, idChild);
}
else
{
el = new WindowsEditBox(hwnd, null, 0);
// If this is an Edit control inside of a [....] Spinner, need to treat the property
// changes for as property changes on the whole [....] Spinner, not on the element
// of the [....] Spinner. [....] Spinner raise WinEvents on the Edit portion of
// the spinner and not the UpDown portion like the Win32 Spinner.
IntPtr hwndParent = NativeMethodsSetLastError.GetAncestor(hwnd, NativeMethods.GA_PARENT);
if (hwndParent != IntPtr.Zero)
{
// Test for spinner - Create checks if the element is a spinner
ProxySimple spinner = (ProxySimple)WinformsSpinner.Create(hwndParent, 0);
if (spinner != null)
{
el = spinner;
}
}
}
el.DispatchEvents (eventId, idProp, idObject, idChild);
}
}
#endregion
//------------------------------------------------------
//
// Patterns Implementation
//
//------------------------------------------------------
#region ProxySimple Interface
internal override string GetAccessKey()
{
string accessKey = base.GetAccessKey();
if ((bool)GetElementProperty(AutomationElement.IsKeyboardFocusableProperty))
{
// Walk up the parent hwnd chain to find the associated label,
// e.g. for the case of an edit box in a writable combo box.
// The hwnd tree in this case may look like:
// - Dialog
// |- ComboBoxEx32 (optional)
// |- ComboBox
// |- Edit
// So we may need to walk up several levels.
// Although this loop isn't really confined to a window hierarchy
// of exactly the type shown above, in practice there are no realistic
// situations where this will do any harm. If this is shown to be
// a problem at some point, we will have to constrain the loop to
// parent hwnd's of type ComboBox or ComboBoxEx32.
for (IntPtr hwnd = _hwnd;
hwnd != IntPtr.Zero && string.IsNullOrEmpty(accessKey);
hwnd = Misc.GetParent(hwnd))
{
accessKey = GetLabelAccessKey(hwnd);
}
}
return accessKey;
}
// Returns a pattern interface if supported.
internal override object GetPatternProvider(AutomationPattern iid)
{
if (IsInsideOfIPAddress(_hwnd))
{
// ByteEditBoxOverride will service this call.
return null;
}
else if (iid == ValuePattern.Pattern && !IsMultiline)
{
return this;
}
// text pattern is supported for non-password boxes
else if (iid == TextPattern.Pattern && _type != EditboxType.Password)
{
return this;
}
return null;
}
// Process all the Logical and Raw Element Properties
internal override object GetElementProperty(AutomationProperty idProp)
{
if (idProp == AutomationElement.IsControlElementProperty)
{
// When embedded inside of the spinner, hide edit portion in the logical tree
if (IsInsideOfSpinner())
{
return false;
}
}
else if (idProp == AutomationElement.IsPasswordProperty)
{
return _type == EditboxType.Password;
}
else if (idProp == AutomationElement.NameProperty)
{
// Per ControlType.Edit spec if there is no static text
// label for an Edit then it must NEVER return the contents
// of the edit as the Name property. This relies on the
// default ProxyHwnd impl looking for a label for Name and
// not using WM_GETTEXT on the edit hwnd.
string name = base.GetElementProperty(idProp) as string;
if (string.IsNullOrEmpty(name))
{
// Stop UIA from asking other providers
return AutomationElement.NotSupported;
}
return name;
}
return base.GetElementProperty(idProp);
}
internal override ProxySimple ElementProviderFromPoint(int x, int y)
{
IntPtr hwndUpDown = WindowsSpinner.GetUpDownFromEdit(_hwnd);
if (hwndUpDown != IntPtr.Zero)
{
return new WindowsSpinner(hwndUpDown, _hwnd, _parent, _item);
}
return base.ElementProviderFromPoint(x, y);
}
internal override ProxySimple GetFocus()
{
IntPtr hwndUpDown = WindowsSpinner.GetUpDownFromEdit(_hwnd);
if (hwndUpDown != IntPtr.Zero)
{
return new WindowsSpinner(hwndUpDown, _hwnd, _parent, _item);
}
return base.GetFocus();
}
internal override ProxySimple GetParent()
{
IntPtr hwndUpDown = WindowsSpinner.GetUpDownFromEdit(_hwnd);
if (hwndUpDown != IntPtr.Zero)
{
return new WindowsSpinner(hwndUpDown, _hwnd, _parent, _item);
}
return base.GetParent();
}
#endregion ProxySimple Interface
#region ProxyHwnd Overrides
// Builds a list of Win32 WinEvents to process a UIAutomation Event.
protected override WinEventTracker.EvtIdProperty[] EventToWinEvent(AutomationEvent idEvent, out int cEvent)
{
// Once the shell team implements the WinEvent EVENT_OBJECT_TEXTSELECTIONCHANGED,
// we will start to see 2 events fired when the text selection changes.
// At that point, uncomment the code below so that
// TextPattern.TextSelectionChanged will only fire on Vista
// in response to NativeMethods.EventObjectTextSelectionChanged,
// but not in response to NativeMethods.EventObjectLocationChange.
/*
// For Vista, we only need register for EventObjectTextSelectionChanged to handle
// TextPattern.TextSelectionChangedEvent.
// For XP, we rely on EventObjectLocationChange, handled in ProxyHwnd.EventToWinEvent().
if (idEvent == TextPattern.TextSelectionChangedEvent && Environment.OSVersion.Version.Major >= 6)
{
cEvent = 1;
return new WinEventTracker.EvtIdProperty[] {
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectTextSelectionChanged, idEvent)
};
}
*/
return base.EventToWinEvent(idEvent, out cEvent);
}
#endregion
#region Value Pattern
// Sets the text of the edit.
void IValueProvider.SetValue (string str)
{
// Ensure that the edit box and all its parents are enabled.
Misc.CheckEnabled(_hwnd);
int styles = WindowStyle;
if (Misc.IsBitSet(styles, NativeMethods.ES_READONLY))
{
throw new InvalidOperationException(SR.Get(SRID.ValueReadonly));
}
// check if control only accepts numbers
if (Misc.IsBitSet(styles, NativeMethods.ES_NUMBER))
{
// check if string contains any non-numeric characters.
foreach (char ch in str)
{
if (char.IsLetter (ch))
{
throw new ArgumentException(SR.Get(SRID.NotAValidValue, str), "val");
}
}
}
// bug# 11147, Text/edit box should not enter more characters than what is allowed through keyboard.
// Determine the max number of chars this editbox accepts
int result = Misc.ProxySendMessageInt(_hwnd, NativeMethods.EM_GETLIMITTEXT, IntPtr.Zero, IntPtr.Zero);
// A result of -1 means that no limit is set.
if (result != -1 && result < str.Length)
{
throw new InvalidOperationException (SR.Get(SRID.OperationCannotBePerformed));
}
// Send the message...
result = Misc.ProxySendMessageInt(_hwnd, NativeMethods.WM_SETTEXT, IntPtr.Zero, new StringBuilder(str));
if (result != 1)
{
throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed));
}
}
// Request to get the value that this UI element is representing as a string
string IValueProvider.Value
{
get
{
return GetValue();
}
}
bool IValueProvider.IsReadOnly
{
get
{
return IsReadOnly();
}
}
#endregion
#region Text Pattern Methods
ITextRangeProvider [] ITextProvider.GetSelection()
{
int start, end;
GetSel(out start, out end);
return new ITextRangeProvider[] { new WindowsEditBoxRange(this, start, end) };
}
ITextRangeProvider [] ITextProvider.GetVisibleRanges()
{
int start, end;
GetVisibleRangePoints(out start, out end);
return new ITextRangeProvider[] { new WindowsEditBoxRange(this, start, end) };
}
ITextRangeProvider ITextProvider.RangeFromChild(IRawElementProviderSimple childElement)
{
// we don't have any children so this call must be in error.
throw new InvalidOperationException(SR.Get(SRID.EditControlsHaveNoChildren,GetType().FullName));
}
ITextRangeProvider ITextProvider.RangeFromPoint(Point screenLocation)
{
// convert screen to client coordinates.
// (Essentially ScreenToClient but MapWindowPoints accounts for window mirroring using WS_EX_LAYOUTRTL.)
NativeMethods.Win32Point clientLocation = (NativeMethods.Win32Point)screenLocation;
if (!Misc.MapWindowPoints(IntPtr.Zero, WindowHandle, ref clientLocation, 1))
{
return null;
}
// we have to deal with the possibility that the coordinate is inside the window rect
// but outside the client rect. in that case we just scoot it over so it is at the nearest
// point in the client rect.
NativeMethods.Win32Rect clientRect = new NativeMethods.Win32Rect();
if (!Misc.GetClientRect(WindowHandle, ref clientRect))
{
return null;
}
clientLocation.x = Math.Max(clientLocation.x, clientRect.left);
clientLocation.x = Math.Min(clientLocation.x, clientRect.right);
clientLocation.y = Math.Max(clientLocation.y, clientRect.top);
clientLocation.y = Math.Min(clientLocation.y, clientRect.bottom);
// get the character at those client coordinates
int start = CharFromPosEx(clientLocation);
return new WindowsEditBoxRange(this, start, start);
}
#endregion TextPattern Methods
#region TextPattern Properties
ITextRangeProvider ITextProvider.DocumentRange
{
get
{
return new WindowsEditBoxRange(this, 0, GetTextLength());
}
}
// THESE PROPERTIES ARE REMOVED IN 8.2 BREAKING CHANGE.
//
SupportedTextSelection ITextProvider.SupportedTextSelection
{
get
{
return SupportedTextSelection.Single;
}
}
#endregion Text Properties
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
internal bool IsMultiline
{
get
{
return _type == EditboxType.Multiline;
}
}
internal bool IsScrollable
{
get
{
return _type == EditboxType.Scrollable;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// send an EM_CHARPOS message with an (x,y) coordinate in lParam and
// report the returned character index and line number.
// IMPORTANT: the character index and line number are each 16-bit (half of the lResult).
// the high-order word is zero.
internal void CharFromPos(NativeMethods.Win32Point point, out ushort indexLowWord, out ushort lineLowWord)
{
Debug.Assert(point.x >= 0 && point.x < 65536, "WindowsEditBox.CharFromPos() x coordinate out of range.");
Debug.Assert(point.y >= 0 && point.y < 65536, "WindowsEditBox.CharFromPos() y coordinate out of range.");
// ask edit control for line number and character offset at client coordinates.
// low order word of return value is the character position.
// high order word is the zero-based line index.
IntPtr lParam = NativeMethods.Util.MAKELPARAM(point.x, point.y);
int result = Misc.ProxySendMessageInt(WindowHandle, NativeMethods.EM_CHARFROMPOS, IntPtr.Zero, lParam);
indexLowWord = unchecked((ushort)(NativeMethods.Util.LOWORD(result)));
lineLowWord = unchecked((ushort)(NativeMethods.Util.HIWORD(result)));
}
// an improvement on EM_CHARFROMPOS that handles edit controls with content greater than 65535 characters.
internal int CharFromPosEx(NativeMethods.Win32Point point)
{
// get the low words of the character position and line number at the coordinate.
ushort indexLowWord, lineLowWord;
CharFromPos(point, out indexLowWord, out lineLowWord);
// we handle multi-line edit controls differently than single line edit controls.
int index;
if (IsMultiline)
{
// note: an optimization would be to call GetTextLength and do the following only if the length is
// greater than 65535.
// to make the line number accurate in the case there are more than 65535 lines we get a 32-bit line number
// for the first visible line then use it to figure out the high-order word of our line number.
// this assumes that there aren't more than 65535 visible lines in the window, which is a
// pretty safe assumption.
int line = IntFromLowWord(lineLowWord, GetFirstVisibleLine());
// to make the character position accurate in case there are more than 65535 characters we use our line number to
// get the character position of the beginning of that line and use it to figure out the high-order word
// of our character position.
// this assumes that there aren't more than 65535 characters on the line before our target character,
// which is a pretty safe assumption.
index = IntFromLowWord(indexLowWord, LineIndex(line));
}
else
{
// single-line edit control
// to make the character position accurate in case there are more than 65535 characters we get a 32-bit
// character position from the first visible character, then use it to figure out the high-order word
// of our character position.
// this assumes that there aren't more than 65535 visible characters in the window,
// which is a pretty safe assumption.
index = IntFromLowWord(indexLowWord, GetFirstVisibleChar());
}
return index;
}
// Retrive edit box type
internal static EditboxType GetEditboxtype (IntPtr hwnd)
{
int style = Misc.GetWindowStyle(hwnd);
EditboxType type = EditboxType.Editbox;
if (Misc.IsBitSet(style, NativeMethods.ES_PASSWORD))
{
type = EditboxType.Password;
}
else if (Misc.IsBitSet(style, NativeMethods.ES_MULTILINE))
{
type = EditboxType.Multiline;
}
else if (Misc.IsBitSet(style, NativeMethods.ES_AUTOHSCROLL))
{
type = EditboxType.Scrollable;
}
return type;
}
// send an EM_GETFIRSTVISIBLELINE message to a single-line edit box to get the first visible character.
internal int GetFirstVisibleChar()
{
Debug.Assert(!IsMultiline);
return Misc.ProxySendMessageInt(WindowHandle, NativeMethods.EM_GETFIRSTVISIBLELINE, IntPtr.Zero, IntPtr.Zero);
}
// send an EM_GETFIRSTVISIBLELINE message to a multi-line edit box to get the first visible line.
internal int GetFirstVisibleLine()
{
Debug.Assert(IsMultiline);
return Misc.ProxySendMessageInt(WindowHandle, NativeMethods.EM_GETFIRSTVISIBLELINE, IntPtr.Zero, IntPtr.Zero);
}
// send a WM_GETFONT message to find out what font the edit control is using.
internal IntPtr GetFont()
{
IntPtr result = Misc.ProxySendMessage(WindowHandle, NativeMethods.WM_GETFONT, IntPtr.Zero, IntPtr.Zero);
//
// A null result is within normal bounds, as per the WM_GETFONT documentation:
// The return value is a handle to the font used by the control, or NULL if the control is using the system font.
//
if (result == IntPtr.Zero)
{
result = UnsafeNativeMethods.GetStockObject(NativeMethods.SYSTEM_FONT);
}
return result;
}
// send an EM_GETLINECOUNT message to find out how many lines are in the edit box.
internal int GetLineCount()
{
return Misc.ProxySendMessageInt(WindowHandle, NativeMethods.EM_GETLINECOUNT, IntPtr.Zero, IntPtr.Zero);
}
internal NativeMethods.LOGFONT GetLogfont()
{
IntPtr hfont = GetFont();
Debug.Assert(hfont != IntPtr.Zero, "WindowsEditBox.GetLogfont got null HFONT");
NativeMethods.LOGFONT logfont = new NativeMethods.LOGFONT();
int cb = Marshal.SizeOf(typeof(NativeMethods.LOGFONT));
if (Misc.GetObjectW(hfont, cb, ref logfont) != cb)
{
Debug.Assert(false, "WindowsEditBox.GetObject unexpected return value");
}
return logfont;
}
// send an EM_GETRECT message to find out the bounding rectangle
internal Rect GetRect()
{
NativeMethods.Win32Rect rect = new NativeMethods.Win32Rect();
Misc.ProxySendMessage(WindowHandle, NativeMethods.EM_GETRECT, IntPtr.Zero, ref rect);
return new Rect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
}
// send an EM_GETSEL message to get the starting and ending
// character positions of the selection.
internal void GetSel(out int start, out int end)
{
Misc.ProxySendMessage(WindowHandle, NativeMethods.EM_GETSEL, out start, out end);
}
// send a WM_GETTEXT message to get the text of the edit box.
internal string GetText()
{
return Misc.ProxyGetText(_hwnd, GetTextLength());
}
// send a WM_GETTEXTLENGTH to find out how long the text is in the edit box.
internal int GetTextLength()
{
return Misc.ProxySendMessageInt(WindowHandle, NativeMethods.WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
}
internal void GetVisibleRangePoints(out int start, out int end)
{
start = 0;
end = 0;
NativeMethods.Win32Rect rect = new NativeMethods.Win32Rect();
if (Misc.GetClientRect(_hwnd, ref rect) && !rect.IsEmpty)
{
NativeMethods.SIZE size;
string s = new string('E', 1);
GetTextExtentPoint32(s, out size);
NativeMethods.Win32Point ptStart = new NativeMethods.Win32Point((int)(rect.left + size.cx / 4), (int)(rect.top + size.cy / 4));
NativeMethods.Win32Point ptEnd = new NativeMethods.Win32Point((int)(rect.right - size.cx / 8), (int)(rect.bottom - size.cy / 4));
start = CharFromPosEx(ptStart);
end = CharFromPosEx(ptEnd);
if (start > 0)
{
Point pt = PosFromChar(start);
if (pt.X < rect.left)
{
start++;
}
}
}
else
{
// multi-line edit controls are handled differently than single-line edit controls.
if (IsMultiline)
{
// get the line number of the first visible line and start the range at
// the beginning of that line.
int firstLine = GetFirstVisibleLine();
start = LineIndex(firstLine);
// calculate the line number of the first line scrolled off the bottom and
// end the range at the beginning of that line.
end = LineIndex(firstLine + LinesPerPage());
}
else
{
// single-line edit control
// the problem is that using a variable-width font the number of characters visible
// depends on the text that is in the edit control. so we can't just divide the
// width of the edit control by the width of a character.
// so instead we do a binary search of the characters from the first visible character
// to the end of the text to find the visibility boundary.
Rect r = GetRect();
int limit = GetTextLength();
start = GetFirstVisibleChar();
int lo = start; // known visible
int hi = limit; // known non-visible
while (lo + 1 < hi)
{
int mid = (lo + hi) / 2;
Point pt = PosFromChar(mid);
if (pt.X >= r.Left && pt.X < r.Right)
{
lo = mid;
}
else
{
hi = mid;
}
}
// trim off one character unless the range is empty or reaches the end.
end = hi > start && hi < limit ? hi - 1 : hi;
}
}
}
// return true iff the user can modify the text in the edit control.
internal bool IsReadOnly()
{
return (!SafeNativeMethods.IsWindowEnabled(WindowHandle) || Misc.IsBitSet(WindowStyle, NativeMethods.ES_READONLY));
}
// send an EM_LINEFROMCHAR message to find out what line contains a character position.
internal int LineFromChar(int index)
{
Debug.Assert(index >= 0, "WindowsEditBox.LineFromChar negative index.");
Debug.Assert(index <= GetTextLength(), "WindowsEditBox.LineFromChar index out of range.");
// The return of EM_LINEFROMCHAR is the zero-based line number of the line containing the character index.
return Misc.ProxySendMessageInt(WindowHandle, NativeMethods.EM_LINEFROMCHAR, (IntPtr)index, IntPtr.Zero);
}
// send an EM_LINEINDEX message to get the character position at the start of a line.
internal int LineIndex(int line)
{
int index = Misc.ProxySendMessageInt(WindowHandle, NativeMethods.EM_LINEINDEX, (IntPtr)(line), IntPtr.Zero);
return index >=0 ? index : GetTextLength();
}
// send an EM_LINESCROLL message to scroll it horizontally and/or vertically
internal bool LineScroll(int charactersHorizontal, int linesVertical)
{
return 0 != Misc.ProxySendMessageInt(WindowHandle, NativeMethods.EM_LINESCROLL, (IntPtr)charactersHorizontal, (IntPtr)linesVertical);
}
// determine the number of lines that are visible in the Edit control.
// if there is no scrollbar then this is the actual number of lines displayed.
internal int LinesPerPage()
{
int linePerPage = 0;
if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_VSCROLL))
{
// we call GetScrollInfo and return the size of the "page"
NativeMethods.ScrollInfo si = new NativeMethods.ScrollInfo();
si.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(NativeMethods.ScrollInfo));
si.fMask = NativeMethods.SIF_ALL;
bool ok = Misc.GetScrollInfo(WindowHandle, NativeMethods.SB_VERT, ref si);
linePerPage = ok ? si.nPage : 0;
if (IsMultiline && linePerPage <= 0)
{
linePerPage = 1;
}
}
else
{
NativeMethods.Win32Rect rect = new NativeMethods.Win32Rect();
if (Misc.GetClientRect(_hwnd, ref rect) && !rect.IsEmpty)
{
NativeMethods.SIZE size;
string s = new string('E', 1);
GetTextExtentPoint32(s, out size);
if (size.cy != 0)
{
linePerPage = (rect.bottom - rect.top) / size.cy;
}
}
}
return linePerPage;
}
// send an EM_POSFROMCHAR message to find out the (x,y) position of a character.
// note: this assumes that the x and y coordinates will not be greater than 65535.
internal Point PosFromChar(int index)
{
Debug.Assert(index >= 0, "WindowsEditBox.PosFromChar negative index.");
Debug.Assert(index < GetTextLength(), "WindowsEditBox.PosFromChar index out of range.");
int result = Misc.ProxySendMessageInt(WindowHandle, NativeMethods.EM_POSFROMCHAR, (IntPtr)index, IntPtr.Zero);
Debug.Assert(result!=-1, "WindowsEditBox.PosFromChar index out of bounds.");
// A returned coordinate can be a negative value if the specified character is not displayed in the
// edit control's client area. So do not loose the sign.
int x = (int)((short)NativeMethods.Util.LOWORD(result));
int y = (int)((short)NativeMethods.Util.HIWORD(result));
return new Point(x, y);
}
// a variation on EM_POSFROMCHAR that returns the upper-right corner instead of upper-left.
internal Point PosFromCharUR(int index, string text)
{
// get the upper-left of the character
Point pt;
char ch = text[index];
switch(ch)
{
case '\n':
case '\r':
// get the UL corner of the character and return it since these characters have no width.
pt = PosFromChar(index);
break;
case '\t':
{
// for tabs the calculated width of the character is no help so we use the
// UL corner of the following character if it is on the same line.
bool useNext = index<GetTextLength()-1 && LineFromChar(index+1)==LineFromChar(index);
pt = PosFromChar(useNext ? index+1 : index);
}
break;
default:
{
// get the UL corner of the character
pt = PosFromChar(index);
// add the width of the character at that position.
NativeMethods.SIZE size;
string s = new string(ch, 1);
if( GetTextExtentPoint32(s, out size) == 0)
{
break;
}
pt.X += size.cx;
}
break;
}
return pt;
}
// send an EM_SETSEL message to set the selection.
internal void SetSel(int start, int end)
{
Debug.Assert(start >= 0, "WindowsEditBox.SetSel negative start.");
Debug.Assert(start <= GetTextLength(), "WindowsEditBox.SetSel start out of range.");
Debug.Assert(end >= 0, "WindowsEditBox.SetSel negative end.");
Debug.Assert(end <= GetTextLength(), "WindowsEditBox.SetSel end out of range.");
Misc.ProxySendMessage(WindowHandle, NativeMethods.EM_SETSEL, (IntPtr)start, (IntPtr)end);
}
// Retrieves text associated with EditBox control.
// this differs from GetText(), above, in that it limits the text to 2000 characters.
// it is used by the Value pattern methods, not the Text pattern methods.
internal static string Text(IntPtr hwnd)
{
return Misc.ProxyGetText(hwnd);
}
#endregion
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
// Different styles of edit boxes.
internal enum EditboxType
{
Editbox,
Multiline,
Password,
Readonly,
Scrollable
};
#endregion
// ------------------------------------------------------
//
// Private Methods
//
// ------------------------------------------------------
#region Private methods
private int GetTextExtentPoint32(string text, out NativeMethods.SIZE size)
{
size.cx = 0;
size.cy = 0;
// add the width of the character at that position.
// note: if any of these can throw an exception then we should use a finally clause
// to ensure the DC is released.
IntPtr hdc = Misc.GetDC(_hwnd);
if (hdc == IntPtr.Zero)
{
return 0;
}
IntPtr oldFont = IntPtr.Zero;
try
{
IntPtr hfont = GetFont();
oldFont = Misc.SelectObject(hdc, hfont);
return Misc.GetTextExtentPoint32(hdc, text, text.Length, out size);
}
finally
{
if (oldFont != IntPtr.Zero)
{
Misc.SelectObject(hdc, oldFont);
}
Misc.ReleaseDC(_hwnd, hdc);
}
}
private string GetValue()
{
if (_type == EditboxType.Password)
{
// Trying to retrieve the text (through WM_GETTEXT) from an edit box that has
// the ES_PASSWORD style throws an InvalidOperationException.
throw new InvalidOperationException();
}
return Text(_hwnd);
}
private bool IsInsideOfCombo()
{
IntPtr hwndParent = NativeMethodsSetLastError.GetAncestor(_hwnd, NativeMethods.GA_PARENT);
if (hwndParent == IntPtr.Zero)
{
return false;
}
// Test for combo
NativeMethods.COMBOBOXINFO cbInfo = new NativeMethods.COMBOBOXINFO(NativeMethods.comboboxInfoSize);
if (WindowsComboBox.GetComboInfo(hwndParent, ref cbInfo) && cbInfo.hwndItem == _hwnd)
{
return true;
}
return false;
}
private bool IsInsideOfSpinner()
{
IntPtr hwndParent = NativeMethodsSetLastError.GetAncestor(_hwnd, NativeMethods.GA_PARENT);
if (hwndParent != IntPtr.Zero)
{
// Test for spinner - Create checks if the element is a spinner
if (WinformsSpinner.Create(hwndParent, 0) != null)
{
return true;
}
}
return WindowsSpinner.IsSpinnerEdit(_hwnd);
}
private static bool IsInsideOfIPAddress(IntPtr hwnd)
{
IntPtr hwndParent = NativeMethodsSetLastError.GetAncestor(hwnd, NativeMethods.GA_PARENT);
if (hwndParent != IntPtr.Zero)
{
string classname = Misc.GetClassName(hwndParent);
if (classname.Equals("SysIPAddress32"))
{
return true;
}
}
return false;
}
private static bool IsInsideOfListView(IntPtr hwnd)
{
IntPtr hwndParent = NativeMethodsSetLastError.GetAncestor(hwnd, NativeMethods.GA_PARENT);
if (hwndParent != IntPtr.Zero)
{
string classname = Misc.GetClassName(hwndParent);
if (classname.Equals("SysListView32"))
{
return true;
}
}
return false;
}
// given the low-order word of a non-negative integer that is at most 0xffff greater than some floor integer
// we calculate what the original integer was.
private static int IntFromLowWord(ushort lowWord, int floor)
{
// get the high-word from our floor integer
Debug.Assert(floor >= 0);
short hiWord = (short)(floor >> 16);
// if our unknown integer has cross a 64k boundary from our floor integer
// then we need to increment the high-word
ushort floorLowWord = (ushort)(floor & 0xffff);
if (lowWord < floorLowWord)
hiWord++;
// combine the adjusted floor high-word with the known low-word to get our integer
int i = NativeMethods.Util.MAKELONG((int)lowWord, (int)hiWord);
Debug.Assert(i >= floor);
return i;
}
#endregion Private methods
// ------------------------------------------------------
//
// Private Fields
//
// ------------------------------------------------------
#region Private Fields
private EditboxType _type;
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Microedition.Khronos.Egl.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 Javax.Microedition.Khronos.Egl
{
/// <java-name>
/// javax/microedition/khronos/egl/EGLConfig
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGLConfig", AccessFlags = 1057)]
public abstract partial class EGLConfig
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public EGLConfig() /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL10
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IEGL10Constants
/* scope: __dot42__ */
{
/// <java-name>
/// EGL_SUCCESS
/// </java-name>
[Dot42.DexImport("EGL_SUCCESS", "I", AccessFlags = 25)]
public const int EGL_SUCCESS = 12288;
/// <java-name>
/// EGL_NOT_INITIALIZED
/// </java-name>
[Dot42.DexImport("EGL_NOT_INITIALIZED", "I", AccessFlags = 25)]
public const int EGL_NOT_INITIALIZED = 12289;
/// <java-name>
/// EGL_BAD_ACCESS
/// </java-name>
[Dot42.DexImport("EGL_BAD_ACCESS", "I", AccessFlags = 25)]
public const int EGL_BAD_ACCESS = 12290;
/// <java-name>
/// EGL_BAD_ALLOC
/// </java-name>
[Dot42.DexImport("EGL_BAD_ALLOC", "I", AccessFlags = 25)]
public const int EGL_BAD_ALLOC = 12291;
/// <java-name>
/// EGL_BAD_ATTRIBUTE
/// </java-name>
[Dot42.DexImport("EGL_BAD_ATTRIBUTE", "I", AccessFlags = 25)]
public const int EGL_BAD_ATTRIBUTE = 12292;
/// <java-name>
/// EGL_BAD_CONFIG
/// </java-name>
[Dot42.DexImport("EGL_BAD_CONFIG", "I", AccessFlags = 25)]
public const int EGL_BAD_CONFIG = 12293;
/// <java-name>
/// EGL_BAD_CONTEXT
/// </java-name>
[Dot42.DexImport("EGL_BAD_CONTEXT", "I", AccessFlags = 25)]
public const int EGL_BAD_CONTEXT = 12294;
/// <java-name>
/// EGL_BAD_CURRENT_SURFACE
/// </java-name>
[Dot42.DexImport("EGL_BAD_CURRENT_SURFACE", "I", AccessFlags = 25)]
public const int EGL_BAD_CURRENT_SURFACE = 12295;
/// <java-name>
/// EGL_BAD_DISPLAY
/// </java-name>
[Dot42.DexImport("EGL_BAD_DISPLAY", "I", AccessFlags = 25)]
public const int EGL_BAD_DISPLAY = 12296;
/// <java-name>
/// EGL_BAD_MATCH
/// </java-name>
[Dot42.DexImport("EGL_BAD_MATCH", "I", AccessFlags = 25)]
public const int EGL_BAD_MATCH = 12297;
/// <java-name>
/// EGL_BAD_NATIVE_PIXMAP
/// </java-name>
[Dot42.DexImport("EGL_BAD_NATIVE_PIXMAP", "I", AccessFlags = 25)]
public const int EGL_BAD_NATIVE_PIXMAP = 12298;
/// <java-name>
/// EGL_BAD_NATIVE_WINDOW
/// </java-name>
[Dot42.DexImport("EGL_BAD_NATIVE_WINDOW", "I", AccessFlags = 25)]
public const int EGL_BAD_NATIVE_WINDOW = 12299;
/// <java-name>
/// EGL_BAD_PARAMETER
/// </java-name>
[Dot42.DexImport("EGL_BAD_PARAMETER", "I", AccessFlags = 25)]
public const int EGL_BAD_PARAMETER = 12300;
/// <java-name>
/// EGL_BAD_SURFACE
/// </java-name>
[Dot42.DexImport("EGL_BAD_SURFACE", "I", AccessFlags = 25)]
public const int EGL_BAD_SURFACE = 12301;
/// <java-name>
/// EGL_BUFFER_SIZE
/// </java-name>
[Dot42.DexImport("EGL_BUFFER_SIZE", "I", AccessFlags = 25)]
public const int EGL_BUFFER_SIZE = 12320;
/// <java-name>
/// EGL_ALPHA_SIZE
/// </java-name>
[Dot42.DexImport("EGL_ALPHA_SIZE", "I", AccessFlags = 25)]
public const int EGL_ALPHA_SIZE = 12321;
/// <java-name>
/// EGL_BLUE_SIZE
/// </java-name>
[Dot42.DexImport("EGL_BLUE_SIZE", "I", AccessFlags = 25)]
public const int EGL_BLUE_SIZE = 12322;
/// <java-name>
/// EGL_GREEN_SIZE
/// </java-name>
[Dot42.DexImport("EGL_GREEN_SIZE", "I", AccessFlags = 25)]
public const int EGL_GREEN_SIZE = 12323;
/// <java-name>
/// EGL_RED_SIZE
/// </java-name>
[Dot42.DexImport("EGL_RED_SIZE", "I", AccessFlags = 25)]
public const int EGL_RED_SIZE = 12324;
/// <java-name>
/// EGL_DEPTH_SIZE
/// </java-name>
[Dot42.DexImport("EGL_DEPTH_SIZE", "I", AccessFlags = 25)]
public const int EGL_DEPTH_SIZE = 12325;
/// <java-name>
/// EGL_STENCIL_SIZE
/// </java-name>
[Dot42.DexImport("EGL_STENCIL_SIZE", "I", AccessFlags = 25)]
public const int EGL_STENCIL_SIZE = 12326;
/// <java-name>
/// EGL_CONFIG_CAVEAT
/// </java-name>
[Dot42.DexImport("EGL_CONFIG_CAVEAT", "I", AccessFlags = 25)]
public const int EGL_CONFIG_CAVEAT = 12327;
/// <java-name>
/// EGL_CONFIG_ID
/// </java-name>
[Dot42.DexImport("EGL_CONFIG_ID", "I", AccessFlags = 25)]
public const int EGL_CONFIG_ID = 12328;
/// <java-name>
/// EGL_LEVEL
/// </java-name>
[Dot42.DexImport("EGL_LEVEL", "I", AccessFlags = 25)]
public const int EGL_LEVEL = 12329;
/// <java-name>
/// EGL_MAX_PBUFFER_HEIGHT
/// </java-name>
[Dot42.DexImport("EGL_MAX_PBUFFER_HEIGHT", "I", AccessFlags = 25)]
public const int EGL_MAX_PBUFFER_HEIGHT = 12330;
/// <java-name>
/// EGL_MAX_PBUFFER_PIXELS
/// </java-name>
[Dot42.DexImport("EGL_MAX_PBUFFER_PIXELS", "I", AccessFlags = 25)]
public const int EGL_MAX_PBUFFER_PIXELS = 12331;
/// <java-name>
/// EGL_MAX_PBUFFER_WIDTH
/// </java-name>
[Dot42.DexImport("EGL_MAX_PBUFFER_WIDTH", "I", AccessFlags = 25)]
public const int EGL_MAX_PBUFFER_WIDTH = 12332;
/// <java-name>
/// EGL_NATIVE_RENDERABLE
/// </java-name>
[Dot42.DexImport("EGL_NATIVE_RENDERABLE", "I", AccessFlags = 25)]
public const int EGL_NATIVE_RENDERABLE = 12333;
/// <java-name>
/// EGL_NATIVE_VISUAL_ID
/// </java-name>
[Dot42.DexImport("EGL_NATIVE_VISUAL_ID", "I", AccessFlags = 25)]
public const int EGL_NATIVE_VISUAL_ID = 12334;
/// <java-name>
/// EGL_NATIVE_VISUAL_TYPE
/// </java-name>
[Dot42.DexImport("EGL_NATIVE_VISUAL_TYPE", "I", AccessFlags = 25)]
public const int EGL_NATIVE_VISUAL_TYPE = 12335;
/// <java-name>
/// EGL_SAMPLES
/// </java-name>
[Dot42.DexImport("EGL_SAMPLES", "I", AccessFlags = 25)]
public const int EGL_SAMPLES = 12337;
/// <java-name>
/// EGL_SAMPLE_BUFFERS
/// </java-name>
[Dot42.DexImport("EGL_SAMPLE_BUFFERS", "I", AccessFlags = 25)]
public const int EGL_SAMPLE_BUFFERS = 12338;
/// <java-name>
/// EGL_SURFACE_TYPE
/// </java-name>
[Dot42.DexImport("EGL_SURFACE_TYPE", "I", AccessFlags = 25)]
public const int EGL_SURFACE_TYPE = 12339;
/// <java-name>
/// EGL_TRANSPARENT_TYPE
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_TYPE", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_TYPE = 12340;
/// <java-name>
/// EGL_TRANSPARENT_BLUE_VALUE
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_BLUE_VALUE", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_BLUE_VALUE = 12341;
/// <java-name>
/// EGL_TRANSPARENT_GREEN_VALUE
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_GREEN_VALUE", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_GREEN_VALUE = 12342;
/// <java-name>
/// EGL_TRANSPARENT_RED_VALUE
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_RED_VALUE", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_RED_VALUE = 12343;
/// <java-name>
/// EGL_NONE
/// </java-name>
[Dot42.DexImport("EGL_NONE", "I", AccessFlags = 25)]
public const int EGL_NONE = 12344;
/// <java-name>
/// EGL_LUMINANCE_SIZE
/// </java-name>
[Dot42.DexImport("EGL_LUMINANCE_SIZE", "I", AccessFlags = 25)]
public const int EGL_LUMINANCE_SIZE = 12349;
/// <java-name>
/// EGL_ALPHA_MASK_SIZE
/// </java-name>
[Dot42.DexImport("EGL_ALPHA_MASK_SIZE", "I", AccessFlags = 25)]
public const int EGL_ALPHA_MASK_SIZE = 12350;
/// <java-name>
/// EGL_COLOR_BUFFER_TYPE
/// </java-name>
[Dot42.DexImport("EGL_COLOR_BUFFER_TYPE", "I", AccessFlags = 25)]
public const int EGL_COLOR_BUFFER_TYPE = 12351;
/// <java-name>
/// EGL_RENDERABLE_TYPE
/// </java-name>
[Dot42.DexImport("EGL_RENDERABLE_TYPE", "I", AccessFlags = 25)]
public const int EGL_RENDERABLE_TYPE = 12352;
/// <java-name>
/// EGL_SLOW_CONFIG
/// </java-name>
[Dot42.DexImport("EGL_SLOW_CONFIG", "I", AccessFlags = 25)]
public const int EGL_SLOW_CONFIG = 12368;
/// <java-name>
/// EGL_NON_CONFORMANT_CONFIG
/// </java-name>
[Dot42.DexImport("EGL_NON_CONFORMANT_CONFIG", "I", AccessFlags = 25)]
public const int EGL_NON_CONFORMANT_CONFIG = 12369;
/// <java-name>
/// EGL_TRANSPARENT_RGB
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_RGB", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_RGB = 12370;
/// <java-name>
/// EGL_RGB_BUFFER
/// </java-name>
[Dot42.DexImport("EGL_RGB_BUFFER", "I", AccessFlags = 25)]
public const int EGL_RGB_BUFFER = 12430;
/// <java-name>
/// EGL_LUMINANCE_BUFFER
/// </java-name>
[Dot42.DexImport("EGL_LUMINANCE_BUFFER", "I", AccessFlags = 25)]
public const int EGL_LUMINANCE_BUFFER = 12431;
/// <java-name>
/// EGL_VENDOR
/// </java-name>
[Dot42.DexImport("EGL_VENDOR", "I", AccessFlags = 25)]
public const int EGL_VENDOR = 12371;
/// <java-name>
/// EGL_VERSION
/// </java-name>
[Dot42.DexImport("EGL_VERSION", "I", AccessFlags = 25)]
public const int EGL_VERSION = 12372;
/// <java-name>
/// EGL_EXTENSIONS
/// </java-name>
[Dot42.DexImport("EGL_EXTENSIONS", "I", AccessFlags = 25)]
public const int EGL_EXTENSIONS = 12373;
/// <java-name>
/// EGL_HEIGHT
/// </java-name>
[Dot42.DexImport("EGL_HEIGHT", "I", AccessFlags = 25)]
public const int EGL_HEIGHT = 12374;
/// <java-name>
/// EGL_WIDTH
/// </java-name>
[Dot42.DexImport("EGL_WIDTH", "I", AccessFlags = 25)]
public const int EGL_WIDTH = 12375;
/// <java-name>
/// EGL_LARGEST_PBUFFER
/// </java-name>
[Dot42.DexImport("EGL_LARGEST_PBUFFER", "I", AccessFlags = 25)]
public const int EGL_LARGEST_PBUFFER = 12376;
/// <java-name>
/// EGL_RENDER_BUFFER
/// </java-name>
[Dot42.DexImport("EGL_RENDER_BUFFER", "I", AccessFlags = 25)]
public const int EGL_RENDER_BUFFER = 12422;
/// <java-name>
/// EGL_COLORSPACE
/// </java-name>
[Dot42.DexImport("EGL_COLORSPACE", "I", AccessFlags = 25)]
public const int EGL_COLORSPACE = 12423;
/// <java-name>
/// EGL_ALPHA_FORMAT
/// </java-name>
[Dot42.DexImport("EGL_ALPHA_FORMAT", "I", AccessFlags = 25)]
public const int EGL_ALPHA_FORMAT = 12424;
/// <java-name>
/// EGL_HORIZONTAL_RESOLUTION
/// </java-name>
[Dot42.DexImport("EGL_HORIZONTAL_RESOLUTION", "I", AccessFlags = 25)]
public const int EGL_HORIZONTAL_RESOLUTION = 12432;
/// <java-name>
/// EGL_VERTICAL_RESOLUTION
/// </java-name>
[Dot42.DexImport("EGL_VERTICAL_RESOLUTION", "I", AccessFlags = 25)]
public const int EGL_VERTICAL_RESOLUTION = 12433;
/// <java-name>
/// EGL_PIXEL_ASPECT_RATIO
/// </java-name>
[Dot42.DexImport("EGL_PIXEL_ASPECT_RATIO", "I", AccessFlags = 25)]
public const int EGL_PIXEL_ASPECT_RATIO = 12434;
/// <java-name>
/// EGL_SINGLE_BUFFER
/// </java-name>
[Dot42.DexImport("EGL_SINGLE_BUFFER", "I", AccessFlags = 25)]
public const int EGL_SINGLE_BUFFER = 12421;
/// <java-name>
/// EGL_CORE_NATIVE_ENGINE
/// </java-name>
[Dot42.DexImport("EGL_CORE_NATIVE_ENGINE", "I", AccessFlags = 25)]
public const int EGL_CORE_NATIVE_ENGINE = 12379;
/// <java-name>
/// EGL_DRAW
/// </java-name>
[Dot42.DexImport("EGL_DRAW", "I", AccessFlags = 25)]
public const int EGL_DRAW = 12377;
/// <java-name>
/// EGL_READ
/// </java-name>
[Dot42.DexImport("EGL_READ", "I", AccessFlags = 25)]
public const int EGL_READ = 12378;
/// <java-name>
/// EGL_DONT_CARE
/// </java-name>
[Dot42.DexImport("EGL_DONT_CARE", "I", AccessFlags = 25)]
public const int EGL_DONT_CARE = -1;
/// <java-name>
/// EGL_PBUFFER_BIT
/// </java-name>
[Dot42.DexImport("EGL_PBUFFER_BIT", "I", AccessFlags = 25)]
public const int EGL_PBUFFER_BIT = 1;
/// <java-name>
/// EGL_PIXMAP_BIT
/// </java-name>
[Dot42.DexImport("EGL_PIXMAP_BIT", "I", AccessFlags = 25)]
public const int EGL_PIXMAP_BIT = 2;
/// <java-name>
/// EGL_WINDOW_BIT
/// </java-name>
[Dot42.DexImport("EGL_WINDOW_BIT", "I", AccessFlags = 25)]
public const int EGL_WINDOW_BIT = 4;
/// <java-name>
/// EGL_DEFAULT_DISPLAY
/// </java-name>
[Dot42.DexImport("EGL_DEFAULT_DISPLAY", "Ljava/lang/Object;", AccessFlags = 25)]
public static readonly object EGL_DEFAULT_DISPLAY;
/// <java-name>
/// EGL_NO_DISPLAY
/// </java-name>
[Dot42.DexImport("EGL_NO_DISPLAY", "Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 25)]
public static readonly global::Javax.Microedition.Khronos.Egl.EGLDisplay EGL_NO_DISPLAY;
/// <java-name>
/// EGL_NO_CONTEXT
/// </java-name>
[Dot42.DexImport("EGL_NO_CONTEXT", "Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 25)]
public static readonly global::Javax.Microedition.Khronos.Egl.EGLContext EGL_NO_CONTEXT;
/// <java-name>
/// EGL_NO_SURFACE
/// </java-name>
[Dot42.DexImport("EGL_NO_SURFACE", "Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 25)]
public static readonly global::Javax.Microedition.Khronos.Egl.EGLSurface EGL_NO_SURFACE;
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL10
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537)]
public partial interface IEGL10 : global::Javax.Microedition.Khronos.Egl.IEGL
/* scope: __dot42__ */
{
/// <java-name>
/// eglChooseConfig
/// </java-name>
[Dot42.DexImport("eglChooseConfig", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I[Ljavax/microedition/khronos/egl/EG" +
"LConfig;I[I)Z", AccessFlags = 1025)]
bool EglChooseConfig(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] attrib_list, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCopyBuffers
/// </java-name>
[Dot42.DexImport("eglCopyBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;Ljava/lang/Object;)Z", AccessFlags = 1025)]
bool EglCopyBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, object native_pixmap) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCreateContext
/// </java-name>
[Dot42.DexImport("eglCreateContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;Ljavax/microedition/khronos/egl/EGLContext;[I)Ljavax/microedition/khronos/e" +
"gl/EGLContext;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLContext EglCreateContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, global::Javax.Microedition.Khronos.Egl.EGLContext share_context, int[] attrib_list) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCreatePbufferSurface
/// </java-name>
[Dot42.DexImport("eglCreatePbufferSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePbufferSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int[] attrib_list) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCreatePixmapSurface
/// </java-name>
[Dot42.DexImport("eglCreatePixmapSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePixmapSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_pixmap, int[] attrib_list) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCreateWindowSurface
/// </java-name>
[Dot42.DexImport("eglCreateWindowSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreateWindowSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_window, int[] attrib_list) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglDestroyContext
/// </java-name>
[Dot42.DexImport("eglDestroyContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"ntext;)Z", AccessFlags = 1025)]
bool EglDestroyContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglDestroySurface
/// </java-name>
[Dot42.DexImport("eglDestroySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;)Z", AccessFlags = 1025)]
bool EglDestroySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetConfigAttrib
/// </java-name>
[Dot42.DexImport("eglGetConfigAttrib", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;I[I)Z", AccessFlags = 1025)]
bool EglGetConfigAttrib(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int attribute, int[] value) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetConfigs
/// </java-name>
[Dot42.DexImport("eglGetConfigs", "(Ljavax/microedition/khronos/egl/EGLDisplay;[Ljavax/microedition/khronos/egl/EGLC" +
"onfig;I[I)Z", AccessFlags = 1025)]
bool EglGetConfigs(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetCurrentContext
/// </java-name>
[Dot42.DexImport("eglGetCurrentContext", "()Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLContext EglGetCurrentContext() /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetCurrentDisplay
/// </java-name>
[Dot42.DexImport("eglGetCurrentDisplay", "()Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetCurrentDisplay() /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetCurrentSurface
/// </java-name>
[Dot42.DexImport("eglGetCurrentSurface", "(I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLSurface EglGetCurrentSurface(int readdraw) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetDisplay
/// </java-name>
[Dot42.DexImport("eglGetDisplay", "(Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetDisplay(object native_display) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetError
/// </java-name>
[Dot42.DexImport("eglGetError", "()I", AccessFlags = 1025)]
int EglGetError() /* MethodBuilder.Create */ ;
/// <java-name>
/// eglInitialize
/// </java-name>
[Dot42.DexImport("eglInitialize", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I)Z", AccessFlags = 1025)]
bool EglInitialize(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] major_minor) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglMakeCurrent
/// </java-name>
[Dot42.DexImport("eglMakeCurrent", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;Ljavax/microedition/khronos/egl/EGLSurface;Ljavax/microedition/khronos/egl" +
"/EGLContext;)Z", AccessFlags = 1025)]
bool EglMakeCurrent(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface draw, global::Javax.Microedition.Khronos.Egl.EGLSurface read, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglQueryContext
/// </java-name>
[Dot42.DexImport("eglQueryContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"ntext;I[I)Z", AccessFlags = 1025)]
bool EglQueryContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context, int attribute, int[] value) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglQueryString
/// </java-name>
[Dot42.DexImport("eglQueryString", "(Ljavax/microedition/khronos/egl/EGLDisplay;I)Ljava/lang/String;", AccessFlags = 1025)]
string EglQueryString(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int name) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglQuerySurface
/// </java-name>
[Dot42.DexImport("eglQuerySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;I[I)Z", AccessFlags = 1025)]
bool EglQuerySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, int attribute, int[] value) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglSwapBuffers
/// </java-name>
[Dot42.DexImport("eglSwapBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;)Z", AccessFlags = 1025)]
bool EglSwapBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglTerminate
/// </java-name>
[Dot42.DexImport("eglTerminate", "(Ljavax/microedition/khronos/egl/EGLDisplay;)Z", AccessFlags = 1025)]
bool EglTerminate(global::Javax.Microedition.Khronos.Egl.EGLDisplay display) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglWaitGL
/// </java-name>
[Dot42.DexImport("eglWaitGL", "()Z", AccessFlags = 1025)]
bool EglWaitGL() /* MethodBuilder.Create */ ;
/// <java-name>
/// eglWaitNative
/// </java-name>
[Dot42.DexImport("eglWaitNative", "(ILjava/lang/Object;)Z", AccessFlags = 1025)]
bool EglWaitNative(int engine, object bindTarget) /* MethodBuilder.Create */ ;
}
/// <java-name>
/// javax/microedition/khronos/egl/EGLSurface
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGLSurface", AccessFlags = 1057)]
public abstract partial class EGLSurface
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public EGLSurface() /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL", AccessFlags = 1537)]
public partial interface IEGL
/* scope: __dot42__ */
{
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL11
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IEGL11Constants
/* scope: __dot42__ */
{
/// <java-name>
/// EGL_CONTEXT_LOST
/// </java-name>
[Dot42.DexImport("EGL_CONTEXT_LOST", "I", AccessFlags = 25)]
public const int EGL_CONTEXT_LOST = 12302;
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL11
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537)]
public partial interface IEGL11 : global::Javax.Microedition.Khronos.Egl.IEGL10
/* scope: __dot42__ */
{
}
/// <java-name>
/// javax/microedition/khronos/egl/EGLContext
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGLContext", AccessFlags = 1057)]
public abstract partial class EGLContext
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public EGLContext() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getEGL
/// </java-name>
[Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)]
public static global::Javax.Microedition.Khronos.Egl.IEGL GetEGL() /* MethodBuilder.Create */
{
return default(global::Javax.Microedition.Khronos.Egl.IEGL);
}
/// <java-name>
/// getGL
/// </java-name>
[Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)]
public abstract global::Javax.Microedition.Khronos.Opengles.IGL GetGL() /* MethodBuilder.Create */ ;
/// <java-name>
/// getEGL
/// </java-name>
public static global::Javax.Microedition.Khronos.Egl.IEGL EGL
{
[Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)]
get{ return GetEGL(); }
}
/// <java-name>
/// getGL
/// </java-name>
public global::Javax.Microedition.Khronos.Opengles.IGL GL
{
[Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)]
get{ return GetGL(); }
}
}
/// <java-name>
/// javax/microedition/khronos/egl/EGLDisplay
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGLDisplay", AccessFlags = 1057)]
public abstract partial class EGLDisplay
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public EGLDisplay() /* MethodBuilder.Create */
{
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// InventoryDetail
/// </summary>
[DataContract]
public partial class InventoryDetail : IEquatable<InventoryDetail>
{
/// <summary>
/// Initializes a new instance of the <see cref="InventoryDetail" /> class.
/// </summary>
[JsonConstructorAttribute]
protected InventoryDetail() { }
/// <summary>
/// Initializes a new instance of the <see cref="InventoryDetail" /> class.
/// </summary>
/// <param name="WarehouseLocationId">WarehouseLocationId (required).</param>
/// <param name="Sku">Sku.</param>
public InventoryDetail(int? WarehouseLocationId = null, string Sku = null)
{
// to ensure "WarehouseLocationId" is required (not null)
if (WarehouseLocationId == null)
{
throw new InvalidDataException("WarehouseLocationId is a required property for InventoryDetail and cannot be null");
}
else
{
this.WarehouseLocationId = WarehouseLocationId;
}
this.Sku = Sku;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets WarehouseLocationId
/// </summary>
[DataMember(Name="warehouseLocationId", EmitDefaultValue=false)]
public int? WarehouseLocationId { get; set; }
/// <summary>
/// Gets or Sets Quantity
/// </summary>
[DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; private set; }
/// <summary>
/// Gets or Sets DistributionDate
/// </summary>
[DataMember(Name="distributionDate", EmitDefaultValue=false)]
public DateTime? DistributionDate { get; private set; }
/// <summary>
/// Gets or Sets UnitsPerCase
/// </summary>
[DataMember(Name="unitsPerCase", EmitDefaultValue=false)]
public int? UnitsPerCase { get; private set; }
/// <summary>
/// Gets or Sets UnitsPerWrap
/// </summary>
[DataMember(Name="unitsPerWrap", EmitDefaultValue=false)]
public int? UnitsPerWrap { get; private set; }
/// <summary>
/// Gets or Sets RevisionDate
/// </summary>
[DataMember(Name="revisionDate", EmitDefaultValue=false)]
public string RevisionDate { get; private set; }
/// <summary>
/// Gets or Sets ProductionLot
/// </summary>
[DataMember(Name="productionLot", EmitDefaultValue=false)]
public string ProductionLot { get; private set; }
/// <summary>
/// Gets or Sets OldestReceiptDate
/// </summary>
[DataMember(Name="oldestReceiptDate", EmitDefaultValue=false)]
public DateTime? OldestReceiptDate { get; private set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; private set; }
/// <summary>
/// Gets or Sets PoNo
/// </summary>
[DataMember(Name="poNo", EmitDefaultValue=false)]
public string PoNo { get; private set; }
/// <summary>
/// Gets or Sets Sku
/// </summary>
[DataMember(Name="sku", EmitDefaultValue=false)]
public string Sku { 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 InventoryDetail {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" WarehouseLocationId: ").Append(WarehouseLocationId).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" DistributionDate: ").Append(DistributionDate).Append("\n");
sb.Append(" UnitsPerCase: ").Append(UnitsPerCase).Append("\n");
sb.Append(" UnitsPerWrap: ").Append(UnitsPerWrap).Append("\n");
sb.Append(" RevisionDate: ").Append(RevisionDate).Append("\n");
sb.Append(" ProductionLot: ").Append(ProductionLot).Append("\n");
sb.Append(" OldestReceiptDate: ").Append(OldestReceiptDate).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" PoNo: ").Append(PoNo).Append("\n");
sb.Append(" Sku: ").Append(Sku).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as InventoryDetail);
}
/// <summary>
/// Returns true if InventoryDetail instances are equal
/// </summary>
/// <param name="other">Instance of InventoryDetail to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InventoryDetail other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.WarehouseLocationId == other.WarehouseLocationId ||
this.WarehouseLocationId != null &&
this.WarehouseLocationId.Equals(other.WarehouseLocationId)
) &&
(
this.Quantity == other.Quantity ||
this.Quantity != null &&
this.Quantity.Equals(other.Quantity)
) &&
(
this.DistributionDate == other.DistributionDate ||
this.DistributionDate != null &&
this.DistributionDate.Equals(other.DistributionDate)
) &&
(
this.UnitsPerCase == other.UnitsPerCase ||
this.UnitsPerCase != null &&
this.UnitsPerCase.Equals(other.UnitsPerCase)
) &&
(
this.UnitsPerWrap == other.UnitsPerWrap ||
this.UnitsPerWrap != null &&
this.UnitsPerWrap.Equals(other.UnitsPerWrap)
) &&
(
this.RevisionDate == other.RevisionDate ||
this.RevisionDate != null &&
this.RevisionDate.Equals(other.RevisionDate)
) &&
(
this.ProductionLot == other.ProductionLot ||
this.ProductionLot != null &&
this.ProductionLot.Equals(other.ProductionLot)
) &&
(
this.OldestReceiptDate == other.OldestReceiptDate ||
this.OldestReceiptDate != null &&
this.OldestReceiptDate.Equals(other.OldestReceiptDate)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.PoNo == other.PoNo ||
this.PoNo != null &&
this.PoNo.Equals(other.PoNo)
) &&
(
this.Sku == other.Sku ||
this.Sku != null &&
this.Sku.Equals(other.Sku)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.WarehouseLocationId != null)
hash = hash * 59 + this.WarehouseLocationId.GetHashCode();
if (this.Quantity != null)
hash = hash * 59 + this.Quantity.GetHashCode();
if (this.DistributionDate != null)
hash = hash * 59 + this.DistributionDate.GetHashCode();
if (this.UnitsPerCase != null)
hash = hash * 59 + this.UnitsPerCase.GetHashCode();
if (this.UnitsPerWrap != null)
hash = hash * 59 + this.UnitsPerWrap.GetHashCode();
if (this.RevisionDate != null)
hash = hash * 59 + this.RevisionDate.GetHashCode();
if (this.ProductionLot != null)
hash = hash * 59 + this.ProductionLot.GetHashCode();
if (this.OldestReceiptDate != null)
hash = hash * 59 + this.OldestReceiptDate.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.PoNo != null)
hash = hash * 59 + this.PoNo.GetHashCode();
if (this.Sku != null)
hash = hash * 59 + this.Sku.GetHashCode();
return hash;
}
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Moq.Behaviors;
namespace Moq
{
internal static class HandleWellKnownMethods
{
private static Dictionary<string, Func<Invocation, Mock, bool>> specialMethods = new Dictionary<string, Func<Invocation, Mock, bool>>()
{
["Equals"] = HandleEquals,
["Finalize"] = HandleFinalize,
["GetHashCode"] = HandleGetHashCode,
["get_" + nameof(IMocked.Mock)] = HandleMockGetter,
["ToString"] = HandleToString,
};
public static bool Handle(Invocation invocation, Mock mock)
{
return specialMethods.TryGetValue(invocation.Method.Name, out var handler)
&& handler.Invoke(invocation, mock);
}
private static bool HandleEquals(Invocation invocation, Mock mock)
{
if (IsObjectMethod(invocation.Method) && !mock.MutableSetups.Any(c => IsObjectMethod(c.Method, "Equals")))
{
invocation.ReturnValue = ReferenceEquals(invocation.Arguments.First(), mock.Object);
return true;
}
else
{
return false;
}
}
private static bool HandleFinalize(Invocation invocation, Mock mock)
{
return IsFinalizer(invocation.Method);
}
private static bool HandleGetHashCode(Invocation invocation, Mock mock)
{
// Only if there is no corresponding setup for `GetHashCode()`
if (IsObjectMethod(invocation.Method) && !mock.MutableSetups.Any(c => IsObjectMethod(c.Method, "GetHashCode")))
{
invocation.ReturnValue = mock.GetHashCode();
return true;
}
else
{
return false;
}
}
private static bool HandleToString(Invocation invocation, Mock mock)
{
// Only if there is no corresponding setup for `ToString()`
if (IsObjectMethod(invocation.Method) && !mock.MutableSetups.Any(c => IsObjectMethod(c.Method, "ToString")))
{
invocation.ReturnValue = mock.ToString() + ".Object";
return true;
}
else
{
return false;
}
}
private static bool HandleMockGetter(Invocation invocation, Mock mock)
{
if (typeof(IMocked).IsAssignableFrom(invocation.Method.DeclaringType))
{
invocation.ReturnValue = mock;
return true;
}
else
{
return false;
}
}
private static bool IsFinalizer(MethodInfo method)
{
return method.GetBaseDefinition() == typeof(object).GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance);
}
private static bool IsObjectMethod(MethodInfo method) => method.DeclaringType == typeof(object);
private static bool IsObjectMethod(MethodInfo method, string name) => IsObjectMethod(method) && method.Name == name;
}
internal static class FindAndExecuteMatchingSetup
{
public static bool Handle(Invocation invocation, Mock mock)
{
var matchingSetup = mock.MutableSetups.FindMatchFor(invocation);
if (matchingSetup != null)
{
matchingSetup.Execute(invocation);
return true;
}
else
{
return false;
}
}
}
internal static class HandleEventSubscription
{
public static bool Handle(Invocation invocation, Mock mock)
{
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
var methodName = invocation.Method.Name;
// Special case for event accessors. The following, seemingly random character checks are guards against
// more expensive checks (for the common case where the invoked method is *not* an event accessor).
if (methodName.Length > 4)
{
if (methodName[0] == 'a' && methodName[3] == '_' && invocation.Method.IsEventAddAccessor())
{
var implementingMethod = invocation.Method.GetImplementingMethod(invocation.ProxyType);
var @event = implementingMethod.DeclaringType.GetEvents(bindingFlags).SingleOrDefault(e => e.GetAddMethod(true) == implementingMethod);
if (@event != null)
{
bool doesntHaveEventSetup = !mock.MutableSetups.HasEventSetup;
if (mock.CallBase && !invocation.Method.IsAbstract)
{
if (doesntHaveEventSetup)
{
invocation.ReturnValue = invocation.CallBase();
}
}
else if (invocation.Arguments.Length > 0 && invocation.Arguments[0] is Delegate delegateInstance)
{
mock.EventHandlers.Add(@event, delegateInstance);
}
return doesntHaveEventSetup;
}
}
else if (methodName[0] == 'r' && methodName.Length > 7 && methodName[6] == '_' && invocation.Method.IsEventRemoveAccessor())
{
var implementingMethod = invocation.Method.GetImplementingMethod(invocation.ProxyType);
var @event = implementingMethod.DeclaringType.GetEvents(bindingFlags).SingleOrDefault(e => e.GetRemoveMethod(true) == implementingMethod);
if (@event != null)
{
bool doesntHaveEventSetup = !mock.MutableSetups.HasEventSetup;
if (mock.CallBase && !invocation.Method.IsAbstract)
{
if (doesntHaveEventSetup)
{
invocation.ReturnValue = invocation.CallBase();
}
}
else if (invocation.Arguments.Length > 0 && invocation.Arguments[0] is Delegate delegateInstance)
{
mock.EventHandlers.Remove(@event, delegateInstance);
}
return doesntHaveEventSetup;
}
}
}
return false;
}
}
internal static class RecordInvocation
{
public static void Handle(Invocation invocation, Mock mock)
{
// Save to support Verify[expression] pattern.
mock.MutableInvocations.Add(invocation);
}
}
internal static class Return
{
public static void Handle(Invocation invocation, Mock mock)
{
new ReturnBaseOrDefaultValue(mock).Execute(invocation);
}
}
internal static class HandleAutoSetupProperties
{
private static readonly int AccessorPrefixLength = "?et_".Length; // get_ or set_
public static bool Handle(Invocation invocation, Mock mock)
{
if (mock.AutoSetupPropertiesDefaultValueProvider == null)
{
return false;
}
MethodInfo invocationMethod = invocation.Method;
if (invocationMethod.IsPropertyAccessor())
{
string propertyNameToSearch = invocationMethod.Name.Substring(AccessorPrefixLength);
PropertyInfo property = invocationMethod.DeclaringType.GetProperty(propertyNameToSearch);
if (property == null)
{
return false;
}
var expression = GetPropertyExpression(invocationMethod.DeclaringType, property);
object propertyValue;
Setup getterSetup = null;
if (property.CanRead(out var getter))
{
if (ProxyFactory.Instance.IsMethodVisible(getter, out _))
{
propertyValue = CreateInitialPropertyValue(mock, getter);
getterSetup = new AutoImplementedPropertyGetterSetup(mock, expression, getter, () => propertyValue);
mock.MutableSetups.Add(getterSetup);
}
// If we wanted to optimise for speed, we'd probably be forgiven
// for removing the above `IsMethodVisible` guard, as it's rather
// unlikely to encounter non-public getters such as the following
// in real-world code:
//
// public T Property { internal get; set; }
//
// Usually, it's only the setters that are made non-public. For
// now however, we prefer correctness.
}
Setup setterSetup = null;
if (property.CanWrite(out var setter))
{
if (ProxyFactory.Instance.IsMethodVisible(setter, out _))
{
setterSetup = new AutoImplementedPropertySetterSetup(mock, expression, setter, (newValue) =>
{
propertyValue = newValue;
});
mock.MutableSetups.Add(setterSetup);
}
}
Setup setupToExecute = invocationMethod.IsGetAccessor() ? getterSetup : setterSetup;
setupToExecute.Execute(invocation);
return true;
}
else
{
return false;
}
}
private static object CreateInitialPropertyValue(Mock mock, MethodInfo getter)
{
object initialValue = mock.GetDefaultValue(getter, out Mock innerMock,
useAlternateProvider: mock.AutoSetupPropertiesDefaultValueProvider);
if (innerMock != null)
{
Mock.SetupAllProperties(innerMock, mock.AutoSetupPropertiesDefaultValueProvider);
}
return initialValue;
}
private static LambdaExpression GetPropertyExpression(Type mockType, PropertyInfo property)
{
var param = Expression.Parameter(mockType, "m");
return Expression.Lambda(Expression.MakeMemberAccess(param, property), param);
}
}
internal static class FailForStrictMock
{
public static void Handle(Invocation invocation, Mock mock)
{
if (mock.Behavior == MockBehavior.Strict)
{
throw MockException.NoSetup(invocation);
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Analysis {
/// <summary>
/// Encapsulates all of the information about a single module which has been analyzed.
///
/// Can be queried for various information about the resulting analysis.
/// </summary>
public sealed class ModuleAnalysis {
private readonly AnalysisUnit _unit;
private readonly InterpreterScope _scope;
private readonly IAnalysisCookie _cookie;
private static Regex _otherPrivateRegex = new Regex("^_[a-zA-Z_]\\w*__[a-zA-Z_]\\w*$");
private static readonly IEnumerable<IOverloadResult> GetSignaturesError =
new[] { new SimpleOverloadResult(new ParameterResult[0], "Unknown", "IntellisenseError_Sigs") };
internal ModuleAnalysis(AnalysisUnit unit, InterpreterScope scope, IAnalysisCookie cookie) {
_unit = unit;
_scope = scope;
_cookie = cookie;
}
#region Public API
/// <summary>
/// Returns the IAnalysisCookie which was used to produce this ModuleAnalysis.
/// </summary>
public IAnalysisCookie AnalysisCookie {
get {
return _cookie;
}
}
/// <summary>
/// Evaluates the given expression in at the provided line number and returns the values
/// that the expression can evaluate to.
/// </summary>
/// <param name="exprText">The expression to determine the result of.</param>
/// <param name="index">The 0-based absolute index into the file where the expression should be evaluated.</param>
public IEnumerable<AnalysisValue> GetValuesByIndex(string exprText, int index) {
return GetValues(exprText, _unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Evaluates the given expression in at the provided line number and returns the values
/// that the expression can evaluate to.
/// </summary>
/// <param name="exprText">The expression to determine the result of.</param>
/// <param name="location">The location in the file where the expression should be evaluated.</param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<AnalysisValue> GetValues(string exprText, SourceLocation location) {
var scope = FindScope(location);
var privatePrefix = GetPrivatePrefixClassName(scope);
var expr = Statement.GetExpression(GetAstFromText(exprText, privatePrefix).Body);
var unit = GetNearestEnclosingAnalysisUnit(scope);
var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true);
var values = eval.Evaluate(expr);
var res = AnalysisSet.EmptyUnion;
foreach (var v in values) {
MultipleMemberInfo multipleMembers = v as MultipleMemberInfo;
if (multipleMembers != null) {
foreach (var member in multipleMembers.Members) {
if (member.IsCurrent) {
res = res.Add(member);
}
}
} else if (v.IsCurrent) {
res = res.Add(v);
}
}
return res;
}
internal IEnumerable<AnalysisVariable> ReferencablesToVariables(IEnumerable<IReferenceable> defs) {
foreach (var def in defs) {
foreach (var res in ToVariables(def)) {
yield return res;
}
}
}
internal IEnumerable<AnalysisVariable> ToVariables(IReferenceable referenceable) {
LocatedVariableDef locatedDef = referenceable as LocatedVariableDef;
if (locatedDef != null &&
locatedDef.Entry.Tree != null && // null tree if there are errors in the file
locatedDef.DeclaringVersion == locatedDef.Entry.AnalysisVersion) {
var start = locatedDef.Node.GetStart(locatedDef.Entry.Tree);
yield return new AnalysisVariable(VariableType.Definition, new LocationInfo(locatedDef.Entry, start.Line, start.Column));
}
VariableDef def = referenceable as VariableDef;
if (def != null) {
foreach (var location in def.TypesNoCopy.SelectMany(type => type.Locations)) {
yield return new AnalysisVariable(VariableType.Value, location);
}
}
foreach (var reference in referenceable.Definitions) {
yield return new AnalysisVariable(VariableType.Definition, reference.Value.GetLocationInfo(reference.Key));
}
foreach (var reference in referenceable.References) {
yield return new AnalysisVariable(VariableType.Reference, reference.Value.GetLocationInfo(reference.Key));
}
}
/// <summary>
/// Gets the variables the given expression evaluates to. Variables
/// include parameters, locals, and fields assigned on classes, modules
/// and instances.
///
/// Variables are classified as either definitions or references. Only
/// parameters have unique definition points - all other types of
/// variables have only one or more references.
/// </summary>
/// <param name="exprText">The expression to find variables for.</param>
/// <param name="index">
/// The 0-based absolute index into the file where the expression should
/// be evaluated.
/// </param>
public IEnumerable<IAnalysisVariable> GetVariablesByIndex(string exprText, int index) {
return GetVariables(exprText, _unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets the variables the given expression evaluates to. Variables
/// include parameters, locals, and fields assigned on classes, modules
/// and instances.
///
/// Variables are classified as either definitions or references. Only
/// parameters have unique definition points - all other types of
/// variables have only one or more references.
/// </summary>
/// <param name="exprText">The expression to find variables for.</param>
/// <param name="location">
/// The location in the file where the expression should be evaluated.
/// </param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<IAnalysisVariable> GetVariables(string exprText, SourceLocation location) {
var scope = FindScope(location);
string privatePrefix = GetPrivatePrefixClassName(scope);
var expr = Statement.GetExpression(GetAstFromText(exprText, privatePrefix).Body);
var unit = GetNearestEnclosingAnalysisUnit(scope);
NameExpression name = expr as NameExpression;
if (name != null) {
var defScope = scope.EnumerateTowardsGlobal.FirstOrDefault(s =>
s.ContainsVariable(name.Name) && (s == scope || s.VisibleToChildren || IsFirstLineOfFunction(scope, s, location)));
if (defScope == null) {
var variables = _unit.ProjectState.BuiltinModule.GetDefinitions(name.Name);
return variables.SelectMany(ToVariables);
}
return GetVariablesInScope(name, defScope).Distinct();
}
MemberExpression member = expr as MemberExpression;
if (member != null && !string.IsNullOrEmpty(member.Name)) {
var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true);
var objects = eval.Evaluate(member.Target);
foreach (var v in objects) {
var container = v as IReferenceableContainer;
if (container != null) {
return ReferencablesToVariables(container.GetDefinitions(member.Name));
}
}
}
return Enumerable.Empty<IAnalysisVariable>();
}
private IEnumerable<IAnalysisVariable> GetVariablesInScope(NameExpression name, InterpreterScope scope) {
var result = new List<IAnalysisVariable>();
result.AddRange(scope.GetMergedVariables(name.Name).SelectMany(ToVariables));
// if a variable is imported from another module then also yield the defs/refs for the
// value in the defining module.
result.AddRange(scope.GetLinkedVariables(name.Name).SelectMany(ToVariables));
var classScope = scope as ClassScope;
if (classScope != null) {
// if the member is defined in a base class as well include the base class member and references
var cls = classScope.Class;
if (cls.Push()) {
try {
foreach (var baseNs in cls.Bases.SelectMany()) {
if (baseNs.Push()) {
try {
ClassInfo baseClassNs = baseNs as ClassInfo;
if (baseClassNs != null) {
result.AddRange(
baseClassNs.Scope.GetMergedVariables(name.Name).SelectMany(ToVariables)
);
}
} finally {
baseNs.Pop();
}
}
}
} finally {
cls.Pop();
}
}
}
return result;
}
/// <summary>
/// Gets the list of modules known by the current analysis.
/// </summary>
/// <param name="topLevelOnly">Only return top-level modules.</param>
public MemberResult[] GetModules(bool topLevelOnly = false) {
List<MemberResult> res = new List<MemberResult>(ProjectState.GetModules(topLevelOnly));
var children = GlobalScope.GetChildrenPackages(InterpreterContext);
foreach (var child in children) {
res.Add(new MemberResult(child.Key, PythonMemberType.Module));
}
return res.ToArray();
}
/// <summary>
/// Gets the list of modules and members matching the provided names.
/// </summary>
/// <param name="names">The dotted name parts to match</param>
/// <param name="includeMembers">Include module members that match as
/// well as just modules.</param>
public MemberResult[] GetModuleMembers(string[] names, bool includeMembers = false) {
var res = new List<MemberResult>(ProjectState.GetModuleMembers(InterpreterContext, names, includeMembers));
var children = GlobalScope.GetChildrenPackages(InterpreterContext);
foreach (var child in children) {
var mod = (ModuleInfo)child.Value;
if (string.IsNullOrEmpty(mod.Name)) {
// Module does not have an importable name
continue;
}
var childName = mod.Name.Split('.');
if (childName.Length >= 2 && childName[0] == GlobalScope.Name && childName[1] == names[0]) {
res.AddRange(PythonAnalyzer.GetModuleMembers(InterpreterContext, names, includeMembers, mod as IModule));
}
}
return res.ToArray();
}
private static bool IsFirstLineOfFunction(InterpreterScope innerScope, InterpreterScope outerScope, SourceLocation location) {
if (innerScope.OuterScope == outerScope && innerScope is FunctionScope) {
var funcScope = (FunctionScope)innerScope;
var def = funcScope.Function.FunctionDefinition;
// TODO: Use indexes rather than lines to check location
if (location.Line == def.GetStart(def.GlobalParent).Line) {
return true;
}
}
return false;
}
private class ErrorWalker : PythonWalker {
public bool HasError { get; private set; }
public override bool Walk(ErrorStatement node) {
HasError = true;
return false;
}
public override bool Walk(ErrorExpression node) {
HasError = true;
return false;
}
}
/// <summary>
/// Evaluates a given expression and returns a list of members which
/// exist in the expression.
///
/// If the expression is an empty string returns all available members
/// at that location.
/// </summary>
/// <param name="exprText">The expression to find members for.</param>
/// <param name="index">
/// The 0-based absolute index into the file where the expression should
/// be evaluated.
/// </param>
public IEnumerable<MemberResult> GetMembersByIndex(
string exprText,
int index,
GetMemberOptions options = GetMemberOptions.IntersectMultipleResults
) {
return GetMembers(exprText, _unit.Tree.IndexToLocation(index), options);
}
/// <summary>
/// Evaluates a given expression and returns a list of members which
/// exist in the expression.
///
/// If the expression is an empty string returns all available members
/// at that location.
/// </summary>
/// <param name="exprText">The expression to find members for.</param>
/// </param>
/// <param name="location">
/// The location in the file where the expression should be evaluated.
/// </param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<MemberResult> GetMembers(
string exprText,
SourceLocation location,
GetMemberOptions options = GetMemberOptions.IntersectMultipleResults
) {
if (exprText.Length == 0) {
return GetAllAvailableMembers(location, options);
}
var scope = FindScope(location);
var privatePrefix = GetPrivatePrefixClassName(scope);
var expr = Statement.GetExpression(GetAstFromText(exprText, privatePrefix).Body);
if (expr is ConstantExpression && ((ConstantExpression)expr).Value is int) {
// no completions on integer ., the user is typing a float
return Enumerable.Empty<MemberResult>();
}
var errorWalker = new ErrorWalker();
expr.Walk(errorWalker);
if (errorWalker.HasError) {
return null;
}
var unit = GetNearestEnclosingAnalysisUnit(scope);
var lookup = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true).Evaluate(expr);
return GetMemberResults(lookup, scope, options);
}
/// <summary>
/// Gets information about the available signatures for the given expression.
/// </summary>
/// <param name="exprText">The expression to get signatures for.</param>
/// <param name="index">The 0-based absolute index into the file.</param>
public IEnumerable<IOverloadResult> GetSignaturesByIndex(string exprText, int index) {
return GetSignatures(exprText, _unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets information about the available signatures for the given expression.
/// </summary>
/// <param name="exprText">The expression to get signatures for.</param>
/// <param name="location">The location in the file.</param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<IOverloadResult> GetSignatures(string exprText, SourceLocation location) {
try {
var scope = FindScope(location);
var unit = GetNearestEnclosingAnalysisUnit(scope);
var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true);
using (var parser = Parser.CreateParser(new StringReader(exprText), _unit.ProjectState.LanguageVersion)) {
var expr = GetExpression(parser.ParseTopExpression().Body);
if (expr is ListExpression ||
expr is TupleExpression ||
expr is DictionaryExpression) {
return Enumerable.Empty<IOverloadResult>();
}
var lookup = eval.Evaluate(expr);
lookup = AnalysisSet.Create(lookup.Where(av => !(av is MultipleMemberInfo)).Concat(
lookup.OfType<MultipleMemberInfo>().SelectMany(mmi => mmi.Members)
));
var result = new HashSet<OverloadResult>(OverloadResultComparer.Instance);
// TODO: Include relevant type info on the parameter...
result.UnionWith(lookup
// Exclude constant values first time through
.Where(av => av.MemberType != PythonMemberType.Constant)
.SelectMany(av => av.Overloads ?? Enumerable.Empty<OverloadResult>())
);
if (!result.Any()) {
result.UnionWith(lookup
.Where(av => av.MemberType == PythonMemberType.Constant)
.SelectMany(av => av.Overloads ?? Enumerable.Empty<OverloadResult>()));
}
return result;
}
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
Debug.Fail(ex.ToString());
return GetSignaturesError;
}
}
/// <summary>
/// Gets the hierarchy of class and function definitions at the
/// specified location.
/// </summary>
/// <param name="index">The 0-based absolute index into the file.</param>
public IEnumerable<MemberResult> GetDefinitionTreeByIndex(int index) {
return GetDefinitionTree(_unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets the hierarchy of class and function definitions at the
/// specified location.
/// </summary>
/// <param name="location">The location in the file.</param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<MemberResult> GetDefinitionTree(SourceLocation location) {
try {
return FindScope(location).EnumerateTowardsGlobal
.Select(s => new MemberResult(s.Name, s.GetMergedAnalysisValues()))
.ToList();
} catch (Exception) {
// TODO: log exception
Debug.Fail("Failed to find scope. Bad state in analysis");
return new[] { new MemberResult("Unknown", new AnalysisValue[] { }) };
}
}
/// <summary>
/// Gets information about methods defined on base classes but not
/// directly on the current class.
/// </summary>
/// <param name="index">The 0-based absolute index into the file.</param>
public IEnumerable<IOverloadResult> GetOverrideableByIndex(int index) {
return GetOverrideable(_unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets information about methods defined on base classes but not
/// directly on the current class.
/// </summary>
/// <param name="location">The location in the file.</param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<IOverloadResult> GetOverrideable(SourceLocation location) {
try {
var result = new List<IOverloadResult>();
var scope = FindScope(location);
var cls = scope as ClassScope;
if (cls == null) {
return result;
}
var handled = new HashSet<string>(cls.Children.Select(child => child.Name));
var cls2 = scope as ClassScope;
var mro = (cls2 ?? cls).Class.Mro;
if (mro == null) {
return result;
}
foreach (var baseClass in mro.Skip(1).SelectMany()) {
ClassInfo klass;
BuiltinClassInfo builtinClass;
IEnumerable<AnalysisValue> source;
if ((klass = baseClass as ClassInfo) != null) {
source = klass.Scope.Children
.Where(child => child != null && child.AnalysisValue != null)
.Select(child => child.AnalysisValue);
} else if ((builtinClass = baseClass as BuiltinClassInfo) != null) {
source = builtinClass.GetAllMembers(InterpreterContext)
.SelectMany(kv => kv.Value)
.Where(child => child != null &&
(child.MemberType == PythonMemberType.Function ||
child.MemberType == PythonMemberType.Method));
} else {
continue;
}
foreach (var child in source) {
if (!child.Overloads.Any()) {
continue;
}
try {
var overload = child.Overloads.Aggregate(
(best, o) => o.Parameters.Length > best.Parameters.Length ? o : best
);
if (handled.Contains(overload.Name)) {
continue;
}
handled.Add(overload.Name);
result.Add(overload);
} catch {
// TODO: log exception
// Exceptions only affect the current override. Others may still be offerred.
}
}
}
return result;
} catch (Exception) {
// TODO: log exception
return new IOverloadResult[0];
}
}
/// <summary>
/// Gets the available names at the given location. This includes
/// built-in variables, global variables, and locals.
/// </summary>
/// <param name="index">
/// The 0-based absolute index into the file where the available members
/// should be looked up.
/// </param>
public IEnumerable<MemberResult> GetAllAvailableMembersByIndex(
int index,
GetMemberOptions options = GetMemberOptions.IntersectMultipleResults
) {
return GetAllAvailableMembers(_unit.Tree.IndexToLocation(index), options);
}
/// <summary>
/// Gets the available names at the given location. This includes
/// built-in variables, global variables, and locals.
/// </summary>
/// <param name="location">
/// The location in the file where the available members should be
/// looked up.
/// </param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<MemberResult> GetAllAvailableMembers(SourceLocation location, GetMemberOptions options = GetMemberOptions.IntersectMultipleResults) {
var result = new Dictionary<string, IEnumerable<AnalysisValue>>();
// collect builtins
foreach (var variable in ProjectState.BuiltinModule.GetAllMembers(ProjectState._defaultContext)) {
result[variable.Key] = new List<AnalysisValue>(variable.Value);
}
// collect variables from user defined scopes
var scope = FindScope(location);
foreach (var s in scope.EnumerateTowardsGlobal) {
foreach (var kvp in s.GetAllMergedVariables()) {
// deliberately overwrite variables from outer scopes
result[kvp.Key] = new List<AnalysisValue>(kvp.Value.TypesNoCopy);
}
}
var res = MemberDictToResultList(GetPrivatePrefix(scope), options, result);
if (options.Keywords()) {
res = GetKeywordMembers(options, scope).Union(res);
}
return res;
}
private IEnumerable<MemberResult> GetKeywordMembers(GetMemberOptions options, InterpreterScope scope) {
IEnumerable<string> keywords = null;
if (options.ExpressionKeywords()) {
// keywords available in any context
keywords = PythonKeywords.Expression(ProjectState.LanguageVersion);
} else {
keywords = Enumerable.Empty<string>();
}
if (options.StatementKeywords()) {
keywords = keywords.Union(PythonKeywords.Statement(ProjectState.LanguageVersion));
}
if (!(scope is FunctionScope)) {
keywords = keywords.Except(PythonKeywords.InvalidOutsideFunction(ProjectState.LanguageVersion));
}
return keywords.Select(kw => new MemberResult(kw, PythonMemberType.Keyword));
}
#endregion
/// <summary>
/// Gets the available names at the given location. This includes
/// global variables and locals, but not built-in variables.
/// </summary>
/// <param name="index">
/// The 0-based absolute index into the file where the available members
/// should be looked up.
/// </param>
/// <remarks>TODO: Remove; this is only used for tests</remarks>
internal IEnumerable<string> GetVariablesNoBuiltinsByIndex(int index) {
return GetVariablesNoBuiltins(_unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets the available names at the given location. This includes
/// global variables and locals, but not built-in variables.
/// </summary>
/// <param name="location">
/// The location in the file where the available members should be
/// looked up.
/// </param>
/// <remarks>TODO: Remove; this is only used for tests</remarks>
/// <remarks>New in 2.2</remarks>
internal IEnumerable<string> GetVariablesNoBuiltins(SourceLocation location) {
var result = Enumerable.Empty<string>();
var chain = FindScope(location);
foreach (var scope in chain.EnumerateFromGlobal) {
if (scope.VisibleToChildren || scope == chain) {
result = result.Concat(scope.GetAllMergedVariables().Select(val => val.Key));
}
}
return result.Distinct();
}
/// <summary>
/// Gets the top-level scope for the module.
/// </summary>
internal ModuleInfo GlobalScope {
get {
var result = (ModuleScope)Scope;
return result.Module;
}
}
public IModuleContext InterpreterContext {
get {
return GlobalScope.InterpreterContext;
}
}
public PythonAnalyzer ProjectState {
get { return GlobalScope.ProjectEntry.ProjectState; }
}
internal InterpreterScope Scope {
get { return _scope; }
}
internal IEnumerable<MemberResult> GetMemberResults(
IEnumerable<AnalysisValue> vars,
InterpreterScope scope,
GetMemberOptions options
) {
IList<AnalysisValue> namespaces = new List<AnalysisValue>();
foreach (var ns in vars) {
if (ns != null) {
namespaces.Add(ns);
}
}
if (namespaces.Count == 1) {
// optimize for the common case of only a single namespace
var newMembers = namespaces[0].GetAllMembers(GlobalScope.InterpreterContext);
if (newMembers == null || newMembers.Count == 0) {
return new MemberResult[0];
}
return SingleMemberResult(GetPrivatePrefix(scope), options, newMembers);
}
Dictionary<string, IEnumerable<AnalysisValue>> memberDict = null;
Dictionary<string, IEnumerable<AnalysisValue>> ownerDict = null;
HashSet<string> memberSet = null;
int namespacesCount = namespaces.Count;
foreach (AnalysisValue ns in namespaces) {
if (ProjectState._noneInst == ns) {
namespacesCount -= 1;
continue;
}
var newMembers = ns.GetAllMembers(GlobalScope.InterpreterContext);
// IntersectMembers(members, memberSet, memberDict);
if (newMembers == null || newMembers.Count == 0) {
continue;
}
if (memberSet == null) {
// first namespace, add everything
memberSet = new HashSet<string>(newMembers.Keys);
memberDict = new Dictionary<string, IEnumerable<AnalysisValue>>();
ownerDict = new Dictionary<string, IEnumerable<AnalysisValue>>();
foreach (var kvp in newMembers) {
var tmp = new List<AnalysisValue>(kvp.Value);
memberDict[kvp.Key] = tmp;
ownerDict[kvp.Key] = new List<AnalysisValue> { ns };
}
} else {
// 2nd or nth namespace, union or intersect
HashSet<string> toRemove;
IEnumerable<string> adding;
if (options.Intersect()) {
adding = new HashSet<string>(newMembers.Keys);
// Find the things only in memberSet that we need to remove from memberDict
// toRemove = (memberSet ^ adding) & memberSet
toRemove = new HashSet<string>(memberSet);
toRemove.SymmetricExceptWith(adding);
toRemove.IntersectWith(memberSet);
// intersect memberSet with what we're adding
memberSet.IntersectWith(adding);
// we're only adding things they both had
adding = memberSet;
} else {
// we're adding all of newMembers keys
adding = newMembers.Keys;
toRemove = null;
}
// update memberDict
foreach (var name in adding) {
IEnumerable<AnalysisValue> values;
List<AnalysisValue> valueList;
if (!memberDict.TryGetValue(name, out values)) {
memberDict[name] = values = new List<AnalysisValue>();
}
if ((valueList = values as List<AnalysisValue>) == null) {
memberDict[name] = valueList = new List<AnalysisValue>(values);
}
valueList.AddRange(newMembers[name]);
if (!ownerDict.TryGetValue(name, out values)) {
ownerDict[name] = values = new List<AnalysisValue>();
}
if ((valueList = values as List<AnalysisValue>) == null) {
ownerDict[name] = valueList = new List<AnalysisValue>(values);
}
valueList.Add(ns);
}
if (toRemove != null) {
foreach (var name in toRemove) {
memberDict.Remove(name);
ownerDict.Remove(name);
}
}
}
}
if (memberDict == null) {
return new MemberResult[0];
}
if (options.Intersect()) {
// No need for this information if we're only showing the
// intersection. Setting it to null saves lookups later.
ownerDict = null;
}
return MemberDictToResultList(GetPrivatePrefix(scope), options, memberDict, ownerDict, namespacesCount);
}
/// <summary>
/// Gets the expression for the given text.
///
/// This overload shipped in v1 but does not take into account private members
/// prefixed with __'s. Calling the GetExpressionFromText(string exprText, int lineNumber)
/// overload will take into account the current class and therefore will
/// work properly with name mangled private members.
/// </summary>
[Obsolete("Use GetAstFromTextByIndex")]
public Expression GetExpressionFromText(string exprText) {
return Statement.GetExpression(GetAstFromText(exprText, null).Body);
}
/// <summary>
/// Gets the AST for the given text as if it appeared at the specified
/// location.
///
/// If the expression is a member expression such as "fob.__bar" and the
/// line number is inside of a class definition this will return a
/// MemberExpression with the mangled name like "fob.__ClassName_Bar".
/// </summary>
/// <param name="exprText">The expression to evaluate.</param>
/// <param name="index">
/// The 0-based index into the file where the expression should be
/// evaluated.
/// </param>
/// <remarks>New in 1.1</remarks>
public PythonAst GetAstFromTextByIndex(string exprText, int index) {
return GetAstFromText(exprText, _unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets the AST for the given text as if it appeared at the specified
/// location.
///
/// If the expression is a member expression such as "fob.__bar" and the
/// line number is inside of a class definition this will return a
/// MemberExpression with the mangled name like "fob.__ClassName_Bar".
/// </summary>
/// <param name="exprText">The expression to evaluate.</param>
/// <param name="index">
/// The 0-based index into the file where the expression should be
/// evaluated.
/// </param>
/// <remarks>New in 2.2</remarks>
public PythonAst GetAstFromText(string exprText, SourceLocation location) {
var scopes = FindScope(location);
var privatePrefix = GetPrivatePrefixClassName(scopes);
return GetAstFromText(exprText, privatePrefix);
}
public string ModuleName {
get {
return _scope.GlobalScope.Name;
}
}
private PythonAst GetAstFromText(string exprText, string privatePrefix) {
using (var parser = Parser.CreateParser(new StringReader(exprText), _unit.ProjectState.LanguageVersion, new ParserOptions() { PrivatePrefix = privatePrefix, Verbatim = true })) {
return parser.ParseTopExpression();
}
}
internal static Expression GetExpression(Statement statement) {
if (statement is ExpressionStatement) {
return ((ExpressionStatement)statement).Expression;
} else if (statement is ReturnStatement) {
return ((ReturnStatement)statement).Expression;
} else {
return null;
}
}
/// <summary>
/// Gets the chain of scopes which are associated with the given position in the code.
/// </summary>
private InterpreterScope FindScope(SourceLocation location) {
var res = FindScope(Scope, _unit.Tree, location);
Debug.Assert(res != null, "Should never return null from FindScope");
return res;
}
private static bool IsInFunctionParameter(InterpreterScope scope, PythonAst tree, SourceLocation location) {
var function = scope.Node as FunctionDefinition;
if (function == null) {
// Not a function
return false;
}
if (location.Index < function.StartIndex || location.Index >= function.Body.StartIndex) {
// Not within the def line
return false;
}
return function.Parameters != null &&
function.Parameters.Any(p => {
var paramName = p.GetVerbatimImage(tree) ?? p.Name;
return location.Index >= p.StartIndex && location.Index <= p.StartIndex + paramName.Length;
});
}
private static int GetParentScopeIndent(InterpreterScope scope, PythonAst tree) {
if (scope is ClassScope) {
// Return column of "class" statement
return tree.IndexToLocation(scope.GetStart(tree)).Column;
}
var function = scope as FunctionScope;
if (function != null && !((FunctionDefinition)function.Node).IsLambda) {
// Return column of "def" statement
return tree.IndexToLocation(scope.GetStart(tree)).Column;
}
var isinstance = scope as IsInstanceScope;
if (isinstance != null && isinstance._effectiveSuite != null) {
int col = tree.IndexToLocation(isinstance._startIndex).Column;
if (isinstance._effectiveSuite.StartIndex < isinstance._startIndex) {
// "assert isinstance", so scope is before the test
return col - 1;
} else {
// "if isinstance", so scope is at the test
return col;
}
}
return -1;
}
private static InterpreterScope FindScope(InterpreterScope parent, PythonAst tree, SourceLocation location) {
var children = parent.Children.Where(c => !(c is StatementScope)).ToList();
InterpreterScope candidate = null;
for (int i = 0; i < children.Count; ++i) {
if (IsInFunctionParameter(children[i], tree, location)) {
// In parameter name scope, so consider the function scope.
candidate = children[i];
continue;
}
int start = children[i].GetBodyStart(tree);
if (start > location.Index) {
// We've gone past index completely so our last candidate is
// the best one.
break;
}
int end = children[i].GetStop(tree);
if (i + 1 < children.Count) {
int nextStart = children[i + 1].GetStart(tree);
if (nextStart > end) {
end = nextStart;
}
}
if (location.Index <= end || (candidate == null && i + 1 == children.Count)) {
candidate = children[i];
}
}
if (candidate == null) {
// No children, so we must belong in our parent
return parent;
}
int scopeIndent = GetParentScopeIndent(candidate, tree);
if (location.Column <= scopeIndent) {
// Candidate is at deeper indentation than location and the
// candidate is scoped, so return the parent instead.
return parent;
}
// Recurse to check children of candidate scope
var child = FindScope(candidate, tree, location);
var funcChild = child as FunctionScope;
if (funcChild != null &&
funcChild.Function.FunctionDefinition.IsLambda &&
child.GetStop(tree) < location.Index) {
// Do not want to extend a lambda function's scope to the end of
// the parent scope.
return parent;
}
return child;
}
private static IEnumerable<MemberResult> MemberDictToResultList(
string privatePrefix,
GetMemberOptions options,
Dictionary<string, IEnumerable<AnalysisValue>> memberDict,
Dictionary<string, IEnumerable<AnalysisValue>> ownerDict = null,
int maximumOwners = 0
) {
foreach (var kvp in memberDict) {
string name = GetMemberName(privatePrefix, options, kvp.Key);
string completion = name;
if (name != null) {
IEnumerable<AnalysisValue> owners;
if (ownerDict != null && ownerDict.TryGetValue(kvp.Key, out owners) &&
owners.Any() && owners.Count() < maximumOwners) {
// This member came from less than the full set of types.
var seenNames = new HashSet<string>();
var newName = new StringBuilder(name);
newName.Append(" (");
foreach (var v in owners) {
if (!string.IsNullOrWhiteSpace(v.ShortDescription) && seenNames.Add(v.ShortDescription)) {
// Restrict each displayed type to 25 characters
if (v.ShortDescription.Length > 25) {
newName.Append(v.ShortDescription.Substring(0, 22));
newName.Append("...");
} else {
newName.Append(v.ShortDescription);
}
newName.Append(", ");
}
if (newName.Length > 200) break;
}
// Restrict the entire completion string to 200 characters
if (newName.Length > 200) {
newName.Length = 197;
// Avoid showing more than three '.'s in a row
while (newName[newName.Length - 1] == '.') {
newName.Length -= 1;
}
newName.Append("...");
} else {
newName.Length -= 2;
}
newName.Append(")");
name = newName.ToString();
}
yield return new MemberResult(name, completion, kvp.Value, null);
}
}
}
private static IEnumerable<MemberResult> SingleMemberResult(string privatePrefix, GetMemberOptions options, IDictionary<string, IAnalysisSet> memberDict) {
foreach (var kvp in memberDict) {
string name = GetMemberName(privatePrefix, options, kvp.Key);
if (name != null) {
yield return new MemberResult(name, kvp.Value);
}
}
}
private static string GetMemberName(string privatePrefix, GetMemberOptions options, string name) {
if (privatePrefix != null && name.StartsWith(privatePrefix) && !name.EndsWith("__")) {
// private prefix inside of the class, filter out the prefix.
return name.Substring(privatePrefix.Length - 2);
} else if (!_otherPrivateRegex.IsMatch(name) || !options.HideAdvanced()) {
return name;
}
return null;
}
private static string GetPrivatePrefixClassName(InterpreterScope scope) {
var klass = scope.EnumerateTowardsGlobal.OfType<ClassScope>().FirstOrDefault();
return klass == null ? null : klass.Name;
}
private static string GetPrivatePrefix(InterpreterScope scope) {
string classScopePrefix = GetPrivatePrefixClassName(scope);
if (classScopePrefix != null) {
return "_" + classScopePrefix + "__";
}
return null;
}
private int LineToIndex(int line) {
if (line <= 1) { // <= because v1 allowed zero even though we take 1 based lines.
return 0;
}
// line is 1 based, and index 0 in the array is the position of the 2nd line in the file.
line -= 2;
return _unit.Tree._lineLocations[line];
}
/// <summary>
/// Finds the best available analysis unit for lookup. This will be the one that is provided
/// by the nearest enclosing scope that is capable of providing one.
/// </summary>
private AnalysisUnit GetNearestEnclosingAnalysisUnit(InterpreterScope scopes) {
var units = from scope in scopes.EnumerateTowardsGlobal
let ns = scope.AnalysisValue
where ns != null
let unit = ns.AnalysisUnit
where unit != null
select unit;
return units.FirstOrDefault() ?? _unit;
}
}
}
| |
/*
* OANDA v20 REST API
*
* The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
*
* OpenAPI spec version: 3.0.15
* Contact: api@oanda.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Oanda.RestV20.Model
{
/// <summary>
/// The specification of an Account-specific Price.
/// </summary>
[DataContract]
public partial class Price : IEquatable<Price>, IValidatableObject
{
/// <summary>
/// The status of the Price.
/// </summary>
/// <value>The status of the Price.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum StatusEnum
{
/// <summary>
/// Enum Tradeable for "tradeable"
/// </summary>
[EnumMember(Value = "tradeable")]
Tradeable,
/// <summary>
/// Enum Nontradeable for "non-tradeable"
/// </summary>
[EnumMember(Value = "non-tradeable")]
Nontradeable,
/// <summary>
/// Enum Invalid for "invalid"
/// </summary>
[EnumMember(Value = "invalid")]
Invalid
}
/// <summary>
/// The status of the Price.
/// </summary>
/// <value>The status of the Price.</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public StatusEnum? Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Price" /> class.
/// </summary>
/// <param name="Type">The string \"PRICE\". Used to identify the a Price object when found in a stream..</param>
/// <param name="Instrument">The Price's Instrument..</param>
/// <param name="Time">The date/time when the Price was created.</param>
/// <param name="Status">The status of the Price..</param>
/// <param name="Tradeable">Flag indicating if the Price is tradeable or not.</param>
/// <param name="Bids">The list of prices and liquidity available on the Instrument's bid side. It is possible for this list to be empty if there is no bid liquidity currently available for the Instrument in the Account..</param>
/// <param name="Asks">The list of prices and liquidity available on the Instrument's ask side. It is possible for this list to be empty if there is no ask liquidity currently available for the Instrument in the Account..</param>
/// <param name="CloseoutBid">The closeout bid Price. This Price is used when a bid is required to closeout a Position (margin closeout or manual) yet there is no bid liquidity. The closeout bid is never used to open a new position..</param>
/// <param name="CloseoutAsk">The closeout ask Price. This Price is used when a ask is required to closeout a Position (margin closeout or manual) yet there is no ask liquidity. The closeout ask is never used to open a new position..</param>
/// <param name="QuoteHomeConversionFactors">QuoteHomeConversionFactors.</param>
/// <param name="UnitsAvailable">UnitsAvailable.</param>
public Price(string Type = default(string), string Instrument = default(string), string Time = default(string), StatusEnum? Status = default(StatusEnum?), bool? Tradeable = default(bool?), List<PriceBucket> Bids = default(List<PriceBucket>), List<PriceBucket> Asks = default(List<PriceBucket>), string CloseoutBid = default(string), string CloseoutAsk = default(string), QuoteHomeConversionFactors QuoteHomeConversionFactors = default(QuoteHomeConversionFactors), UnitsAvailable UnitsAvailable = default(UnitsAvailable))
{
this.Type = Type;
this.Instrument = Instrument;
this.Time = Time;
this.Status = Status;
this.Tradeable = Tradeable;
this.Bids = Bids;
this.Asks = Asks;
this.CloseoutBid = CloseoutBid;
this.CloseoutAsk = CloseoutAsk;
this.QuoteHomeConversionFactors = QuoteHomeConversionFactors;
this.UnitsAvailable = UnitsAvailable;
}
/// <summary>
/// The string \"PRICE\". Used to identify the a Price object when found in a stream.
/// </summary>
/// <value>The string \"PRICE\". Used to identify the a Price object when found in a stream.</value>
[DataMember(Name="type", EmitDefaultValue=false)]
public string Type { get; set; }
/// <summary>
/// The Price's Instrument.
/// </summary>
/// <value>The Price's Instrument.</value>
[DataMember(Name="instrument", EmitDefaultValue=false)]
public string Instrument { get; set; }
/// <summary>
/// The date/time when the Price was created
/// </summary>
/// <value>The date/time when the Price was created</value>
[DataMember(Name="time", EmitDefaultValue=false)]
public string Time { get; set; }
/// <summary>
/// Flag indicating if the Price is tradeable or not
/// </summary>
/// <value>Flag indicating if the Price is tradeable or not</value>
[DataMember(Name="tradeable", EmitDefaultValue=false)]
public bool? Tradeable { get; set; }
/// <summary>
/// The list of prices and liquidity available on the Instrument's bid side. It is possible for this list to be empty if there is no bid liquidity currently available for the Instrument in the Account.
/// </summary>
/// <value>The list of prices and liquidity available on the Instrument's bid side. It is possible for this list to be empty if there is no bid liquidity currently available for the Instrument in the Account.</value>
[DataMember(Name="bids", EmitDefaultValue=false)]
public List<PriceBucket> Bids { get; set; }
/// <summary>
/// The list of prices and liquidity available on the Instrument's ask side. It is possible for this list to be empty if there is no ask liquidity currently available for the Instrument in the Account.
/// </summary>
/// <value>The list of prices and liquidity available on the Instrument's ask side. It is possible for this list to be empty if there is no ask liquidity currently available for the Instrument in the Account.</value>
[DataMember(Name="asks", EmitDefaultValue=false)]
public List<PriceBucket> Asks { get; set; }
/// <summary>
/// The closeout bid Price. This Price is used when a bid is required to closeout a Position (margin closeout or manual) yet there is no bid liquidity. The closeout bid is never used to open a new position.
/// </summary>
/// <value>The closeout bid Price. This Price is used when a bid is required to closeout a Position (margin closeout or manual) yet there is no bid liquidity. The closeout bid is never used to open a new position.</value>
[DataMember(Name="closeoutBid", EmitDefaultValue=false)]
public string CloseoutBid { get; set; }
/// <summary>
/// The closeout ask Price. This Price is used when a ask is required to closeout a Position (margin closeout or manual) yet there is no ask liquidity. The closeout ask is never used to open a new position.
/// </summary>
/// <value>The closeout ask Price. This Price is used when a ask is required to closeout a Position (margin closeout or manual) yet there is no ask liquidity. The closeout ask is never used to open a new position.</value>
[DataMember(Name="closeoutAsk", EmitDefaultValue=false)]
public string CloseoutAsk { get; set; }
/// <summary>
/// Gets or Sets QuoteHomeConversionFactors
/// </summary>
[DataMember(Name="quoteHomeConversionFactors", EmitDefaultValue=false)]
public QuoteHomeConversionFactors QuoteHomeConversionFactors { get; set; }
/// <summary>
/// Gets or Sets UnitsAvailable
/// </summary>
[DataMember(Name="unitsAvailable", EmitDefaultValue=false)]
public UnitsAvailable UnitsAvailable { 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 Price {\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Instrument: ").Append(Instrument).Append("\n");
sb.Append(" Time: ").Append(Time).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Tradeable: ").Append(Tradeable).Append("\n");
sb.Append(" Bids: ").Append(Bids).Append("\n");
sb.Append(" Asks: ").Append(Asks).Append("\n");
sb.Append(" CloseoutBid: ").Append(CloseoutBid).Append("\n");
sb.Append(" CloseoutAsk: ").Append(CloseoutAsk).Append("\n");
sb.Append(" QuoteHomeConversionFactors: ").Append(QuoteHomeConversionFactors).Append("\n");
sb.Append(" UnitsAvailable: ").Append(UnitsAvailable).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Price);
}
/// <summary>
/// Returns true if Price instances are equal
/// </summary>
/// <param name="other">Instance of Price to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Price other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
) &&
(
this.Instrument == other.Instrument ||
this.Instrument != null &&
this.Instrument.Equals(other.Instrument)
) &&
(
this.Time == other.Time ||
this.Time != null &&
this.Time.Equals(other.Time)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.Tradeable == other.Tradeable ||
this.Tradeable != null &&
this.Tradeable.Equals(other.Tradeable)
) &&
(
this.Bids == other.Bids ||
this.Bids != null &&
this.Bids.SequenceEqual(other.Bids)
) &&
(
this.Asks == other.Asks ||
this.Asks != null &&
this.Asks.SequenceEqual(other.Asks)
) &&
(
this.CloseoutBid == other.CloseoutBid ||
this.CloseoutBid != null &&
this.CloseoutBid.Equals(other.CloseoutBid)
) &&
(
this.CloseoutAsk == other.CloseoutAsk ||
this.CloseoutAsk != null &&
this.CloseoutAsk.Equals(other.CloseoutAsk)
) &&
(
this.QuoteHomeConversionFactors == other.QuoteHomeConversionFactors ||
this.QuoteHomeConversionFactors != null &&
this.QuoteHomeConversionFactors.Equals(other.QuoteHomeConversionFactors)
) &&
(
this.UnitsAvailable == other.UnitsAvailable ||
this.UnitsAvailable != null &&
this.UnitsAvailable.Equals(other.UnitsAvailable)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
if (this.Instrument != null)
hash = hash * 59 + this.Instrument.GetHashCode();
if (this.Time != null)
hash = hash * 59 + this.Time.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.Tradeable != null)
hash = hash * 59 + this.Tradeable.GetHashCode();
if (this.Bids != null)
hash = hash * 59 + this.Bids.GetHashCode();
if (this.Asks != null)
hash = hash * 59 + this.Asks.GetHashCode();
if (this.CloseoutBid != null)
hash = hash * 59 + this.CloseoutBid.GetHashCode();
if (this.CloseoutAsk != null)
hash = hash * 59 + this.CloseoutAsk.GetHashCode();
if (this.QuoteHomeConversionFactors != null)
hash = hash * 59 + this.QuoteHomeConversionFactors.GetHashCode();
if (this.UnitsAvailable != null)
hash = hash * 59 + this.UnitsAvailable.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Channels
{
using System.Collections;
using System.Collections.Generic;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xml;
internal static class ReliableSessionPolicyStrings
{
public const string AcknowledgementInterval = "AcknowledgementInterval";
public const string AtLeastOnce = "AtLeastOnce";
public const string AtMostOnce = "AtMostOnce";
public const string BaseRetransmissionInterval = "BaseRetransmissionInterval";
public const string DeliveryAssurance = "DeliveryAssurance";
public const string ExactlyOnce = "ExactlyOnce";
public const string ExponentialBackoff = "ExponentialBackoff";
public const string InactivityTimeout = "InactivityTimeout";
public const string InOrder = "InOrder";
public const string Milliseconds = "Milliseconds";
public const string NET11Namespace = "http://schemas.microsoft.com/ws-rx/wsrmp/200702";
public const string NET11Prefix = "netrmp";
public const string ReliableSessionName = "RMAssertion";
public const string ReliableSessionFebruary2005Namespace = "http://schemas.xmlsoap.org/ws/2005/02/rm/policy";
public const string ReliableSessionFebruary2005Prefix = "wsrm";
public const string ReliableSession11Namespace = "http://docs.oasis-open.org/ws-rx/wsrmp/200702";
public const string ReliableSession11Prefix = "wsrmp";
public const string SequenceSTR = "SequenceSTR";
public const string SequenceTransportSecurity = "SequenceTransportSecurity";
}
public sealed class ReliableSessionBindingElementImporter : IPolicyImportExtension
{
void IPolicyImportExtension.ImportPolicy(MetadataImporter importer, PolicyConversionContext context)
{
if (importer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("importer");
}
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
bool gotAssertion = false;
XmlElement reliableSessionAssertion = PolicyConversionContext.FindAssertion(context.GetBindingAssertions(),
ReliableSessionPolicyStrings.ReliableSessionName,
ReliableSessionPolicyStrings.ReliableSessionFebruary2005Namespace, true);
if (reliableSessionAssertion != null)
{
ProcessReliableSessionFeb2005Assertion(reliableSessionAssertion, GetReliableSessionBindingElement(context));
gotAssertion = true;
}
reliableSessionAssertion = PolicyConversionContext.FindAssertion(context.GetBindingAssertions(),
ReliableSessionPolicyStrings.ReliableSessionName,
ReliableSessionPolicyStrings.ReliableSession11Namespace, true);
if (reliableSessionAssertion != null)
{
if (gotAssertion)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(
string.Format(SRServiceModel.MultipleVersionsFoundInPolicy,
ReliableSessionPolicyStrings.ReliableSessionName)));
}
ProcessReliableSession11Assertion(importer, reliableSessionAssertion,
GetReliableSessionBindingElement(context));
}
}
private static ReliableSessionBindingElement GetReliableSessionBindingElement(PolicyConversionContext context)
{
ReliableSessionBindingElement settings = context.BindingElements.Find<ReliableSessionBindingElement>();
if (settings == null)
{
settings = new ReliableSessionBindingElement();
context.BindingElements.Add(settings);
}
return settings;
}
private static bool Is11Assertion(XmlNode node, string assertion)
{
return IsElement(node, ReliableSessionPolicyStrings.NET11Namespace, assertion);
}
private static bool IsElement(XmlNode node, string ns, string assertion)
{
if (assertion == null)
{
throw Fx.AssertAndThrow("Argument assertion cannot be null.");
}
return ((node != null)
&& (node.NodeType == XmlNodeType.Element)
&& (node.NamespaceURI == ns)
&& (node.LocalName == assertion));
}
private static bool IsFeb2005Assertion(XmlNode node, string assertion)
{
return IsElement(node, ReliableSessionPolicyStrings.ReliableSessionFebruary2005Namespace, assertion);
}
private static void ProcessReliableSession11Assertion(MetadataImporter importer, XmlElement element,
ReliableSessionBindingElement settings)
{
// Version
settings.ReliableMessagingVersion = ReliableMessagingVersion.WSReliableMessaging11;
IEnumerator assertionChildren = element.ChildNodes.GetEnumerator();
XmlNode currentNode = SkipToNode(assertionChildren);
// Policy
ProcessWsrm11Policy(importer, currentNode, settings);
currentNode = SkipToNode(assertionChildren);
// Looking for:
// InactivityTimeout, AcknowledgementInterval
// InactivityTimeout
// AcknowledgementInterval
// or nothing at all.
State state = State.InactivityTimeout;
while (currentNode != null)
{
if (state == State.InactivityTimeout)
{
// InactivityTimeout assertion
if (Is11Assertion(currentNode, ReliableSessionPolicyStrings.InactivityTimeout))
{
SetInactivityTimeout(settings, ReadMillisecondsAttribute(currentNode, true), currentNode.LocalName);
state = State.AcknowledgementInterval;
currentNode = SkipToNode(assertionChildren);
continue;
}
}
// AcknowledgementInterval assertion
if (Is11Assertion(currentNode, ReliableSessionPolicyStrings.AcknowledgementInterval))
{
SetAcknowledgementInterval(settings, ReadMillisecondsAttribute(currentNode, true), currentNode.LocalName);
// ignore the rest
break;
}
if (state == State.AcknowledgementInterval)
{
// ignore the rest
break;
}
currentNode = SkipToNode(assertionChildren);
}
// Schema allows arbitrary elements from now on, ignore everything else
}
private static void ProcessReliableSessionFeb2005Assertion(XmlElement element, ReliableSessionBindingElement settings)
{
// Version
settings.ReliableMessagingVersion = ReliableMessagingVersion.WSReliableMessagingFebruary2005;
IEnumerator nodes = element.ChildNodes.GetEnumerator();
XmlNode currentNode = SkipToNode(nodes);
// InactivityTimeout assertion
if (IsFeb2005Assertion(currentNode, ReliableSessionPolicyStrings.InactivityTimeout))
{
SetInactivityTimeout(settings, ReadMillisecondsAttribute(currentNode, true), currentNode.LocalName);
currentNode = SkipToNode(nodes);
}
// BaseRetransmissionInterval assertion is read but ignored
if (IsFeb2005Assertion(currentNode, ReliableSessionPolicyStrings.BaseRetransmissionInterval))
{
ReadMillisecondsAttribute(currentNode, false);
currentNode = SkipToNode(nodes);
}
// ExponentialBackoff assertion is read but ignored
if (IsFeb2005Assertion(currentNode, ReliableSessionPolicyStrings.ExponentialBackoff))
{
currentNode = SkipToNode(nodes);
}
// AcknowledgementInterval assertion
if (IsFeb2005Assertion(currentNode, ReliableSessionPolicyStrings.AcknowledgementInterval))
{
SetAcknowledgementInterval(settings, ReadMillisecondsAttribute(currentNode, true), currentNode.LocalName);
}
// Schema allows arbitrary elements from now on, ignore everything else
}
private static void ProcessWsrm11Policy(MetadataImporter importer, XmlNode node, ReliableSessionBindingElement settings)
{
XmlElement element = ThrowIfNotPolicyElement(node, ReliableMessagingVersion.WSReliableMessaging11);
IEnumerable<IEnumerable<XmlElement>> alternatives = importer.NormalizePolicy(new XmlElement[] { element });
List<Wsrm11PolicyAlternative> wsrmAlternatives = new List<Wsrm11PolicyAlternative>();
foreach (IEnumerable<XmlElement> alternative in alternatives)
{
Wsrm11PolicyAlternative wsrm11Policy = Wsrm11PolicyAlternative.ImportAlternative(importer, alternative);
wsrmAlternatives.Add(wsrm11Policy);
}
if (wsrmAlternatives.Count == 0)
{
// No specific policy other than turn on WS-RM.
return;
}
foreach (Wsrm11PolicyAlternative wsrmAlternative in wsrmAlternatives)
{
// The only policy setting that affects the binding is the InOrder assurance.
// Even that setting does not affect the binding since InOrder is a server delivery assurance.
// Transfer any that is valid.
if (wsrmAlternative.HasValidPolicy)
{
wsrmAlternative.TransferSettings(settings);
return;
}
}
// Found only invalid policy.
// This throws an exception about security since that is the only invalid policy we have.
Wsrm11PolicyAlternative.ThrowInvalidBindingException();
}
private static TimeSpan ReadMillisecondsAttribute(XmlNode wsrmNode, bool convertToTimeSpan)
{
XmlAttribute millisecondsAttribute = wsrmNode.Attributes[ReliableSessionPolicyStrings.Milliseconds];
if (millisecondsAttribute == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(string.Format(SRServiceModel.RequiredAttributeIsMissing, ReliableSessionPolicyStrings.Milliseconds, wsrmNode.LocalName, ReliableSessionPolicyStrings.ReliableSessionName)));
UInt64 milliseconds = 0;
Exception innerException = null;
try
{
milliseconds = XmlConvert.ToUInt64(millisecondsAttribute.Value);
}
catch (FormatException exception)
{
innerException = exception;
}
catch (OverflowException exception)
{
innerException = exception;
}
if (innerException != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(string.Format(SRServiceModel.RequiredMillisecondsAttributeIncorrect, wsrmNode.LocalName), innerException));
if (convertToTimeSpan)
{
TimeSpan interval;
try
{
interval = TimeSpan.FromMilliseconds(Convert.ToDouble(milliseconds));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(string.Format(SRServiceModel.MillisecondsNotConvertibleToBindingRange, wsrmNode.LocalName), exception));
}
return interval;
}
else
{
return default(TimeSpan);
}
}
private static void SetInactivityTimeout(ReliableSessionBindingElement settings, TimeSpan inactivityTimeout, string localName)
{
try
{
settings.InactivityTimeout = inactivityTimeout;
}
catch (ArgumentOutOfRangeException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(string.Format(SRServiceModel.MillisecondsNotConvertibleToBindingRange, localName), exception));
}
}
private static void SetAcknowledgementInterval(ReliableSessionBindingElement settings, TimeSpan acknowledgementInterval, string localName)
{
try
{
settings.AcknowledgementInterval = acknowledgementInterval;
}
catch (ArgumentOutOfRangeException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(string.Format(SRServiceModel.MillisecondsNotConvertibleToBindingRange, localName), exception));
}
}
private static bool ShouldSkipNodeType(XmlNodeType type)
{
return (type == XmlNodeType.Comment || type == XmlNodeType.SignificantWhitespace || type == XmlNodeType.Whitespace || type == XmlNodeType.Notation);
}
private static XmlNode SkipToNode(IEnumerator nodes)
{
while (nodes.MoveNext())
{
XmlNode currentNode = (XmlNode)nodes.Current;
if (ShouldSkipNodeType(currentNode.NodeType))
continue;
return currentNode;
}
return null;
}
private static XmlElement ThrowIfNotPolicyElement(XmlNode node, ReliableMessagingVersion reliableMessagingVersion)
{
string policyLocalName = MetadataStrings.WSPolicy.Elements.Policy;
if (!IsElement(node, MetadataStrings.WSPolicy.NamespaceUri, policyLocalName)
&& !IsElement(node, MetadataStrings.WSPolicy.NamespaceUri15, policyLocalName))
{
string wsrmPrefix = (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
? ReliableSessionPolicyStrings.ReliableSessionFebruary2005Prefix
: ReliableSessionPolicyStrings.ReliableSession11Prefix;
string exceptionString = (node == null)
? string.Format(SRServiceModel.ElementRequired, wsrmPrefix,
ReliableSessionPolicyStrings.ReliableSessionName, MetadataStrings.WSPolicy.Prefix,
MetadataStrings.WSPolicy.Elements.Policy)
: string.Format(SRServiceModel.ElementFound, wsrmPrefix,
ReliableSessionPolicyStrings.ReliableSessionName, MetadataStrings.WSPolicy.Prefix,
MetadataStrings.WSPolicy.Elements.Policy, node.LocalName, node.NamespaceURI);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(exceptionString));
}
return (XmlElement)node;
}
private class Wsrm11PolicyAlternative
{
private bool _hasValidPolicy = true;
private bool _isOrdered = false;
public bool HasValidPolicy
{
get
{
return _hasValidPolicy;
}
}
public static Wsrm11PolicyAlternative ImportAlternative(MetadataImporter importer,
IEnumerable<XmlElement> alternative)
{
State state = State.Security;
Wsrm11PolicyAlternative wsrmPolicy = new Wsrm11PolicyAlternative();
foreach (XmlElement node in alternative)
{
if (state == State.Security)
{
state = State.DeliveryAssurance;
if (wsrmPolicy.TryImportSequenceSTR(node))
{
continue;
}
}
if (state == State.DeliveryAssurance)
{
state = State.Done;
if (wsrmPolicy.TryImportDeliveryAssurance(importer, node))
{
continue;
}
}
string exceptionString = string.Format(SRServiceModel.UnexpectedXmlChildNode,
node.LocalName,
node.NodeType,
ReliableSessionPolicyStrings.ReliableSessionName);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(exceptionString));
}
return wsrmPolicy;
}
public static void ThrowInvalidBindingException()
{
string exceptionString = string.Format(SRServiceModel.AssertionNotSupported,
ReliableSessionPolicyStrings.ReliableSession11Prefix,
ReliableSessionPolicyStrings.SequenceTransportSecurity);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(exceptionString));
}
public void TransferSettings(ReliableSessionBindingElement settings)
{
settings.Ordered = _isOrdered;
}
private bool TryImportSequenceSTR(XmlElement node)
{
string wsrmNs = ReliableSessionPolicyStrings.ReliableSession11Namespace;
if (IsElement(node, wsrmNs, ReliableSessionPolicyStrings.SequenceSTR))
{
return true;
}
if (IsElement(node, wsrmNs, ReliableSessionPolicyStrings.SequenceTransportSecurity))
{
_hasValidPolicy = false;
return true;
}
return false;
}
private bool TryImportDeliveryAssurance(MetadataImporter importer, XmlElement node)
{
string wsrmNs = ReliableSessionPolicyStrings.ReliableSession11Namespace;
if (!IsElement(node, wsrmNs, ReliableSessionPolicyStrings.DeliveryAssurance))
{
return false;
}
// Policy
IEnumerator policyNodes = node.ChildNodes.GetEnumerator();
XmlNode policyNode = SkipToNode(policyNodes);
XmlElement policyElement = ThrowIfNotPolicyElement(policyNode, ReliableMessagingVersion.WSReliableMessaging11);
IEnumerable<IEnumerable<XmlElement>> alternatives = importer.NormalizePolicy(new XmlElement[] { policyElement });
foreach (IEnumerable<XmlElement> alternative in alternatives)
{
State state = State.Assurance;
foreach (XmlElement element in alternative)
{
if (state == State.Assurance)
{
state = State.Order;
if (!IsElement(element, wsrmNs, ReliableSessionPolicyStrings.ExactlyOnce)
&& !IsElement(element, wsrmNs, ReliableSessionPolicyStrings.AtMostOnce)
&& !IsElement(element, wsrmNs, ReliableSessionPolicyStrings.AtMostOnce))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(string.Format(
SRServiceModel.DeliveryAssuranceRequired,
wsrmNs,
element.LocalName,
element.NamespaceURI)));
}
// Found required DeliveryAssurance, ignore the value and skip to InOrder
continue;
}
if (state == State.Order)
{
state = State.Done;
// InOrder
if (IsElement(element, wsrmNs, ReliableSessionPolicyStrings.InOrder))
{
// set ordered
if (!_isOrdered)
{
_isOrdered = true;
}
continue;
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(string.Format(
SRServiceModel.UnexpectedXmlChildNode,
element.LocalName,
element.NodeType,
ReliableSessionPolicyStrings.DeliveryAssurance)));
}
if (state == State.Assurance)
{
string exceptionString = string.Format(SRServiceModel.DeliveryAssuranceRequiredNothingFound, wsrmNs);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(exceptionString));
}
}
policyNode = SkipToNode(policyNodes);
if (policyNode != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(string.Format(
SRServiceModel.UnexpectedXmlChildNode,
policyNode.LocalName,
policyNode.NodeType,
node.LocalName)));
}
return true;
}
}
private enum State
{
Security,
DeliveryAssurance,
Assurance,
Order,
InactivityTimeout,
AcknowledgementInterval,
Done,
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
// ReSharper disable once CheckNamespace
namespace WebTrackr.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator _simpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return _simpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
var genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
var collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
var closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
var dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
var closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
var genericArgs = type.GetGenericArguments();
var parameterValues = new object[genericArgs.Length];
var failedToCreateTuple = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
var result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
var genericArgs = keyValuePairType.GetGenericArguments();
var typeK = genericArgs[0];
var typeV = genericArgs[1];
var objectGenerator = new ObjectGenerator();
var keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
var valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
var result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
var type = arrayType.GetElementType();
var result = Array.CreateInstance(type, size);
var areAllElementsNull = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
var typeK = typeof(object);
var typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
var genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
var result = Activator.CreateInstance(dictionaryType);
var addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
var containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
var containsKey = (bool)containsMethod.Invoke(result, new[] { newKey });
if (!containsKey)
{
var newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
var possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
var isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
var listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
var argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
var asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return ((IEnumerable)list).AsQueryable();
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
var type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
var result = Activator.CreateInstance(collectionType);
var addMethod = collectionType.GetMethod("Add");
var areAllElementsNull = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
var type = nullableType.GetGenericArguments()[0];
var objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
var defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var objectGenerator = new ObjectGenerator();
foreach (var property in properties)
{
if (property.CanWrite)
{
var propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
var objectGenerator = new ObjectGenerator();
foreach (var field in fields)
{
var fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => index + 0.1 },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index => String.Format(CultureInfo.CurrentCulture, "sample string {0}", index)
},
{
typeof(TimeSpan), index => TimeSpan.FromTicks(1234567)
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index => new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index))
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Editors;
using Umbraco.Cms.Core.PropertyEditors.ValueConverters;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Extensions;
using File = System.IO.File;
namespace Umbraco.Cms.Core.PropertyEditors
{
/// <summary>
/// The value editor for the image cropper property editor.
/// </summary>
internal class ImageCropperPropertyValueEditor : DataValueEditor // TODO: core vs web?
{
private readonly ILogger<ImageCropperPropertyValueEditor> _logger;
private readonly MediaFileManager _mediaFileManager;
private readonly ContentSettings _contentSettings;
private readonly IDataTypeService _dataTypeService;
public ImageCropperPropertyValueEditor(
DataEditorAttribute attribute,
ILogger<ImageCropperPropertyValueEditor> logger,
MediaFileManager mediaFileSystem,
ILocalizedTextService localizedTextService,
IShortStringHelper shortStringHelper,
IOptions<ContentSettings> contentSettings,
IJsonSerializer jsonSerializer,
IIOHelper ioHelper,
IDataTypeService dataTypeService)
: base(localizedTextService, shortStringHelper, jsonSerializer, ioHelper, attribute)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_mediaFileManager = mediaFileSystem ?? throw new ArgumentNullException(nameof(mediaFileSystem));
_contentSettings = contentSettings.Value;
_dataTypeService = dataTypeService;
}
/// <summary>
/// This is called to merge in the prevalue crops with the value that is saved - similar to the property value converter for the front-end
/// </summary>
public override object ToEditor(IProperty property, string culture = null, string segment = null)
{
var val = property.GetValue(culture, segment);
if (val == null) return null;
ImageCropperValue value;
try
{
value = JsonConvert.DeserializeObject<ImageCropperValue>(val.ToString());
}
catch
{
value = new ImageCropperValue { Src = val.ToString() };
}
var dataType = _dataTypeService.GetDataType(property.PropertyType.DataTypeId);
if (dataType?.Configuration != null)
value.ApplyConfiguration(dataType.ConfigurationAs<ImageCropperConfiguration>());
return value;
}
/// <summary>
/// Converts the value received from the editor into the value can be stored in the database.
/// </summary>
/// <param name="editorValue">The value received from the editor.</param>
/// <param name="currentValue">The current value of the property</param>
/// <returns>The converted value.</returns>
/// <remarks>
/// <para>The <paramref name="currentValue"/> is used to re-use the folder, if possible.</para>
/// <para>editorValue.Value is used to figure out editorFile and, if it has been cleared, remove the old file - but
/// it is editorValue.AdditionalData["files"] that is used to determine the actual file that has been uploaded.</para>
/// </remarks>
public override object FromEditor(ContentPropertyData editorValue, object currentValue)
{
// Get the current path
var currentPath = string.Empty;
try
{
var svalue = currentValue as string;
var currentJson = string.IsNullOrWhiteSpace(svalue) ? null : JObject.Parse(svalue);
if (currentJson != null && currentJson.TryGetValue("src", out var src))
{
currentPath = src.Value<string>();
}
}
catch (Exception ex)
{
// For some reason the value is invalid so continue as if there was no value there
_logger.LogWarning(ex, "Could not parse current db value to a JObject.");
}
if (string.IsNullOrWhiteSpace(currentPath) == false)
currentPath = _mediaFileManager.FileSystem.GetRelativePath(currentPath);
// Get the new JSON and file path
var editorFile = string.Empty;
if (editorValue.Value is JObject editorJson)
{
// Populate current file
if (editorJson["src"] != null)
{
editorFile = editorJson["src"].Value<string>();
}
// Clean up redundant/default data
ImageCropperValue.Prune(editorJson);
}
else
{
editorJson = null;
}
// ensure we have the required guids
var cuid = editorValue.ContentKey;
if (cuid == Guid.Empty) throw new Exception("Invalid content key.");
var puid = editorValue.PropertyTypeKey;
if (puid == Guid.Empty) throw new Exception("Invalid property type key.");
// editorFile is empty whenever a new file is being uploaded
// or when the file is cleared (in which case editorJson is null)
// else editorFile contains the unchanged value
var uploads = editorValue.Files;
if (uploads == null) throw new Exception("Invalid files.");
var file = uploads.Length > 0 ? uploads[0] : null;
if (file == null) // not uploading a file
{
// if editorFile is empty then either there was nothing to begin with,
// or it has been cleared and we need to remove the file - else the
// value is unchanged.
if (string.IsNullOrWhiteSpace(editorFile) && string.IsNullOrWhiteSpace(currentPath) == false)
{
_mediaFileManager.FileSystem.DeleteFile(currentPath);
return null; // clear
}
return editorJson?.ToString(Formatting.None); // unchanged
}
// process the file
var filepath = editorJson == null ? null : ProcessFile(file, cuid, puid);
// remove all temp files
foreach (ContentPropertyFile f in uploads)
{
File.Delete(f.TempFilePath);
}
// remove current file if replaced
if (currentPath != filepath && string.IsNullOrWhiteSpace(currentPath) == false)
{
_mediaFileManager.FileSystem.DeleteFile(currentPath);
}
// update json and return
if (editorJson == null) return null;
editorJson["src"] = filepath == null ? string.Empty : _mediaFileManager.FileSystem.GetUrl(filepath);
return editorJson.ToString(Formatting.None);
}
private string ProcessFile(ContentPropertyFile file, Guid cuid, Guid puid)
{
// process the file
// no file, invalid file, reject change
if (UploadFileTypeValidator.IsValidFileExtension(file.FileName, _contentSettings) == false)
{
return null;
}
// get the filepath
// in case we are using the old path scheme, try to re-use numbers (bah...)
var filepath = _mediaFileManager.GetMediaPath(file.FileName, cuid, puid); // fs-relative path
using (var filestream = File.OpenRead(file.TempFilePath))
{
// TODO: Here it would make sense to do the auto-fill properties stuff but the API doesn't allow us to do that right
// since we'd need to be able to return values for other properties from these methods
_mediaFileManager.FileSystem.AddFile(filepath, filestream, true); // must overwrite!
}
return filepath;
}
public override string ConvertDbToString(IPropertyType propertyType, object value)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
return null;
// if we don't have a json structure, we will get it from the property type
var val = value.ToString();
if (val.DetectIsJson())
return val;
// more magic here ;-(
var configuration = _dataTypeService.GetDataType(propertyType.DataTypeId).ConfigurationAs<ImageCropperConfiguration>();
var crops = configuration?.Crops ?? Array.Empty<ImageCropperConfiguration.Crop>();
return JsonConvert.SerializeObject(new
{
src = val,
crops = crops
}, new JsonSerializerSettings()
{
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore
});
}
}
}
| |
// cassandra-sharp - high performance .NET driver for Apache Cassandra
// Copyright (c) 2011-2013 Pierre Chalamet
//
// 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 cqlplus.Parser
{
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
#region Scanner
public class Scanner
{
private readonly List<TokenType> SkipList; // tokens to be skipped
private readonly List<TokenType> Tokens;
public int CurrentColumn;
public int CurrentLine;
public int CurrentPosition;
public int EndPos = 0;
public string Input;
private Token LookAheadToken;
public Dictionary<TokenType, Regex> Patterns;
public List<Token> Skipped; // tokens that were skipped
public int StartPos = 0;
public Scanner()
{
Regex regex;
Patterns = new Dictionary<TokenType, Regex>();
Tokens = new List<TokenType>();
LookAheadToken = null;
Skipped = new List<Token>();
SkipList = new List<TokenType>();
SkipList.Add(TokenType.WHITESPACE);
SkipList.Add(TokenType.COMMENT2);
regex = new Regex(@"\s+", RegexOptions.Compiled);
Patterns.Add(TokenType.WHITESPACE, regex);
Tokens.Add(TokenType.WHITESPACE);
regex = new Regex(@"/\*[^*]*\*+(?:[^/*][^*]*\*+)*/", RegexOptions.Compiled);
Patterns.Add(TokenType.COMMENT2, regex);
Tokens.Add(TokenType.COMMENT2);
regex = new Regex(@"^$", RegexOptions.Compiled);
Patterns.Add(TokenType.EOF, regex);
Tokens.Add(TokenType.EOF);
regex = new Regex(@"@?\""(\""\""|[^\""])*\""", RegexOptions.Compiled);
Patterns.Add(TokenType.STRING, regex);
Tokens.Add(TokenType.STRING);
regex = new Regex(@"\b", RegexOptions.Compiled);
Patterns.Add(TokenType.WORD, regex);
Tokens.Add(TokenType.WORD);
regex = new Regex(@"[+-]?[0-9]+", RegexOptions.Compiled);
Patterns.Add(TokenType.INTEGER, regex);
Tokens.Add(TokenType.INTEGER);
regex = new Regex(@"[a-zA-Z_][a-zA-Z0-9_]*", RegexOptions.Compiled);
Patterns.Add(TokenType.IDENTIFIER, regex);
Tokens.Add(TokenType.IDENTIFIER);
regex = new Regex("!", RegexOptions.Compiled);
Patterns.Add(TokenType.BANG, regex);
Tokens.Add(TokenType.BANG);
regex = new Regex("[.]+", RegexOptions.Compiled);
Patterns.Add(TokenType.EVERYTHING, regex);
Tokens.Add(TokenType.EVERYTHING);
regex = new Regex("[^!]+[.]*", RegexOptions.Compiled);
Patterns.Add(TokenType.EVERYTHING_BUT_START_WITH_BANG, regex);
Tokens.Add(TokenType.EVERYTHING_BUT_START_WITH_BANG);
regex = new Regex("-", RegexOptions.Compiled);
Patterns.Add(TokenType.MINUS, regex);
Tokens.Add(TokenType.MINUS);
regex = new Regex("=", RegexOptions.Compiled);
Patterns.Add(TokenType.EQUAL, regex);
Tokens.Add(TokenType.EQUAL);
}
public void Init(string input)
{
Input = input;
StartPos = 0;
EndPos = 0;
CurrentLine = 0;
CurrentColumn = 0;
CurrentPosition = 0;
LookAheadToken = null;
}
public Token GetToken(TokenType type)
{
Token t = new Token(StartPos, EndPos);
t.Type = type;
return t;
}
/// <summary>
/// executes a lookahead of the next token
/// and will advance the scan on the input string
/// </summary>
/// <returns></returns>
public Token Scan(params TokenType[] expectedtokens)
{
Token tok = LookAhead(expectedtokens); // temporarely retrieve the lookahead
LookAheadToken = null; // reset lookahead token, so scanning will continue
StartPos = tok.EndPos;
EndPos = tok.EndPos; // set the tokenizer to the new scan position
return tok;
}
/// <summary>
/// returns token with longest best match
/// </summary>
/// <returns></returns>
public Token LookAhead(params TokenType[] expectedtokens)
{
int i;
int startpos = StartPos;
Token tok = null;
List<TokenType> scantokens;
// this prevents double scanning and matching
// increased performance
if (LookAheadToken != null
&& LookAheadToken.Type != TokenType._UNDETERMINED_
&& LookAheadToken.Type != TokenType._NONE_)
{
return LookAheadToken;
}
// if no scantokens specified, then scan for all of them (= backward compatible)
if (expectedtokens.Length == 0)
{
scantokens = Tokens;
}
else
{
scantokens = new List<TokenType>(expectedtokens);
scantokens.AddRange(SkipList);
}
do
{
int len = -1;
TokenType index = (TokenType) int.MaxValue;
string input = Input.Substring(startpos);
tok = new Token(startpos, EndPos);
for (i = 0; i < scantokens.Count; i++)
{
Regex r = Patterns[scantokens[i]];
Match m = r.Match(input);
if (m.Success && m.Index == 0 && ((m.Length > len) || (scantokens[i] < index && m.Length == len)))
{
len = m.Length;
index = scantokens[i];
}
}
if (index >= 0 && len >= 0)
{
tok.EndPos = startpos + len;
tok.Text = Input.Substring(tok.StartPos, len);
tok.Type = index;
}
else if (tok.StartPos < tok.EndPos - 1)
{
tok.Text = Input.Substring(tok.StartPos, 1);
}
if (SkipList.Contains(tok.Type))
{
startpos = tok.EndPos;
Skipped.Add(tok);
}
else
{
// only assign to non-skipped tokens
tok.Skipped = Skipped; // assign prior skips to this token
Skipped = new List<Token>(); //reset skips
}
} while (SkipList.Contains(tok.Type));
LookAheadToken = tok;
return tok;
}
}
#endregion
#region Token
public enum TokenType
{
//Non terminal tokens:
_NONE_ = 0,
_UNDETERMINED_ = 1,
//Non terminal tokens:
String = 2,
Identifier = 3,
Integer = 4,
Value = 5,
Parameters = 6,
CommandWithParameters = 7,
CqlCommand = 8,
Start = 9,
//Terminal tokens:
WHITESPACE = 10,
COMMENT2 = 11,
EOF = 12,
STRING = 13,
WORD = 14,
INTEGER = 15,
IDENTIFIER = 16,
BANG = 17,
EVERYTHING = 18,
EVERYTHING_BUT_START_WITH_BANG = 19,
MINUS = 20,
EQUAL = 21
}
public class Token
{
[XmlAttribute]
public TokenType Type;
private int endpos;
private int startpos;
public Token()
: this(0, 0)
{
}
public Token(int start, int end)
{
Type = TokenType._UNDETERMINED_;
startpos = start;
endpos = end;
Text = ""; // must initialize with empty string, may cause null reference exceptions otherwise
Value = null;
}
// contains all prior skipped symbols
public int StartPos
{
get { return startpos; }
set { startpos = value; }
}
public int Length
{
get { return endpos - startpos; }
}
public int EndPos
{
get { return endpos; }
set { endpos = value; }
}
public string Text { get; set; }
public List<Token> Skipped { get; set; }
public object Value { get; set; }
public void UpdateRange(Token token)
{
if (token.StartPos < startpos)
{
startpos = token.StartPos;
}
if (token.EndPos > endpos)
{
endpos = token.EndPos;
}
}
public override string ToString()
{
if (Text != null)
{
return Type.ToString() + " '" + Text + "'";
}
else
{
return Type.ToString();
}
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Telerik.Charting;
using Telerik.Core;
using Telerik.UI.Xaml.Controls.Chart;
using Telerik.UI.Xaml.Controls.Chart.Primitives;
using Windows.Devices.Input;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
namespace Telerik.UI.Xaml.Controls.Chart
{
/// <summary>
/// Represents a behavior that adds two lines in <see cref="RadChartBase"/>'s render surface. The two lines intersect at the center of the closest data point found.
/// </summary>
public class ChartTrackBallBehavior : ChartBehavior
{
/// <summary>
/// Identifies the <see cref="LineStyle"/> property.
/// </summary>
public static readonly DependencyProperty LineStyleProperty =
DependencyProperty.Register(nameof(LineStyle), typeof(Style), typeof(ChartTrackBallBehavior), new PropertyMetadata(null, OnLineStylePropertyChanged));
/// <summary>
/// Identifies the <see cref="InfoStyle"/> property.
/// </summary>
public static readonly DependencyProperty InfoStyleProperty =
DependencyProperty.Register(nameof(InfoStyle), typeof(Style), typeof(ChartTrackBallBehavior), null);
/// <summary>
/// Identifies the <see cref="IntersectionTemplateProperty"/> dependency property.
/// </summary>
public static readonly DependencyProperty IntersectionTemplateProperty =
DependencyProperty.RegisterAttached("IntersectionTemplate", typeof(DataTemplate), typeof(ChartTrackBallBehavior), new PropertyMetadata(null));
/// <summary>
/// Identifies the <see cref="TrackInfoTemplateProperty"/> dependency property.
/// </summary>
public static readonly DependencyProperty TrackInfoTemplateProperty =
DependencyProperty.RegisterAttached("TrackInfoTemplate", typeof(DataTemplate), typeof(ChartTrackBallBehavior), new PropertyMetadata(null));
internal List<ContentPresenter> individualTrackInfos;
private static readonly Style DefaultLineStyle;
private TrackBallLineControl lineControl;
private TrackBallSnapMode snapMode;
private bool showInfo = true;
private bool showIntersectionPoints;
private bool visualsDisplayed;
private Point position;
private TrackInfoMode infoMode = TrackInfoMode.Individual;
private TrackBallInfoControl trackInfoControl;
private List<ContentPresenter> intersectionPoints;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "The static DefaultLineStyle field requires additional initialization.")]
static ChartTrackBallBehavior()
{
DefaultLineStyle = new Style(typeof(Polyline));
DefaultLineStyle.Setters.Add(new Setter(Polyline.StrokeThicknessProperty, 2));
DefaultLineStyle.Setters.Add(new Setter(Polyline.StrokeProperty, new SolidColorBrush(Colors.Gray)));
}
/// <summary>
/// Initializes a new instance of the <see cref="ChartTrackBallBehavior"/> class.
/// </summary>
public ChartTrackBallBehavior()
{
this.lineControl = new TrackBallLineControl();
this.snapMode = TrackBallSnapMode.ClosestPoint;
this.trackInfoControl = new TrackBallInfoControl(this);
this.intersectionPoints = new List<ContentPresenter>(4);
this.individualTrackInfos = new List<ContentPresenter>(4);
}
/// <summary>
/// Occurs when a track info is updated, just before the UI that represents it is updated.
/// Allows custom information to be displayed.
/// </summary>
public event EventHandler<TrackBallInfoEventArgs> TrackInfoUpdated;
/// <summary>
/// Gets or sets the <see cref="Style"/> that defines the appearance of the line displayed by a <see cref="ChartTrackBallBehavior"/> instance.
/// The style should target the <see cref="Windows.UI.Xaml.Shapes.Polyline"/> type.
/// </summary>
public Style LineStyle
{
get
{
return this.GetValue(LineStyleProperty) as Style;
}
set
{
this.SetValue(LineStyleProperty, value);
}
}
/// <summary>
/// Gets or sets the <see cref="Style"/> that defines the appearance of the TrackInfo control displayed by a <see cref="ChartTrackBallBehavior"/> instance.
/// The style should target the <see cref="Telerik.UI.Xaml.Controls.Chart.Primitives.TrackBallInfoControl"/> type.
/// </summary>
public Style InfoStyle
{
get
{
return this.GetValue(InfoStyleProperty) as Style;
}
set
{
this.SetValue(InfoStyleProperty, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether a visual information for all the closest data points will be displayed.
/// </summary>
public bool ShowInfo
{
get
{
return this.showInfo;
}
set
{
this.showInfo = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether a visual representation for all the intersection points will be displayed.
/// </summary>
public bool ShowIntersectionPoints
{
get
{
return this.showIntersectionPoints;
}
set
{
this.showIntersectionPoints = value;
}
}
/// <summary>
/// Gets or sets the how this behavior should snap to the closest to a physical location data points.
/// </summary>
public TrackBallSnapMode SnapMode
{
get
{
return this.snapMode;
}
set
{
this.snapMode = value;
}
}
/// <summary>
/// Gets or sets a value indicating the track information displayed by the behavior.
/// </summary>
public TrackInfoMode InfoMode
{
get
{
return this.infoMode;
}
set
{
this.infoMode = value;
}
}
/// <summary>
/// Gets the control used to display Polyline shape that renders the trackball line. Exposed for testing purposes.
/// </summary>
internal TrackBallLineControl LineControl
{
get
{
return this.lineControl;
}
}
/// <summary>
/// Gets the control used to display the track information. Exposed for testing purposes.
/// </summary>
internal TrackBallInfoControl InfoControl
{
get
{
return this.trackInfoControl;
}
}
/// <summary>
/// Gets the list with all the content presenters used to visualize intersection points. Exposed for testing purposes.
/// </summary>
internal List<ContentPresenter> IntersectionPoints
{
get
{
return this.intersectionPoints;
}
}
/// <summary>
/// Gets the position of the track ball. Exposed for testing purposes.
/// </summary>
internal Point Position
{
get
{
return this.position;
}
}
internal override ManipulationModes DesiredManipulationMode
{
get
{
return ManipulationModes.TranslateX | ManipulationModes.TranslateY;
}
}
/// <summary>
/// Gets the <see cref="DataTemplate"/> instance for the specified object instance.
/// </summary>
/// <remarks>
/// This template is used to highlight the intersection point of each <see cref="ChartSeries"/> instance with the trackball line.
/// </remarks>
public static DataTemplate GetIntersectionTemplate(DependencyObject instance)
{
if (instance == null)
{
throw new ArgumentNullException();
}
return instance.GetValue(IntersectionTemplateProperty) as DataTemplate;
}
/// <summary>
/// Sets the <see cref="DataTemplate"/> instance for the specified object instance.
/// </summary>
/// <remarks>
/// This template is used to highlight the intersection point of each <see cref="ChartSeries"/> instance with the trackball line.
/// </remarks>
/// <param name="instance">The object instance to apply the template to.</param>
/// <param name="value">The specified <see cref="DataTemplate"/> instance.</param>
public static void SetIntersectionTemplate(DependencyObject instance, DataTemplate value)
{
if (instance == null)
{
throw new ArgumentNullException();
}
instance.SetValue(IntersectionTemplateProperty, value);
}
/// <summary>
/// Gets the <see cref="DataTemplate"/> instance for the provided object instance.
/// </summary>
/// <remarks>
/// This template defines the appearance of the information for the currently hit data point of each <see cref="ChartSeries"/>.
/// </remarks>
public static DataTemplate GetTrackInfoTemplate(DependencyObject instance)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
return instance.GetValue(TrackInfoTemplateProperty) as DataTemplate;
}
/// <summary>
/// Gets the specified <see cref="DataTemplate"/> instance to the provided object instance.
/// </summary>
/// <remarks>
/// This template defines the appearance of the information for the currently hit data point of each <see cref="ChartSeries"/>.
/// </remarks>
public static void SetTrackInfoTemplate(DependencyObject instance, DataTemplate value)
{
if (instance == null)
{
throw new ArgumentNullException();
}
instance.SetValue(TrackInfoTemplateProperty, value);
}
/// <summary>
/// Exposed for testing purposes.
/// </summary>
internal void HandleDrag(Point currentPosition)
{
this.position = currentPosition;
if (!this.visualsDisplayed)
{
this.PrepareVisuals();
}
this.UpdateVisuals();
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerEntered"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerEntered(PointerRoutedEventArgs args)
{
base.OnPointerEntered(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
this.HandleDrag(args.GetCurrentPoint(this.chart).Position);
args.Handled = true;
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerMoved"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerMoved(PointerRoutedEventArgs args)
{
base.OnPointerMoved(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
if (args.Pointer.IsInContact)
{
return;
}
this.HandleDrag(args.GetCurrentPoint(this.chart).Position);
args.Handled = true;
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerPressed"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerPressed(PointerRoutedEventArgs args)
{
base.OnPointerPressed(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
if (args.Pointer.PointerDeviceType != PointerDeviceType.Touch)
{
this.EndTrack();
}
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerExited"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerExited(PointerRoutedEventArgs args)
{
base.OnPointerExited(args);
this.EndTrack();
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.HoldCompleted"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnHoldCompleted(HoldingRoutedEventArgs args)
{
base.OnHoldCompleted(args);
this.EndTrack();
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerReleased"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerReleased(PointerRoutedEventArgs args)
{
base.OnPointerReleased(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
this.EndTrack();
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.HoldStarted"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnHoldStarted(HoldingRoutedEventArgs args)
{
base.OnHoldStarted(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
this.HandleDrag(args.GetPosition(this.chart));
args.Handled = true;
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.ManipulationDelta"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnManipulationDelta(ManipulationDeltaRoutedEventArgs args)
{
base.OnManipulationDelta(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
if (!this.chart.isInHold || args.IsInertial)
{
return;
}
this.HandleDrag(args.Position);
args.Handled = true;
}
/// <summary>
/// A callback from the owning <see cref="RadChartBase"/> instance that notifies for a completed UpdateUI pass.
/// </summary>
protected internal override void OnChartUIUpdated()
{
base.OnChartUIUpdated();
if (this.visualsDisplayed)
{
this.UpdateVisuals();
}
}
/// <summary>
/// This method is called when this behavior is removed from the chart.
/// </summary>
protected override void OnDetached()
{
base.OnDetached();
this.chart.adornerLayer.LayoutUpdated -= this.OnAdornerLayerLayoutUpdated;
if (this.chart.adornerLayer.Children.Contains(this.lineControl))
{
this.chart.adornerLayer.Children.Remove(this.lineControl);
}
if (this.chart.adornerLayer.Children.Contains(this.trackInfoControl))
{
this.chart.adornerLayer.Children.Remove(this.trackInfoControl);
}
foreach (ContentPresenter presenter in this.intersectionPoints)
{
this.chart.adornerLayer.Children.Remove(presenter);
}
}
private static void OnLineStylePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ChartTrackBallBehavior behavior = d as ChartTrackBallBehavior;
behavior.lineControl.LineStyle = e.NewValue as Style;
}
private void HideVisuals()
{
this.visualsDisplayed = false;
this.lineControl.Visibility = Visibility.Collapsed;
this.lineControl.Line.Points.Clear();
this.trackInfoControl.Visibility = Visibility.Collapsed;
foreach (ContentPresenter presenter in this.intersectionPoints)
{
presenter.Visibility = Visibility.Collapsed;
}
foreach (ContentPresenter presenter in this.individualTrackInfos)
{
presenter.Visibility = Visibility.Collapsed;
}
}
private void PrepareVisuals()
{
this.visualsDisplayed = true;
this.lineControl.Visibility = Visibility.Visible;
if (!this.chart.adornerLayer.Children.Contains(this.lineControl))
{
this.chart.adornerLayer.Children.Add(this.lineControl);
}
if (!this.showInfo)
{
return;
}
this.AdornerLayer.LayoutUpdated += this.OnAdornerLayerLayoutUpdated;
if (this.infoMode == TrackInfoMode.Individual)
{
return;
}
Style style = this.InfoStyle;
if (style != null)
{
this.trackInfoControl.Style = style;
}
if (!this.chart.adornerLayer.Children.Contains(this.trackInfoControl))
{
this.chart.adornerLayer.Children.Add(this.trackInfoControl);
this.trackInfoControl.SetValue(Canvas.ZIndexProperty, this.trackInfoControl.DefaultZIndex);
}
this.trackInfoControl.Visibility = Visibility.Visible;
}
private void UpdateVisuals()
{
ChartDataContext context = this.GetDataContext(this.position, true);
if (context.ClosestDataPoint != null)
{
var point = context.ClosestDataPoint.DataPoint as CategoricalDataPoint;
if (point != null)
{
List<DataPointInfo> points = null;
if (point.Category == null)
{
points = context.DataPoints.Where(c => c.DataPoint is CategoricalDataPoint &&
((CategoricalDataPoint)c.DataPoint).Category == null).ToList();
}
else
{
// select points only with the same category. TODO: Refactor this.
points = context.DataPoints.Where(c =>
c.DataPoint is CategoricalDataPoint &&
point.Category.Equals(((CategoricalDataPoint)c.DataPoint).Category)
).ToList();
}
context = new ChartDataContext(points, context.ClosestDataPoint);
}
}
this.UpdateLine(context);
this.UpdateIntersectionPoints(context);
this.UpdateTrackInfo(context);
}
private void UpdateTrackInfo(ChartDataContext context)
{
if (!this.showInfo)
{
return;
}
// arrange the track content
if (this.lineControl.Line.Points.Count == 0)
{
Debug.Assert(false, "Must have line points initialized.");
return;
}
TrackBallInfoEventArgs args = new TrackBallInfoEventArgs(context);
if (this.TrackInfoUpdated != null)
{
this.TrackInfoUpdated(this, args);
}
if (this.infoMode == TrackInfoMode.Multiple)
{
this.trackInfoControl.Update(args);
}
else
{
this.BuildIndividualTrackInfos(context);
}
}
private void UpdateLine(ChartDataContext context)
{
this.lineControl.Line.Points.Clear();
Point plotOrigin = this.chart.PlotOrigin;
if (this.snapMode == TrackBallSnapMode.AllClosePoints)
{
Point[] points = new Point[context.DataPoints.Count];
int index = 0;
foreach (DataPointInfo info in context.DataPoints)
{
Point center = info.DataPoint.Center();
center.X += plotOrigin.X;
center.Y += plotOrigin.Y;
points[index++] = center;
}
Array.Sort(points, new PointYComparer());
foreach (Point point in points)
{
this.lineControl.Line.Points.Add(point);
}
}
else if (this.snapMode == TrackBallSnapMode.ClosestPoint && context.ClosestDataPoint != null)
{
Point center = context.ClosestDataPoint.DataPoint.Center();
center.X += plotOrigin.X;
center.Y += plotOrigin.Y;
// Temporary fix for NAN values. Remove when the chart starts to support null values.
if (double.IsNaN(center.X))
{
center.X = 0;
}
if (double.IsNaN(center.Y))
{
center.Y = this.chart.chartArea.plotArea.layoutSlot.Bottom;
}
this.lineControl.Line.Points.Add(center);
}
RadRect plotArea = this.chart.chartArea.plotArea.layoutSlot;
Point topPoint;
Point bottomPoint;
if (this.lineControl.Line.Points.Count > 0)
{
topPoint = new Point(this.lineControl.Line.Points[0].X, plotArea.Y);
bottomPoint = new Point(this.lineControl.Line.Points[this.lineControl.Line.Points.Count - 1].X, plotArea.Bottom);
}
else
{
topPoint = new Point(this.position.X, plotArea.Y);
bottomPoint = new Point(this.position.X, plotArea.Bottom);
}
this.lineControl.Line.Points.Insert(0, topPoint);
this.lineControl.Line.Points.Insert(this.lineControl.Line.Points.Count, bottomPoint);
}
private void UpdateIntersectionPoints(ChartDataContext context)
{
if (!this.showIntersectionPoints)
{
return;
}
int index = 0;
Point plotOrigin = this.chart.PlotOrigin;
foreach (ContentPresenter presenter in this.intersectionPoints)
{
presenter.Visibility = Visibility.Collapsed;
}
foreach (DataPointInfo info in context.DataPoints)
{
DataTemplate template = GetIntersectionTemplate(info.Series);
if (template == null)
{
continue;
}
ContentPresenter presenter = this.GetIntersectionPointPresenter(index);
presenter.Visibility = Visibility.Visible;
presenter.Content = info;
presenter.ContentTemplate = template;
presenter.Measure(RadChartBase.InfinitySize);
Point center = info.DataPoint.Center();
Size desiredSize = presenter.DesiredSize;
Canvas.SetLeft(presenter, center.X - Math.Abs(plotOrigin.X) - (desiredSize.Width / 2));
Canvas.SetTop(presenter, center.Y - Math.Abs(plotOrigin.Y) - (desiredSize.Height / 2));
index++;
}
}
private ContentPresenter GetIntersectionPointPresenter(int index)
{
if (index < this.intersectionPoints.Count)
{
return this.intersectionPoints[index];
}
ContentPresenter visual = new ContentPresenter();
this.chart.adornerLayer.Children.Add(visual);
this.intersectionPoints.Add(visual);
return visual;
}
private void OnAdornerLayerLayoutUpdated(object sender, object args)
{
if (this.lineControl.Line.Points.Count == 0)
{
return;
}
if (this.infoMode == TrackInfoMode.Multiple)
{
// fit the info control into the plot area
RadRect plotArea = this.chart.chartArea.plotArea.layoutSlot;
Point topPoint = new Point(this.lineControl.Line.Points[0].X, plotArea.Y);
double left = topPoint.X - (int)(this.trackInfoControl.ActualWidth / 2);
left = Math.Min(left, this.chart.ActualWidth - this.trackInfoControl.ActualWidth);
left = Math.Max(0, left);
Canvas.SetLeft(this.trackInfoControl, left);
Canvas.SetTop(this.trackInfoControl, topPoint.Y);
// update the top line point to reach the bottom edge of the track info
topPoint.Y += this.trackInfoControl.ActualHeight;
this.lineControl.Line.Points[0] = topPoint;
}
else
{
this.ArrangeIndividualTrackInfos();
}
}
private void BuildIndividualTrackInfos(ChartDataContext context)
{
int index = 0;
List<DataPointInfo> infos = new List<DataPointInfo>(context.DataPoints);
infos.Sort(new DataPointInfoYComparer());
foreach (DataPointInfo info in infos)
{
ContentPresenter presenter;
if (this.individualTrackInfos.Count > index)
{
presenter = this.individualTrackInfos[index];
presenter.Visibility = Visibility.Visible;
}
else
{
presenter = new ContentPresenter();
this.individualTrackInfos.Add(presenter);
this.chart.adornerLayer.Children.Add(presenter);
}
presenter.Content = info;
presenter.ContentTemplate = GetTrackInfoTemplate(info.Series);
index++;
}
while (index < this.individualTrackInfos.Count)
{
this.individualTrackInfos[index].Visibility = Visibility.Collapsed;
index++;
}
}
private void ArrangeIndividualTrackInfos()
{
int index = 0;
Point plotOrigin = this.chart.PlotOrigin;
foreach (ContentPresenter presenter in this.individualTrackInfos)
{
if (presenter.Visibility == Visibility.Collapsed)
{
continue;
}
DataPointInfo info = presenter.Content as DataPointInfo;
RadRect layoutSlot = info.DataPoint.layoutSlot;
Size size = presenter.DesiredSize;
HorizontalAlignment horizontalAlign = index % 2 == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
double x = 0;
switch (horizontalAlign)
{
case HorizontalAlignment.Left:
x = layoutSlot.X - size.Width;
break;
case HorizontalAlignment.Center:
x = layoutSlot.Center.X - size.Width / 2;
break;
case HorizontalAlignment.Right:
x = layoutSlot.Right;
break;
}
double y = layoutSlot.Center.Y - size.Height / 2;
Canvas.SetLeft(presenter, x + plotOrigin.X);
Canvas.SetTop(presenter, y + plotOrigin.Y);
index++;
}
}
private void EndTrack()
{
this.chart.adornerLayer.LayoutUpdated -= this.OnAdornerLayerLayoutUpdated;
this.HideVisuals();
}
private class PointYComparer : IComparer<Point>
{
public int Compare(Point x, Point y)
{
return x.Y.CompareTo(y.Y);
}
}
private class DataPointInfoYComparer : IComparer<DataPointInfo>
{
public int Compare(DataPointInfo x, DataPointInfo y)
{
if (x == null || y == null)
{
return 0;
}
return x.DataPoint.layoutSlot.Center.Y.CompareTo(y.DataPoint.layoutSlot.Center.Y);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Plugin.MediaManager.Abstractions.Enums;
using Plugin.MediaManager.Abstractions.EventArguments;
namespace Plugin.MediaManager.Abstractions.Implementations
{
/// <summary>
/// Implementation for MediaManager
/// </summary>
public abstract class MediaManagerBase : IMediaManager, IDisposable
{
private IPlaybackManager _currentPlaybackManager;
private Func<IMediaFile, Task> _onBeforePlay;
private IPlaybackManager CurrentPlaybackManager
{
get
{
if (_currentPlaybackManager == null && CurrentMediaFile != null) SetCurrentPlayer(CurrentMediaFile.Type);
if (_currentPlaybackManager != null)
{
_currentPlaybackManager.RequestHeaders = RequestHeaders;
}
return _currentPlaybackManager;
}
}
public virtual IMediaQueue MediaQueue { get; set; } = new MediaQueue();
public abstract IAudioPlayer AudioPlayer { get; set; }
public abstract IVideoPlayer VideoPlayer { get; set; }
public abstract IMediaNotificationManager MediaNotificationManager { get; set; }
public abstract IMediaExtractor MediaExtractor { get; set; }
public abstract IVolumeManager VolumeManager { get; set; }
public IPlaybackController PlaybackController { get; set; }
public MediaPlayerStatus Status => CurrentPlaybackManager?.Status ?? MediaPlayerStatus.Stopped;
public TimeSpan Position => CurrentPlaybackManager?.Position ?? TimeSpan.Zero;
public TimeSpan Duration => CurrentPlaybackManager?.Duration ?? TimeSpan.Zero;
public TimeSpan Buffered => CurrentPlaybackManager?.Buffered ?? TimeSpan.Zero;
public event StatusChangedEventHandler StatusChanged;
public event PlayingChangedEventHandler PlayingChanged;
public event BufferingChangedEventHandler BufferingChanged;
public event MediaFinishedEventHandler MediaFinished;
public event MediaFailedEventHandler MediaFailed;
public event MediaFileChangedEventHandler MediaFileChanged;
public event MediaFileFailedEventHandler MediaFileFailed;
private IMediaFile CurrentMediaFile => MediaQueue.Current;
public Dictionary<string, string> RequestHeaders { get; set; } = new Dictionary<string, string>();
private bool _startedPlaying;
protected MediaManagerBase()
{
PlaybackController = new PlaybackController(this);
}
public async Task PlayNext()
{
await RaiseMediaFileFailedEventOnException(async () =>
{
if (MediaQueue.HasNext())
{
MediaQueue.SetNextAsCurrent();
await PlayCurrent();
}
else
{
MediaQueue.SetIndexAsCurrent(0);
await PrepareCurrentAndThen(async () =>
{
await CurrentPlaybackManager.Play();
await CurrentPlaybackManager.Pause();
await Seek(TimeSpan.Zero);
});
OnMediaFileChanged(this, new MediaFileChangedEventArgs(CurrentMediaFile));
}
});
}
public async Task PlayPrevious()
{
await RaiseMediaFileFailedEventOnException(async () =>
{
MediaQueue.SetPreviousAsCurrent();
await PlayCurrent();
});
}
public async Task PlayByPosition(int index)
{
MediaQueue.SetIndexAsCurrent(index);
await Play(CurrentMediaFile);
}
public Task Play(string url)
{
var mediaFile = new MediaFile(url);
return Play(mediaFile);
}
public Task Play(string url, MediaFileType fileType)
{
var mediaFile = new MediaFile(url, fileType);
return Play(mediaFile);
}
public Task Play(string url, MediaFileType fileType, ResourceAvailability availability)
{
var mediaFile = new MediaFile(url, fileType, availability);
return Play(mediaFile);
}
public async Task Play(IMediaFile mediaFile = null)
{
if (mediaFile == null)
{
if (Status == MediaPlayerStatus.Paused)
{
await Resume();
return;
}
mediaFile = CurrentMediaFile;
}
if (_currentPlaybackManager != null && Status == MediaPlayerStatus.Failed)
{
await PlayNext();
return;
}
if (mediaFile == null)
{
await Play(MediaQueue);
return;
}
if (!MediaQueue.Contains(mediaFile))
MediaQueue.Add(mediaFile);
MediaQueue.SetTrackAsCurrent(mediaFile);
await RaiseMediaFileFailedEventOnException(async () =>
{
await PlayCurrent();
});
MediaNotificationManager?.StartNotification(mediaFile);
}
/// <summary>
/// Adds all MediaFiles to the Queue and starts playing the first item
/// </summary>
/// <param name="mediaFiles"></param>
/// <returns></returns>
public async Task Play(IEnumerable<IMediaFile> mediaFiles)
{
MediaQueue.Clear();
MediaQueue.AddRange(mediaFiles);
// Play from index 0
MediaQueue.SetIndexAsCurrent(0);
await PlayCurrent();
MediaNotificationManager?.StartNotification(CurrentMediaFile);
}
public void SetOnBeforePlay(Func<IMediaFile, Task> beforePlay)
{
_onBeforePlay = beforePlay;
}
public async Task Pause()
{
IPlaybackManager currentPlaybackManager = CurrentPlaybackManager;
if (currentPlaybackManager != null)
await currentPlaybackManager.Pause();
}
public async Task Stop()
{
if (CurrentPlaybackManager == null)
return;
await CurrentPlaybackManager.Stop();
MediaNotificationManager?.StopNotifications();
}
public async Task Seek(TimeSpan position)
{
if (CurrentPlaybackManager == null)
return;
await CurrentPlaybackManager.Seek(position);
MediaNotificationManager?.UpdateNotifications(CurrentMediaFile, Status);
}
private async Task Resume()
{
if (CurrentPlaybackManager == null)
return;
await CurrentPlaybackManager.Play(CurrentMediaFile);
}
private async Task RaiseMediaFileFailedEventOnException(Func<Task> action)
{
try
{
await action();
}
catch (Exception ex)
{
OnMediaFileFailed(CurrentPlaybackManager, new MediaFileFailedEventArgs(ex, CurrentMediaFile));
}
}
private Task PlayCurrent()
{
return PrepareCurrentAndThen(() => CurrentPlaybackManager.Play(CurrentMediaFile));
}
private async Task PrepareCurrentAndThen(Func<Task> action = null)
{
await ExecuteOnBeforePlay();
if (CurrentPlaybackManager != null)
await Task.WhenAll(
action?.Invoke(),
ExtractMediaInformation(CurrentMediaFile));
}
private async Task ExecuteOnBeforePlay()
{
var beforePlayTask = _onBeforePlay?.Invoke(CurrentMediaFile);
if (beforePlayTask != null) await beforePlayTask;
}
private void SetCurrentPlayer(MediaFileType fileType)
{
if (_currentPlaybackManager != null)
{
RemoveEventHandlers();
}
switch (fileType)
{
case MediaFileType.Audio:
_currentPlaybackManager = AudioPlayer;
break;
case MediaFileType.Video:
_currentPlaybackManager = VideoPlayer;
break;
default:
throw new ArgumentOutOfRangeException();
}
AddEventHandlers();
}
private async Task ExtractMediaInformation(IMediaFile mediaFile)
{
if (mediaFile.ExtractMetadata)
{
var index = MediaQueue.IndexOf(mediaFile);
await MediaExtractor.ExtractMediaInfo(mediaFile);
if (index >= 0)
{
MediaQueue[index] = mediaFile;
}
OnMediaFileChanged(CurrentPlaybackManager, new MediaFileChangedEventArgs(mediaFile));
}
}
private void OnStatusChanged(object sender, StatusChangedEventArgs e)
{
if (sender != CurrentPlaybackManager) return;
if (Status == MediaPlayerStatus.Playing)
{
_startedPlaying = false;
}
MediaNotificationManager?.UpdateNotifications(CurrentMediaFile, e.Status);
StatusChanged?.Invoke(sender, e);
}
private void OnPlayingChanged(object sender, PlayingChangedEventArgs e)
{
if (sender == CurrentPlaybackManager)
{
if (!_startedPlaying && Duration != TimeSpan.Zero)
{
MediaNotificationManager?.UpdateNotifications(MediaQueue.Current, Status);
_startedPlaying = true;
}
PlayingChanged?.Invoke(sender, e);
}
}
private async void OnMediaFinished(object sender, MediaFinishedEventArgs e)
{
if (sender != CurrentPlaybackManager) return;
MediaFinished?.Invoke(sender, e);
if (MediaQueue.Repeat == RepeatType.RepeatOne)
{
await Seek(TimeSpan.Zero);
await Resume();
}
else
{
await PlayNext();
}
}
private void OnMediaFailed(object sender, MediaFailedEventArgs e)
{
if (sender == CurrentPlaybackManager)
{
OnStatusChanged(sender, new StatusChangedEventArgs(MediaPlayerStatus.Failed));
}
MediaFailed?.Invoke(sender, e);
}
private void OnBufferingChanged(object sender, BufferingChangedEventArgs e)
{
if (sender == CurrentPlaybackManager)
BufferingChanged?.Invoke(sender, e);
}
private void OnMediaFileChanged(object sender, MediaFileChangedEventArgs e)
{
if (CurrentMediaFile?.Url == e?.File?.Url)
MediaNotificationManager?.UpdateNotifications(e?.File, Status);
MediaFileChanged?.Invoke(sender, e);
}
private void OnMediaFileFailed(object sender, MediaFileFailedEventArgs e)
{
if (sender == CurrentPlaybackManager)
{
OnStatusChanged(sender, new StatusChangedEventArgs(MediaPlayerStatus.Failed));
MediaFileFailed?.Invoke(sender, e);
}
}
private void AddEventHandlers()
{
_currentPlaybackManager.BufferingChanged += OnBufferingChanged;
_currentPlaybackManager.MediaFailed += OnMediaFailed;
_currentPlaybackManager.MediaFinished += OnMediaFinished;
_currentPlaybackManager.PlayingChanged += OnPlayingChanged;
_currentPlaybackManager.StatusChanged += OnStatusChanged;
}
private void RemoveEventHandlers()
{
_currentPlaybackManager.BufferingChanged -= OnBufferingChanged;
_currentPlaybackManager.MediaFailed -= OnMediaFailed;
_currentPlaybackManager.MediaFinished -= OnMediaFinished;
_currentPlaybackManager.PlayingChanged -= OnPlayingChanged;
_currentPlaybackManager.StatusChanged -= OnStatusChanged;
}
#region IDisposable
// Flag: Has Dispose already been called?
bool disposed = false;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any other managed objects here.
RemoveEventHandlers();
}
// Free any unmanaged objects here.
//
disposed = true;
}
~MediaManagerBase()
{
Dispose(false);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Internal.Web.Utils;
using Microsoft.VisualStudio.ExtensionsExplorer;
using NuGet.Dialog.Extensions;
using NuGet.VisualStudio;
namespace NuGet.Dialog.Providers {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal abstract class PackagesTreeNodeBase : IVsExtensionsTreeNode, IVsPageDataSource, IVsSortDataSource, IVsProgressPaneConsumer, INotifyPropertyChanged, IVsMessagePaneConsumer {
// The number of extensions to show per page.
private const int DefaultItemsPerPage = 10;
// We cache the query until it changes (due to sort order or search)
private IEnumerable<IPackage> _query;
private int _totalCount;
private IList<IVsExtension> _extensions;
private IList<IVsExtensionsTreeNode> _nodes;
private int _totalPages = 1, _currentPage = 1;
private bool _progressPaneActive;
private bool _isExpanded;
private bool _isSelected;
private bool _loadingInProgress;
private CancellationTokenSource _currentCancellationSource;
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler<EventArgs> PageDataChanged;
protected PackagesTreeNodeBase(IVsExtensionsTreeNode parent, PackagesProviderBase provider) {
Debug.Assert(provider != null);
Parent = parent;
Provider = provider;
PageSize = DefaultItemsPerPage;
}
protected PackagesProviderBase Provider {
get;
private set;
}
private IVsProgressPane ProgressPane {
get;
set;
}
private IVsMessagePane MessagePane {
get;
set;
}
/// <summary>
/// Name of this node
/// </summary>
public abstract string Name {
get;
}
public bool IsSearchResultsNode {
get;
set;
}
/// <summary>
/// Select node (UI) property
/// This property maps to TreeViewItem.IsSelected
/// </summary>
public bool IsSelected {
get {
return _isSelected;
}
set {
if (_isSelected != value) {
_isSelected = value;
OnNotifyPropertyChanged("IsSelected");
}
}
}
/// <summary>
/// Expand node (UI) property
/// This property maps to TreeViewItem.IsExpanded
/// </summary>
public bool IsExpanded {
get {
return _isExpanded;
}
set {
if (_isExpanded != value) {
_isExpanded = value;
OnNotifyPropertyChanged("IsExpanded");
}
}
}
/// <summary>
/// List of templates at this node
/// </summary>
public IList<IVsExtension> Extensions {
get {
if (_extensions == null) {
EnsureExtensionCollection();
LoadPage(1);
}
return _extensions;
}
}
/// <summary>
/// Children at this node
/// </summary>
public IList<IVsExtensionsTreeNode> Nodes {
get {
if (_nodes == null) {
_nodes = new ObservableCollection<IVsExtensionsTreeNode>();
}
return _nodes;
}
}
/// <summary>
/// Parent of this node
/// </summary>
public IVsExtensionsTreeNode Parent {
get;
private set;
}
public int TotalPages {
get {
return _totalPages;
}
internal set {
_totalPages = value;
NotifyPropertyChanged();
}
}
public int CurrentPage {
get {
return _currentPage;
}
internal set {
_currentPage = value;
NotifyPropertyChanged();
}
}
// this is for unit testing
internal Action QueryExecutionCallback {
get;
set;
}
internal int PageSize {
get;
set;
}
/// <summary>
/// Refresh the list of packages belong to this node
/// </summary>
public void Refresh() {
LoadPage(CurrentPage);
}
public override string ToString() {
return Name;
}
/// <summary>
/// Get all packages belonging to this node.
/// </summary>
/// <returns></returns>
public abstract IQueryable<IPackage> GetPackages();
/// <summary>
/// Helper function to raise property changed events
/// </summary>
/// <param name="info"></param>
private void NotifyPropertyChanged() {
if (PageDataChanged != null) {
PageDataChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// Loads the packages in the specified page.
/// </summary>
/// <param name="pageNumber"></param>
public void LoadPage(int pageNumber) {
if (pageNumber < 1) {
throw new ArgumentOutOfRangeException("pageNumber", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 1));
}
Trace.WriteLine("Dialog loading page: " + pageNumber);
if (_loadingInProgress) {
return;
}
EnsureExtensionCollection();
ShowProgressPane();
// avoid more than one loading occurring at the same time
_loadingInProgress = true;
_currentCancellationSource = new CancellationTokenSource();
TaskScheduler uiScheduler = null;
try {
uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
}
catch (InvalidOperationException) {
// FromCurrentSynchronizationContext() fails when running from unit test
uiScheduler = TaskScheduler.Default;
}
Task.Factory.StartNew(
(state) => ExecuteAsync(pageNumber, _currentCancellationSource.Token),
_currentCancellationSource,
_currentCancellationSource.Token).ContinueWith(QueryExecutionCompleted, uiScheduler);
}
private void EnsureExtensionCollection() {
if (_extensions == null) {
_extensions = new ObservableCollection<IVsExtension>();
}
}
/// <summary>
/// Called when user clicks on the Cancel button in the progress pane.
/// </summary>
private void CancelCurrentExtensionQuery() {
Trace.WriteLine("Cancelling pending extensions query.");
if (_currentCancellationSource != null) {
_currentCancellationSource.Cancel();
_loadingInProgress = false;
}
}
/// <summary>
/// This method executes on background thread.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We want to show error message inside the dialog, rather than blowing up VS.")]
private LoadPageResult ExecuteAsync(int pageNumber, CancellationToken token) {
token.ThrowIfCancellationRequested();
if (_query == null) {
IQueryable<IPackage> query = GetPackages();
token.ThrowIfCancellationRequested();
// Execute the total count query
_totalCount = query.Count();
token.ThrowIfCancellationRequested();
// Apply the ordering then sort by id
IQueryable<IPackage> orderedQuery = ApplyOrdering(query).ThenBy(p => p.Id);
// Buffer 3 page sizes
_query = orderedQuery.AsBufferedEnumerable(PageSize * 3);
}
IList<IPackage> packages = _query.DistinctLast(PackageEqualityComparer.Id, PackageComparer.Version)
.Skip((pageNumber - 1) * PageSize)
.Take(PageSize)
.ToList();
if (packages.Count < PageSize) {
_totalCount = (pageNumber - 1) * PageSize + packages.Count;
}
token.ThrowIfCancellationRequested();
return new LoadPageResult(packages, pageNumber, _totalCount);
}
private IOrderedQueryable<IPackage> ApplyOrdering(IQueryable<IPackage> query) {
// If the default sort is null then fall back to rating
if (Provider.CurrentSort == null) {
return query.OrderByDescending(p => p.Rating);
}
// Order by the current descriptor
return query.SortBy<IPackage>(Provider.CurrentSort, typeof(RecentPackage));
}
public IList<IVsSortDescriptor> GetSortDescriptors() {
// Get the sort descriptor from the provider
return Provider.SortDescriptors;
}
protected void ResetQuery() {
_query = null;
}
public bool SortSelectionChanged(IVsSortDescriptor selectedDescriptor) {
Provider.CurrentSort = selectedDescriptor as PackageSortDescriptor;
if (Provider.CurrentSort != null) {
// If we changed the sort order then invalidate the cache.
ResetQuery();
// Reload the first page since the sort order changed
LoadPage(1);
return true;
}
return false;
}
private void QueryExecutionCompleted(Task<LoadPageResult> task) {
// If a task throws, the exception must be handled or the Exception
// property must be accessed or the exception will tear down the process when finalized
Exception exception = task.Exception;
var cancellationSource = (CancellationTokenSource)task.AsyncState;
if (cancellationSource != _currentCancellationSource) {
return;
}
_loadingInProgress = false;
// Only process the result if this node is still selected.
if (IsSelected) {
if (task.IsCanceled) {
HideProgressPane();
}
else if (task.IsFaulted) {
// show error message in the Message pane
ShowMessagePane((exception.InnerException ?? exception).Message);
}
else {
LoadPageResult result = task.Result;
IEnumerable<IPackage> packages = result.Packages;
_extensions.Clear();
foreach (IPackage package in packages) {
_extensions.Add(Provider.CreateExtension(package));
}
if (_extensions.Count > 0) {
_extensions[0].IsSelected = true;
}
int totalPages = (result.TotalCount + PageSize - 1) / PageSize;
int pageNumber = result.PageNumber;
TotalPages = Math.Max(1, totalPages);
CurrentPage = Math.Max(1, pageNumber);
HideProgressPane();
}
}
if (QueryExecutionCallback != null) {
QueryExecutionCallback();
}
}
protected void OnNotifyPropertyChanged(string propertyName) {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public void SetProgressPane(IVsProgressPane progressPane) {
ProgressPane = progressPane;
}
public void SetMessagePane(IVsMessagePane messagePane) {
MessagePane = messagePane;
}
protected bool ShowProgressPane() {
if (ProgressPane != null) {
_progressPaneActive = true;
return ProgressPane.Show(new CancelProgressCallback(CancelCurrentExtensionQuery), true);
}
else {
return false;
}
}
protected void HideProgressPane() {
if (_progressPaneActive && ProgressPane != null) {
ProgressPane.Close();
_progressPaneActive = false;
}
}
protected bool ShowMessagePane(string message) {
if (MessagePane != null) {
MessagePane.SetMessageThreadSafe(message);
return MessagePane.Show();
}
else {
return false;
}
}
/// <summary>
/// Called when this node is opened.
/// </summary>
internal void OnOpened() {
if (!Provider.SuppressNextRefresh) {
Provider.SelectedNode = this;
if (Provider.RefreshOnNodeSelection && !this.IsSearchResultsNode) {
Refresh();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
using System.Text.RegularExpressions;
using NUnit.Framework.Constraints;
namespace OpenQA.Selenium
{
[TestFixture]
public class TextHandlingTest : DriverTestFixture
{
private string newLine = "\r\n";
[Test]
public void ShouldReturnTheTextContentOfASingleElementWithNoChildren()
{
driver.Url = simpleTestPage;
string selectText = driver.FindElement(By.Id("oneline")).Text;
Assert.AreEqual(selectText, "A single line of text");
string getText = driver.FindElement(By.Id("oneline")).Text;
Assert.AreEqual(getText, "A single line of text");
}
[Test]
public void ShouldReturnTheEntireTextContentOfChildElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("multiline")).Text;
Assert.IsTrue(text.Contains("A div containing"));
Assert.IsTrue(text.Contains("More than one line of text"));
Assert.IsTrue(text.Contains("and block level elements"));
}
[Test]
public void ShouldIgnoreScriptElements()
{
driver.Url = javascriptEnhancedForm;
IWebElement labelForUsername = driver.FindElement(By.Id("labelforusername"));
string text = labelForUsername.Text;
Assert.AreEqual(labelForUsername.FindElements(By.TagName("script")).Count, 1);
Assert.IsFalse(text.Contains("document.getElementById"));
Assert.AreEqual(text, "Username:");
}
[Test]
public void ShouldRepresentABlockLevelElementAsANewline()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("multiline")).Text;
Assert.IsTrue(text.StartsWith("A div containing" + newLine));
Assert.IsTrue(text.Contains("More than one line of text" + newLine));
Assert.IsTrue(text.EndsWith("and block level elements"));
}
[Test]
public void ShouldCollapseMultipleWhitespaceCharactersIntoASingleSpace()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("lotsofspaces")).Text;
Assert.AreEqual(text, "This line has lots of spaces.");
}
[Test]
public void ShouldTrimText()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("multiline")).Text;
Assert.IsTrue(text.StartsWith("A div containing"));
Assert.IsTrue(text.EndsWith("block level elements"));
}
[Test]
public void ShouldConvertANonBreakingSpaceIntoANormalSpaceCharacter()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("nbsp")).Text;
Assert.AreEqual(text, "This line has a non-breaking space");
}
[Test]
public void ShouldNotCollapseANonBreakingSpaces()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.Id("nbspandspaces"));
string text = element.Text;
Assert.AreEqual(text, "This line has a non-breaking space and spaces");
}
[Test]
public void ShouldNotTrimNonBreakingSpacesAtTheEndOfALineInTheMiddleOfText()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.Id("multilinenbsp"));
string text = element.Text;
string expectedStart = "These lines " + System.Environment.NewLine;
Assert.That(text, Is.StringStarting(expectedStart));
}
[Test]
public void ShouldNotTrimNonBreakingSpacesAtTheStartOfALineInTheMiddleOfText()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.Id("multilinenbsp"));
string text = element.Text;
string expectedContent = System.Environment.NewLine + " have";
Assert.That(text, Is.StringContaining(expectedContent));
}
[Test]
public void ShouldNotTrimTrailingNonBreakingSpacesInMultilineText()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.Id("multilinenbsp"));
string text = element.Text;
string expectedEnd = "trailing NBSPs ";
Assert.That(text, Is.StringEnding(expectedEnd));
}
[Test]
public void HavingInlineElementsShouldNotAffectHowTextIsReturned()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("inline")).Text;
Assert.AreEqual(text, "This line has text within elements that are meant to be displayed inline");
}
[Test]
public void ShouldReturnTheEntireTextOfInlineElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("span")).Text;
Assert.AreEqual(text, "An inline element");
}
[Test]
public void ShouldRetainTheFormatingOfTextWithinAPreElement()
{
driver.Url = simpleTestPage;
string text = driver.FindElement(By.Id("div-with-pre")).Text;
Assert.AreEqual("before pre" + System.Environment.NewLine +
" This section has a preformatted" + System.Environment.NewLine +
" text block " + System.Environment.NewLine +
" split in four lines" + System.Environment.NewLine +
" " + System.Environment.NewLine +
"after pre", text);
}
[Test]
public void ShouldBeAbleToSetMoreThanOneLineOfTextInATextArea()
{
driver.Url = formsPage;
IWebElement textarea = driver.FindElement(By.Id("withText"));
textarea.Clear();
string expectedText = "I like cheese" + newLine + newLine + "It's really nice";
textarea.SendKeys(expectedText);
string seenText = textarea.GetAttribute("value");
Assert.AreEqual(seenText, expectedText);
}
[Test]
public void ShouldBeAbleToEnterDatesAfterFillingInOtherValuesFirst()
{
driver.Url = formsPage;
IWebElement input = driver.FindElement(By.Id("working"));
string expectedValue = "10/03/2007 to 30/07/1993";
input.SendKeys(expectedValue);
string seenValue = input.GetAttribute("value");
Assert.AreEqual(seenValue, expectedValue);
}
[Test]
public void ShouldReturnEmptyStringWhenTextIsOnlySpaces()
{
driver.Url = (xhtmlTestPage);
string text = driver.FindElement(By.Id("spaces")).Text;
Assert.AreEqual(text, string.Empty);
}
[Test]
public void ShouldReturnEmptyStringWhenTextIsEmpty()
{
driver.Url = (xhtmlTestPage);
string text = driver.FindElement(By.Id("empty")).Text;
Assert.AreEqual(text, string.Empty);
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldReturnEmptyStringWhenTagIsSelfClosing()
{
driver.Url = (xhtmlFormPage);
string text = driver.FindElement(By.Id("self-closed")).Text;
Assert.AreEqual(text, string.Empty);
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldNotTrimSpacesWhenLineWraps()
{
driver.Url = simpleTestPage;
string text = driver.FindElement(By.XPath("//table/tbody/tr[1]/td[1]")).Text;
Assert.AreEqual("beforeSpace afterSpace", text);
}
[Test]
public void ShouldHandleSiblingBlockLevelElements()
{
driver.Url = simpleTestPage;
string text = driver.FindElement(By.Id("twoblocks")).Text;
Assert.AreEqual(text, "Some text" + newLine + "Some more text");
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldHandleNestedBlockLevelElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("nestedblocks")).Text;
Assert.AreEqual("Cheese" + newLine + "Some text" + newLine + "Some more text" + newLine
+ "and also" + newLine + "Brie", text);
}
[Test]
public void ShouldHandleWhitespaceInInlineElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("inlinespan")).Text;
Assert.AreEqual(text, "line has text");
}
[Test]
public void ReadALargeAmountOfData()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("macbeth.html");
string source = driver.PageSource.Trim().ToLower();
Assert.IsTrue(source.EndsWith("</html>"));
}
[Test]
public void GetTextWithLineBreakForInlineElement()
{
driver.Url = simpleTestPage;
IWebElement label = driver.FindElement(By.Id("label1"));
string labelText = label.Text;
Assert.IsTrue(new Regex("foo[\\n\\r]+bar").IsMatch(labelText));
}
[Test]
[Category("Javascript")]
public void ShouldOnlyIncludeVisibleText()
{
driver.Url = javascriptPage;
string empty = driver.FindElement(By.Id("suppressedParagraph")).Text;
string explicitText = driver.FindElement(By.Id("outer")).Text;
Assert.AreEqual(string.Empty, empty);
Assert.AreEqual("sub-element that is explicitly visible", explicitText);
}
[Test]
public void ShouldGetTextFromTableCells()
{
driver.Url = tables;
IWebElement tr = driver.FindElement(By.Id("hidden_text"));
String text = tr.Text;
Assert.IsTrue(text.Contains("some text"));
Assert.IsFalse(text.Contains("some more text"));
}
[Test]
public void TextOfAnInputFieldShouldBeEmpty()
{
driver.Url = formsPage;
IWebElement input = driver.FindElement(By.Id("inputWithText"));
Assert.AreEqual(string.Empty, input.Text);
}
[Test]
public void TextOfATextAreaShouldBeEqualToItsDefaultText()
{
driver.Url = formsPage;
IWebElement area = driver.FindElement(By.Id("withText"));
Assert.AreEqual("Example text", area.Text);
}
[Test]
[IgnoreBrowser(Browser.IE, "Fails on IE")]
[IgnoreBrowser(Browser.HtmlUnit, "Fails on IE")]
[IgnoreBrowser(Browser.Android, "untested")]
[IgnoreBrowser(Browser.IPhone, "untested")]
public void TextOfATextAreaShouldBeEqualToItsDefaultTextEvenAfterTyping()
{
driver.Url = formsPage;
IWebElement area = driver.FindElement(By.Id("withText"));
string oldText = area.Text;
area.SendKeys("New Text");
Assert.AreEqual(oldText, area.Text);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IE, "Fails on IE")]
[IgnoreBrowser(Browser.HtmlUnit, "Fails on IE")]
[IgnoreBrowser(Browser.Android, "untested")]
[IgnoreBrowser(Browser.IPhone, "untested")]
public void TextOfATextAreaShouldBeEqualToItsDefaultTextEvenAfterChangingTheValue()
{
driver.Url = formsPage;
IWebElement area = driver.FindElement(By.Id("withText"));
string oldText = area.GetAttribute("value");
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].value = arguments[1]", area, "New Text");
Assert.AreEqual(oldText, area.Text);
}
[Test]
public void ShouldGetTextWhichIsAValidJSONObject()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.Id("simpleJsonText"));
Assert.AreEqual("{a=\"b\", c=1, d=true}", element.Text);
//assertEquals("{a=\"b\", \"c\"=d, e=true, f=\\123\\\\g\\\\\"\"\"\\\'}", element.getText());
}
[Test]
public void ShouldGetTextWhichIsAValidComplexJSONObject()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.Id("complexJsonText"));
Assert.AreEqual("{a=\"\\\\b\\\\\\\"\'\\\'\"}", element.Text);
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
/// <summary>
/// This module loads and saves OpenSimulator inventory archives
/// </summary>
public class InventoryArchiverModule : IRegionModule, IInventoryArchiverModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get { return "Inventory Archiver Module"; } }
public bool IsSharedModule { get { return true; } }
/// <value>
/// Enable or disable checking whether the iar user is actually logged in
/// </value>
public bool DisablePresenceChecks { get; set; }
public event InventoryArchiveSaved OnInventoryArchiveSaved;
/// <summary>
/// The file to load and save inventory if no filename has been specified
/// </summary>
protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar";
/// <value>
/// Pending save completions initiated from the console
/// </value>
protected List<Guid> m_pendingConsoleSaves = new List<Guid>();
/// <value>
/// All scenes that this module knows about
/// </value>
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
private Scene m_aScene;
public InventoryArchiverModule() {}
public InventoryArchiverModule(bool disablePresenceChecks)
{
DisablePresenceChecks = disablePresenceChecks;
}
public void Initialise(Scene scene, IConfigSource source)
{
if (m_scenes.Count == 0)
{
scene.RegisterModuleInterface<IInventoryArchiverModule>(this);
OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted;
scene.AddCommand(
this, "load iar",
"load iar <first> <last> <inventory path> <password> [<archive path>]",
"Load user inventory archive.", HandleLoadInvConsoleCommand);
scene.AddCommand(
this, "save iar",
"save iar <first> <last> <inventory path> <password> [<archive path>]",
"Save user inventory archive.", HandleSaveInvConsoleCommand);
m_aScene = scene;
}
m_scenes[scene.RegionInfo.RegionID] = scene;
}
public void PostInitialise() {}
public void Close() {}
/// <summary>
/// Trigger the inventory archive saved event.
/// </summary>
protected internal void TriggerInventoryArchiveSaved(
Guid id, bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream,
Exception reportedException)
{
InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved;
if (handlerInventoryArchiveSaved != null)
handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException);
}
public bool ArchiveInventory(Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream)
{
if (m_scenes.Count > 0)
{
CachedUserInfo userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
if (CheckPresence(userInfo.UserProfile.ID))
{
try
{
new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute();
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: User {0} {1} not logged in to this region simulator",
userInfo.UserProfile.Name, userInfo.UserProfile.ID);
}
}
}
return false;
}
public bool ArchiveInventory(Guid id, string firstName, string lastName, string invPath, string pass, string savePath)
{
if (m_scenes.Count > 0)
{
CachedUserInfo userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
if (CheckPresence(userInfo.UserProfile.ID))
{
try
{
new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute();
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: User {0} {1} not logged in to this region simulator",
userInfo.UserProfile.Name, userInfo.UserProfile.ID);
}
}
}
return false;
}
public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream)
{
if (m_scenes.Count > 0)
{
CachedUserInfo userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
if (CheckPresence(userInfo.UserProfile.ID))
{
InventoryArchiveReadRequest request;
try
{
request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: User {0} {1} not logged in to this region simulator",
userInfo.UserProfile.Name, userInfo.UserProfile.ID);
}
}
}
return false;
}
public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, string loadPath)
{
if (m_scenes.Count > 0)
{
CachedUserInfo userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
if (CheckPresence(userInfo.UserProfile.ID))
{
InventoryArchiveReadRequest request;
try
{
request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: User {0} {1} not logged in to this region simulator",
userInfo.UserProfile.Name, userInfo.UserProfile.ID);
}
}
}
return false;
}
/// <summary>
/// Load inventory from an inventory file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams)
{
if (cmdparams.Length < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: usage is load iar <first name> <last name> <inventory path> <user password> [<load file path>]");
return;
}
m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME.");
string firstName = cmdparams[2];
string lastName = cmdparams[3];
string invPath = cmdparams[4];
string pass = cmdparams[5];
string loadPath = (cmdparams.Length > 6 ? cmdparams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}",
loadPath, invPath, firstName, lastName);
if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath))
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}",
loadPath, firstName, lastName);
}
/// <summary>
/// Save inventory to a file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
{
if (cmdparams.Length < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: usage is save iar <first name> <last name> <inventory path> <user password> [<save file path>]");
return;
}
m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME.");
string firstName = cmdparams[2];
string lastName = cmdparams[3];
string invPath = cmdparams[4];
string pass = cmdparams[5];
string savePath = (cmdparams.Length > 6 ? cmdparams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}",
savePath, invPath, firstName, lastName);
Guid id = Guid.NewGuid();
ArchiveInventory(id, firstName, lastName, invPath, pass, savePath);
lock (m_pendingConsoleSaves)
m_pendingConsoleSaves.Add(id);
}
private void SaveInvConsoleCommandCompleted(
Guid id, bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream,
Exception reportedException)
{
lock (m_pendingConsoleSaves)
{
if (m_pendingConsoleSaves.Contains(id))
m_pendingConsoleSaves.Remove(id);
else
return;
}
if (succeeded)
{
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0}", userInfo.UserProfile.Name);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Archive save for {0} failed - {1}",
userInfo.UserProfile.Name, reportedException.Message);
}
}
/// <summary>
/// Get user information for the given name.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="pass">User password</param>
/// <returns></returns>
protected CachedUserInfo GetUserInfo(string firstName, string lastName, string pass)
{
CachedUserInfo userInfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(firstName, lastName);
//m_aScene.CommsManager.UserService.GetUserProfile(firstName, lastName);
if (null == userInfo)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}",
firstName, lastName);
return null;
}
try
{
if (m_aScene.CommsManager.UserService.AuthenticateUserByPassword(userInfo.UserProfile.ID, pass))
{
return userInfo;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.",
firstName, lastName);
return null;
}
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e.Message);
return null;
}
}
/// <summary>
/// Notify the client of loaded nodes if they are logged in
/// </summary>
/// <param name="loadedNodes">Can be empty. In which case, nothing happens</param>
private void UpdateClientWithLoadedNodes(CachedUserInfo userInfo, List<InventoryNodeBase> loadedNodes)
{
if (loadedNodes.Count == 0)
return;
foreach (Scene scene in m_scenes.Values)
{
ScenePresence user = scene.GetScenePresence(userInfo.UserProfile.ID);
if (user != null && !user.IsChildAgent)
{
foreach (InventoryNodeBase node in loadedNodes)
{
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}",
// user.Name, node.Name);
user.ControllingClient.SendBulkUpdateInventory(node);
}
break;
}
}
}
/// <summary>
/// Check if the given user is present in any of the scenes.
/// </summary>
/// <param name="userId">The user to check</param>
/// <returns>true if the user is in any of the scenes, false otherwise</returns>
protected bool CheckPresence(UUID userId)
{
if (DisablePresenceChecks)
return true;
foreach (Scene scene in m_scenes.Values)
{
ScenePresence p;
if ((p = scene.GetScenePresence(userId)) != null)
{
p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false);
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Test;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Newtonsoft.Json.Linq;
using Xunit;
namespace ResourceGroups.Tests
{
public class LiveDeploymentTests : TestBase
{
const string DummyTemplateUri = "https://testtemplates.blob.core.windows.net/templates/dummytemplate.js";
const string GoodWebsiteTemplateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/201-web-app-github-deploy/azuredeploy.json";
const string BadTemplateUri = "https://testtemplates.blob.core.windows.net/templates/bad-website-1.js";
const string LocationWestEurope = "West Europe";
const string LocationSouthCentralUS = "South Central US";
public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
{
handler.IsPassThrough = true;
return this.GetResourceManagementClientWithHandler(context, handler);
}
// TODO: Fix
[Fact (Skip = "TODO: Re-record test")]
public void CreateDummyDeploymentTemplateWorks()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
var dictionary = new Dictionary<string, object> {
{"string", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"securestring", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"int", new Dictionary<string, object>() {
{"value", 42},
}},
{"bool", new Dictionary<string, object>() {
{"value", true},
}}
};
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = DummyTemplateUri
},
Parameters = dictionary,
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
JObject json = JObject.Parse(handler.Request);
Assert.NotNull(client.Deployments.Get(groupName, deploymentName));
}
}
[Fact()]
public void CreateDeploymentWithStringTemplateAndParameters()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account.json")),
Parameters = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account-parameters.json")),
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
var deployment = client.Deployments.Get(groupName, deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
}
}
[Fact]
public void CreateDeploymentAndValidateProperties()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(
@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
Assert.NotNull(deploymentCreateResult.Id);
Assert.Equal(deploymentName, deploymentCreateResult.Name);
TestUtilities.Wait(1000);
var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, null);
var deploymentGetResult = client.Deployments.Get(groupName, deploymentName);
Assert.NotEmpty(deploymentListResult);
Assert.Equal(deploymentName, deploymentGetResult.Name);
Assert.Equal(deploymentName, deploymentListResult.First().Name);
Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri);
Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri);
Assert.NotNull(deploymentGetResult.Properties.ProvisioningState);
Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState);
Assert.NotNull(deploymentGetResult.Properties.CorrelationId);
Assert.NotNull(deploymentListResult.First().Properties.CorrelationId);
}
}
[Fact]
public void ValidateGoodDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csres");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
//Action
var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
Assert.Equal(1, validationResult.Properties.Providers.Count);
Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty);
}
}
//TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void ValidateGoodDeploymentWithInlineTemplate()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = File.ReadAllText(Path.Combine("ScenarioTests", "good-website.json")),
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'siteLocation': {'value': 'westus'}, 'sku': {'value': 'Standard'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
//Action
var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
Assert.Equal(1, validationResult.Properties.Providers.Count);
Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty);
}
}
[Fact]
public void ValidateBadDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = BadTemplateUri,
},
Parameters =
JObject.Parse(@"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
var result = client.Deployments.Validate(groupName, deploymentName, parameters);
Assert.NotNull(result);
Assert.Equal("InvalidTemplate", result.Error.Code);
}
}
// TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void CreateDummyDeploymentProducesOperations()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
var dictionary = new Dictionary<string, object> {
{"string", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"securestring", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"int", new Dictionary<string, object>() {
{"value", 42},
}},
{"bool", new Dictionary<string, object>() {
{"value", true},
}}
};
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = DummyTemplateUri
},
Parameters = dictionary,
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csmr");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
// Wait until deployment completes
TestUtilities.Wait(30000);
var operations = client.DeploymentOperations.List(groupName, deploymentName, null);
Assert.True(operations.Any());
Assert.NotNull(operations.First().Id);
Assert.NotNull(operations.First().OperationId);
Assert.NotNull(operations.First().Properties);
}
}
// TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void ListDeploymentsWorksWithFilter()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'siteLocation': {'value': 'westus'}, 'sku': {'value': 'Standard'}}"),
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Running"));
if (null == deploymentListResult|| deploymentListResult.Count() == 0)
{
deploymentListResult = client.Deployments.ListByResourceGroup(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Accepted"));
}
var deploymentGetResult = client.Deployments.Get(groupName, deploymentName);
Assert.NotEmpty(deploymentListResult);
Assert.Equal(deploymentName, deploymentGetResult.Name);
Assert.Equal(deploymentName, deploymentListResult.First().Name);
Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri);
Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri);
Assert.NotNull(deploymentGetResult.Properties.ProvisioningState);
Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState);
Assert.NotNull(deploymentGetResult.Properties.CorrelationId);
Assert.NotNull(deploymentListResult.First().Properties.CorrelationId);
Assert.True(deploymentGetResult.Properties.Parameters.ToString().Contains("mctest0101"));
Assert.True(deploymentListResult.First().Properties.Parameters.ToString().Contains("mctest0101"));
}
}
[Fact]
public void CreateLargeWebDeploymentTemplateWorks()
{
var handler = new RecordedDelegatingHandler();
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string resourceName = TestUtilities.GenerateName("csmr");
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse("{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationSouthCentralUS });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
// Wait until deployment completes
TestUtilities.Wait(30000);
var operations = client.DeploymentOperations.List(groupName, deploymentName, null);
Assert.True(operations.Any());
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#if !NET_1_1
using System.Web.Compilation;
#endif
#if NET_1_1
using System.Reflection;
using System.Web.UI;
#endif
using System;
using System.IO;
//using System.Web;
using Common.Logging;
using Spring.Util;
using IHttpHandler = System.Web.IHttpHandler;
using HttpException = System.Web.HttpException;
namespace Spring.Objects.Factory.Support
{
/// <summary>
/// Miscellaneous utility methods to support web functionality within Spring.Objects
/// </summary>
/// <author>Aleksandar Seovic</author>
public sealed class WebObjectUtils
{
private static ILog s_log = LogManager.GetLogger( typeof( WebObjectUtils ) );
// CLOVER:OFF
#if NET_1_1
// Required method for resolving control types
private static MethodInfo miGetCompiledUserControlType = null;
static WebObjectUtils()
{
Type tUserControlParser = typeof(System.Web.UI.UserControl).Assembly.GetType("System.Web.UI.UserControlParser");
miGetCompiledUserControlType =
tUserControlParser.GetMethod("GetCompiledUserControlType", BindingFlags.Static | BindingFlags.NonPublic);
}
#endif
/// <summary>
/// Creates a new instance of the <see cref="Spring.Util.WebUtils"/> class.
/// </summary>
/// <remarks>
/// <p>
/// This is a utility class, and as such exposes no public constructors.
/// </p>
/// </remarks>
private WebObjectUtils()
{ }
// CLOVER:ON
/// <summary>
/// Creates an instance of the ASPX page
/// referred to by the supplied <paramref name="pageUrl"/>.
/// </summary>
/// <param name="pageUrl">
/// The URL of the ASPX page.
/// </param>
/// <returns>Page instance.</returns>
/// <exception cref="Spring.Objects.Factory.ObjectCreationException">
/// If this method is not called in the scope of an active web session
/// (i.e. the implementation this method depends on this code executing
/// in the environs of a running web server such as IIS); or if the
/// page could not be instantiated (for whatever reason, such as the
/// ASPX <paramref name="pageUrl"/> not actually existing).
/// </exception>
public static IHttpHandler CreatePageInstance( string pageUrl )
{
if (s_log.IsDebugEnabled)
{
s_log.Debug( "creating page instance '" + pageUrl + "'" );
}
// HttpContext ctx = HttpContext.Current;
// if (ctx == null)
// {
// throw new ObjectCreationException(
// "Unable to instantiate page. HttpContext is not defined." );
// }
IHttpHandler page;
try
{
page = CreateHandler( pageUrl );
}
catch (HttpException httpEx)
{
string msg = String.Format( "Unable to instantiate page [{0}]: {1}", pageUrl, httpEx.Message );
if (httpEx.GetHttpCode() == 404)
{
throw new FileNotFoundException( msg );
}
s_log.Error( msg, httpEx );
throw new ObjectCreationException( msg, httpEx );
}
catch (Exception ex)
{
// in case of FileNotFound recreate the exception for clarity
FileNotFoundException fnfe = ex as FileNotFoundException;
if (fnfe != null)
{
string fmsg = String.Format( "Unable to instantiate page [{0}]: The file '{1}' does not exist.", pageUrl, fnfe.Message );
throw new FileNotFoundException( fmsg );
}
string msg = String.Format( "Unable to instantiate page [{0}]", pageUrl );
s_log.Error( msg, ex );
throw new ObjectCreationException( msg, ex );
}
return page;
}
/// <summary>
/// Creates the raw handler instance without any exception handling
/// </summary>
/// <param name="pageUrl"></param>
/// <returns></returns>
internal static IHttpHandler CreateHandler( string pageUrl )
{
IHttpHandler page;
// HttpContext ctx = HttpContext.Current;
//#if NET_1_1
// string physicalPath = ctx.Server.MapPath(pageUrl);
// s_log.Debug(string.Format("constructing page virtual path '{0}' from physical file '{1}'", pageUrl, physicalPath));
// page = PageParser.GetCompiledPageInstance(pageUrl, physicalPath, ctx);
//#else
// string rootedVPath = WebUtils.CombineVirtualPaths( ctx.Request.CurrentExecutionFilePath, pageUrl );
// if (s_log.IsDebugEnabled)
// {
// s_log.Debug( "page vpath is " + rootedVPath );
// }
//
// page = BuildManager.CreateInstanceFromVirtualPath( rootedVPath, typeof( IHttpHandler ) ) as IHttpHandler;
//#endif
page = VirtualEnvironment.CreateInstanceFromVirtualPath(pageUrl, typeof (IHttpHandler)) as IHttpHandler;
return page;
}
/// <summary>
/// Returns the <see cref="System.Type"/> of the ASPX page
/// referred to by the supplied <paramref name="pageUrl"/>.
/// </summary>
/// <remarks>
/// <p>
/// As indicated by the exception that can be thrown by this method,
/// the ASPX page referred to by the supplied <paramref name="pageUrl"/>
/// does have to be instantiated in order to determine its
/// see cref="System.Type"/>
/// </p>
/// </remarks>
/// <param name="pageUrl">
/// The filename of the ASPX page.
/// </param>
/// <returns>
/// The <see cref="System.Type"/> of the ASPX page
/// referred to by the supplied <paramref name="pageUrl"/>.
/// </returns>
/// <exception cref="System.ArgumentNullException">
/// If the supplied <paramref name="pageUrl"/> is <see langword="null"/> or
/// contains only whitespace character(s).
/// </exception>
/// <exception cref="Spring.Objects.Factory.ObjectCreationException">
/// If this method is not called in the scope of an active web session
/// (i.e. the implementation this method depends on this code executing
/// in the environs of a running web server such as IIS); or if the
/// page could not be instantiated (for whatever reason, such as the
/// ASPX <paramref name="pageUrl"/> not actually existing).
/// </exception>
public static Type GetPageType( string pageUrl )
{
AssertUtils.ArgumentHasText( pageUrl, "pageUrl" );
// HttpContext ctx = HttpContext.Current;
// if (ctx == null)
// {
// throw new ObjectCreationException( "Unable to get page type. HttpContext is not defined." );
// }
try
{
Type pageType = GetCompiledPageType( pageUrl );
return pageType;
}
catch (Exception ex)
{
string msg = String.Format( "Unable to get page type for url [{0}]", pageUrl );
s_log.Error( msg, ex );
throw new ObjectCreationException( msg, ex );
}
}
/// <summary>
/// Calls the underlying ASP.NET infrastructure to obtain the compiled page type
/// relative to the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath"/>.
/// </summary>
/// <param name="pageUrl">
/// The filename of the ASPX page relative to the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath"/>
/// </param>
/// <returns>
/// The <see cref="System.Type"/> of the ASPX page
/// referred to by the supplied <paramref name="pageUrl"/>.
/// </returns>
public static Type GetCompiledPageType( string pageUrl )
{
if (s_log.IsDebugEnabled)
{
s_log.Debug( "getting page type for " + pageUrl );
}
string rootedVPath = WebUtils.CombineVirtualPaths( VirtualEnvironment.CurrentExecutionFilePath, pageUrl );
if (s_log.IsDebugEnabled)
{
s_log.Debug( "page vpath is " + rootedVPath );
}
Type pageType = VirtualEnvironment.GetCompiledType(rootedVPath);
//#if NET_2_0
// pageType = BuildManager.GetCompiledType( rootedVPath ); // requires rooted virtual path!
//#else
// pageType = CreatePageInstance(pageUrl).GetType();
//#endif
if (s_log.IsDebugEnabled)
{
s_log.Debug( string.Format( "got page type '{0}' for vpath '{1}'", pageType.FullName, rootedVPath ) );
}
return pageType;
}
/// <summary>
/// Gets the controls type from a given filename
/// </summary>
public static Type GetControlType( string controlName )
{
AssertUtils.ArgumentHasText( controlName, "controlName" );
if (s_log.IsDebugEnabled)
{
s_log.Debug( "getting control type for " + controlName );
}
// HttpContext ctx = HttpContext.Current;
// if (ctx == null)
// {
// throw new ObjectCreationException( "Unable to get control type. HttpContext is not defined." );
// }
string rootedVPath = WebUtils.CombineVirtualPaths( VirtualEnvironment.CurrentExecutionFilePath, controlName );
if (s_log.IsDebugEnabled)
{
s_log.Debug( "control vpath is " + rootedVPath );
}
Type controlType;
try
{
//#if NET_2_0
// controlType = BuildManager.GetCompiledType( rootedVPath ); // requires rooted virtual path!
//#else
// controlType = (Type) miGetCompiledUserControlType.Invoke(null, new object[] { rootedVPath, null, ctx });
//#endif
controlType = VirtualEnvironment.GetCompiledType(rootedVPath);
}
catch (HttpException httpEx)
{
// for better error-handling suppress 404 HttpExceptions here
if (httpEx.GetHttpCode() == 404)
{
throw new FileNotFoundException( string.Format( "Control '{0}' does not exist", rootedVPath ) );
}
throw;
}
if (s_log.IsDebugEnabled)
{
s_log.Debug( string.Format( "got control type '{0}' for vpath '{1}'", controlType.FullName, rootedVPath ) );
}
return controlType;
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.IO;
using FluorineFx.Util;
using FluorineFx.IO;
namespace FluorineFx.IO.FLV
{
/// <summary>
/// Metadata service.
/// </summary>
[CLSCompliant(false)]
public class MetaService
{
/// <summary>
/// Source file.
/// </summary>
private FileInfo _file;
/// <summary>
/// File input stream
/// </summary>
private Stream _input;
/// <summary>
/// Gets the file input stream.
/// </summary>
public Stream Input
{
get { return _input; }
set { _input = value; }
}
/// <summary>
/// File output stream.
/// </summary>
private Stream _output;
/// <summary>
/// Gets or sets the file output stream.
/// </summary>
public Stream Output
{
get { return _output; }
set { _output = value; }
}
private AMFReader _deserializer;
/// <summary>
/// Gets or sets the deserializer.
/// </summary>
public AMFReader Deserializer
{
get { return _deserializer; }
set { _deserializer = value; }
}
private AMFWriter _serializer;
/// <summary>
/// Gets or sets the serializer.
/// </summary>
public AMFWriter Serializer
{
get { return _serializer; }
set { _serializer = value; }
}
/// <summary>
/// Initializes a new instance of the MetaService class.
/// </summary>
public MetaService()
{
}
/// <summary>
/// Initializes a new instance of the MetaService class.
/// </summary>
/// <param name="file">The soure file.</param>
public MetaService(FileInfo file)
{
_file = file;
}
/// <summary>
/// Initiates writing of the Metadata.
/// </summary>
/// <param name="meta">Metadata to write.</param>
public void Write(MetaData meta)
{
// Get cue points, FLV reader and writer
MetaCue[] metaArr = meta.MetaCue;
FlvReader reader = new FlvReader(_file, false);
FlvWriter writer = new FlvWriter(_output, false);
ITag tag = null;
// Read first tag
if (reader.HasMoreTags())
{
tag = reader.ReadTag();
if (tag.DataType == IOConstants.TYPE_METADATA)
{
if (!reader.HasMoreTags())
throw new IOException("File we're writing is metadata only?");
}
}
meta.Duration = (double)reader.Duration / 1000;
meta.VideoCodecId = reader.VideoCodecId;
meta.AudioCodecId = reader.AudioCodecId;
ITag injectedTag = InjectMetaData(meta, tag);
injectedTag.PreviousTagSize = 0;
tag.PreviousTagSize = injectedTag.BodySize;
writer.WriteHeader();
writer.WriteTag(injectedTag);
writer.WriteTag(tag);
int cuePointTimeStamp = 0;
int counter = 0;
if (metaArr != null)
{
Array.Sort(metaArr);
cuePointTimeStamp = GetTimeInMilliseconds(metaArr[0]);
}
while (reader.HasMoreTags())
{
tag = reader.ReadTag();
// if there are cuePoints in the array
if (counter < metaArr.Length)
{
// If the tag has a greater timestamp than the
// cuePointTimeStamp, then inject the tag
while (tag.Timestamp > cuePointTimeStamp)
{
injectedTag = InjectMetaCue(metaArr[counter], tag);
writer.WriteTag(injectedTag);
tag.PreviousTagSize = injectedTag.BodySize;
// Advance to the next CuePoint
counter++;
if (counter > (metaArr.Length - 1))
{
break;
}
cuePointTimeStamp = GetTimeInMilliseconds(metaArr[counter]);
}
}
if (tag.DataType != IOConstants.TYPE_METADATA)
{
writer.WriteTag(tag);
}
}
writer.Close();
}
/// <summary>
/// Injects metadata (other than Cue points) into a tag.
/// </summary>
/// <param name="meta">Metadata.</param>
/// <param name="tag">Tag.</param>
/// <returns></returns>
private ITag InjectMetaData(MetaData meta, ITag tag)
{
MemoryStream ms = new MemoryStream();
AMFWriter writer = new AMFWriter(ms);
writer.WriteData(ObjectEncoding.AMF0, "onMetaData");
writer.WriteData(ObjectEncoding.AMF0, meta);
byte[] buffer = ms.ToArray();
return new Tag(IOConstants.TYPE_METADATA, 0, buffer.Length, buffer, tag.PreviousTagSize);
}
/// <summary>
/// Injects metadata (Cue Points) into a tag.
/// </summary>
/// <param name="meta">Metadata.</param>
/// <param name="tag">Tag.</param>
/// <returns></returns>
private ITag InjectMetaCue(MetaCue meta, ITag tag)
{
MemoryStream ms = new MemoryStream();
AMFWriter writer = new AMFWriter(ms);
writer.WriteData(ObjectEncoding.AMF0, "onCuePoint");
writer.WriteData(ObjectEncoding.AMF0, meta);
byte[] buffer = ms.ToArray();
return new Tag(IOConstants.TYPE_METADATA, GetTimeInMilliseconds(meta), buffer.Length, buffer, tag.PreviousTagSize);
}
/// <summary>
/// Returns a timestamp of cue point in milliseconds.
/// </summary>
/// <param name="metaCue">Cue point.</param>
/// <returns>Timestamp of given cue point (in milliseconds).</returns>
private int GetTimeInMilliseconds(MetaCue metaCue)
{
return (int)(metaCue.Time * 1000.00);
}
/// <summary>
/// Writes the Metadata.
/// </summary>
/// <param name="metaData">Metadata to write.</param>
public void WriteMetaData(MetaData metaData)
{
}
/// <summary>
/// Reads the Metadata.
/// </summary>
/// <param name="buffer">Byte buffer source.</param>
/// <returns>Metadata.</returns>
public MetaData ReadMetaData(byte[] buffer)
{
MetaData retMeta = new MetaData();
MemoryStream ms = new MemoryStream(buffer);
AMFReader reader = new AMFReader(ms);
string metaType = reader.ReadData() as string;
IDictionary data = reader.ReadData() as IDictionary;
retMeta.PutAll(data);
return retMeta;
}
/// <summary>
/// Reads the Meta cue points.
/// </summary>
/// <returns>Meta cue points.</returns>
public MetaCue[] ReadMetaCue()
{
return null;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestMapping.cs" company="Naos Project">
// Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Serialization.Test
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using Naos.Serialization.Bson;
using Naos.Serialization.Json;
using OBeautifulCode.Math.Recipes;
public class TestMapping
{
public string StringProperty { get; set; }
public TestEnumeration EnumProperty { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Need to test an array.")]
public TestEnumeration[] EnumArray { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Need to test an array.")]
public string[] NonEnumArray { get; set; }
public Guid GuidProperty { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int", Justification = "Name is correct.")]
public int IntProperty { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public Dictionary<AnotherEnumeration, int> EnumIntMap { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public Dictionary<string, int> StringIntMap { get; set; }
public Tuple<int, int> IntIntTuple { get; set; }
public DateTime DateTimePropertyUtc { get; set; }
public DateTime DateTimePropertyLocal { get; set; }
public DateTime DateTimePropertyUnspecified { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Just need a type to test.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public int[] IntArray { get; set; }
}
public class TestWithId
{
public string Id { get; set; }
}
public class TestWithInheritor
{
public string Id { get; set; }
public string Name { get; set; }
}
public class TestWithInheritorExtraProperty : TestWithInheritor
{
public string AnotherName { get; set; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "Here for testing.")]
public interface ITestConfigureActionFromInterface
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "Here for testing.")]
public interface ITestConfigureActionFromAuto
{
}
public class TestConfigureActionFromInterface : ITestConfigureActionFromInterface
{
}
public class TestConfigureActionFromAuto : ITestConfigureActionFromAuto
{
}
public abstract class TestConfigureActionBaseFromSub
{
}
public abstract class TestConfigureActionBaseFromAuto
{
}
public class TestConfigureActionInheritedSub : TestConfigureActionBaseFromSub
{
}
public class TestConfigureActionInheritedAuto : TestConfigureActionBaseFromAuto
{
}
public class TestConfigureActionSingle
{
}
public class TestTracking
{
}
public class TestWrappedFields
{
public DateTime? NullableDateTimeNull { get; set; }
public DateTime? NullableDateTimeWithValue { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public ICollection<DateTime> CollectionOfDateTime { get; set; }
public AnotherEnumeration? NullableEnumNull { get; set; }
public AnotherEnumeration? NullableEnumWithValue { get; set; }
public IEnumerable<AnotherEnumeration> EnumerableOfEnum { get; set; }
}
public class TestCollectionFields
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public ReadOnlyCollection<DateTime> ReadOnlyCollectionDateTime { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public ICollection<string> ICollectionDateTime { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public IList<AnotherEnumeration> IListEnum { get; set; }
public IReadOnlyList<string> IReadOnlyListString { get; set; }
public IReadOnlyCollection<DateTime> IReadOnlyCollectionGuid { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Just need a type to test.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public List<DateTime> ListDateTime { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public Collection<Guid> CollectionGuid { get; set; }
}
public class TestWithReadOnlyCollectionOfBaseClass
{
public IReadOnlyCollection<TestBase> TestCollection { get; set; }
public TestImplementationOne RootOne { get; set; }
public TestImplementationTwo RootTwo { get; set; }
}
public class TestWithReadOnlyCollectionOfBaseClassConfig : BsonConfigurationBase
{
protected override IReadOnlyCollection<Type> ClassTypesToRegisterAlongWithInheritors => new[] { typeof(TestBase), typeof(TestWithReadOnlyCollectionOfBaseClass) };
}
public abstract class TestBase
{
public string Message { get; set; }
public static bool operator ==(
TestBase item1,
TestBase item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result = item1.Equals((object)item2);
return result;
}
public static bool operator !=(
TestBase item1,
TestBase item2)
=> !(item1 == item2);
public bool Equals(
TestBase other)
=> this == other;
/// <inheritdoc />
public abstract override bool Equals(
object obj);
/// <inheritdoc />
public abstract override int GetHashCode();
}
public class TestImplementationOne : TestBase
{
public string One { get; set; }
public static bool operator ==(
TestImplementationOne item1,
TestImplementationOne item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result =
(item1.Message == item2.Message) &&
(item1.One == item2.One);
return result;
}
public static bool operator !=(
TestImplementationOne item1,
TestImplementationOne item2)
=> !(item1 == item2);
public bool Equals(TestImplementationOne other) => this == other;
public override bool Equals(object obj) => this == (obj as TestImplementationOne);
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(this.Message)
.Hash(this.One)
.Value;
}
public class TestImplementationTwo : TestBase
{
public string Two { get; set; }
public static bool operator ==(
TestImplementationTwo item1,
TestImplementationTwo item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result =
(item1.Message == item2.Message) &&
(item1.Two == item2.Two);
return result;
}
public static bool operator !=(
TestImplementationTwo item1,
TestImplementationTwo item2)
=> !(item1 == item2);
public bool Equals(TestImplementationTwo other) => this == other;
public override bool Equals(object obj) => this == (obj as TestImplementationTwo);
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(this.Message)
.Hash(this.Two)
.Value;
}
public struct TestStruct
{
}
public enum TestEnumeration
{
/// <summary>
/// No value specified.
/// </summary>
None,
/// <summary>
/// First value.
/// </summary>
TestFirst,
/// <summary>
/// Second value.
/// </summary>
TestSecond,
/// <summary>
/// Third value.
/// </summary>
TestThird,
}
public enum AnotherEnumeration
{
/// <summary>
/// No value specified.
/// </summary>
None,
/// <summary>
/// First value.
/// </summary>
AnotherFirst,
/// <summary>
/// Second value.
/// </summary>
AnotherSecond,
}
public class Investigation
{
public IReadOnlyCollection<IDeduceWhoLetTheDogsOut> Investigators { get; set; }
}
public interface IDeduceWhoLetTheDogsOut
{
string WhoLetTheDogsOut();
}
public class NamedInvestigator : IDeduceWhoLetTheDogsOut
{
public NamedInvestigator(string name, int yearsOfPractice)
{
this.Name = name;
this.YearsOfPractice = yearsOfPractice;
}
public string Name { get; private set; }
public int YearsOfPractice { get; private set; }
public string WhoLetTheDogsOut()
{
return $"I don't know. I, {this.Name} quit!";
}
}
public class AnonymousInvestigator : IDeduceWhoLetTheDogsOut
{
public AnonymousInvestigator(int fee)
{
this.Fee = fee;
}
public int Fee { get; private set; }
public string WhoLetTheDogsOut()
{
return FormattableString.Invariant($"Dunno. You owe me ${this.Fee}");
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Onlys", Justification = "Spelling/name is correct.")]
public abstract class ClassWithGetterOnlysBase
{
public AnotherEnumeration GetMyEnumOnlyBase { get; }
public string GetMyStringOnlyBase { get; }
public abstract AnotherEnumeration GetMyEnumFromBase { get; }
public abstract string GetMyStringFromBase { get; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Onlys", Justification = "Spelling/name is correct.")]
public class ClassWithGetterOnlys : ClassWithGetterOnlysBase
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This is strictly for testing.")]
public AnotherEnumeration GetMyEnumFromThis => AnotherEnumeration.AnotherFirst;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This is strictly for testing.")]
public string GetMyStringFromThis => "TurtleBusiness";
public override AnotherEnumeration GetMyEnumFromBase => AnotherEnumeration.AnotherSecond;
public override string GetMyStringFromBase => "MonkeyBusiness";
}
public class ClassWithPrivateSetter
{
public ClassWithPrivateSetter(string privateValue)
{
this.PrivateValue = privateValue;
}
public string PrivateValue { get; private set; }
public static bool operator ==(
ClassWithPrivateSetter item1,
ClassWithPrivateSetter item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result = item1.PrivateValue == item2.PrivateValue;
return result;
}
public static bool operator !=(
ClassWithPrivateSetter item1,
ClassWithPrivateSetter item2)
=> !(item1 == item2);
public bool Equals(ClassWithPrivateSetter other) => this == other;
public override bool Equals(object obj) => this == (obj as ClassWithPrivateSetter);
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(this.PrivateValue)
.Value;
}
public class VanillaClass : IEquatable<VanillaClass>
{
public string Something { get; set; }
public static bool operator ==(
VanillaClass item1,
VanillaClass item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result = item1.Something == item2.Something;
return result;
}
public static bool operator !=(
VanillaClass item1,
VanillaClass item2)
=> !(item1 == item2);
public bool Equals(VanillaClass other) => this == other;
public override bool Equals(object obj) => this == (obj as VanillaClass);
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(this.Something)
.Value;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames", Justification = "Spelling/name is correct.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Spelling/name is correct.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Spelling/name is correct.")]
[Flags]
public enum FlagsEnumeration
{
/// <summary>
/// None value.
/// </summary>
None,
/// <summary>
/// Second value.
/// </summary>
SecondValue,
/// <summary>
/// Third value.
/// </summary>
ThirdValue,
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Spelling/name is correct.")]
public class ClassWithFlagsEnums
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Spelling/name is correct.")]
public FlagsEnumeration Flags { get; set; }
}
public abstract class Field
{
protected Field(
string id)
{
this.Id = id;
}
public string Id { get; private set; }
public abstract FieldDataKind FieldDataKind { get; }
public string Title { get; set; }
}
public abstract class DecimalField : Field
{
protected DecimalField(string id)
: base(id)
{
}
public int NumberOfDecimalPlaces { get; set; }
}
public class CurrencyField : DecimalField
{
public CurrencyField(string id)
: base(id)
{
}
public override FieldDataKind FieldDataKind
{
get
{
var result = this.NumberOfDecimalPlaces == 0
? FieldDataKind.CurrencyWithoutDecimals
: FieldDataKind.CurrencyWithDecimals;
return result;
}
}
}
public class NumberField : DecimalField
{
public NumberField(string id)
: base(id)
{
}
public override FieldDataKind FieldDataKind
{
get
{
var result = this.NumberOfDecimalPlaces == 0
? FieldDataKind.NumberWithoutDecimals
: FieldDataKind.NumberWithDecimals;
return result;
}
}
}
public class YearField : NumberField
{
public YearField(string id)
: base(id)
{
}
public override FieldDataKind FieldDataKind => FieldDataKind.Year;
}
public enum FieldDataKind
{
#pragma warning disable SA1602 // Enumeration items should be documented
CurrencyWithDecimals,
CurrencyWithoutDecimals,
NumberWithDecimals,
NumberWithoutDecimals,
Text,
Date,
Year,
#pragma warning restore SA1602 // Enumeration items should be documented
}
}
| |
/**
* Lexer.cs
* JSON lexer implementation based on a finite state machine.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace LitJson
{
internal class FsmContext
{
public bool Return;
public int NextState;
public Lexer L;
public int StateStack;
}
internal class Lexer
{
#region Fields
private delegate bool StateHandler (FsmContext ctx);
private static int[] fsm_return_table;
private static StateHandler[] fsm_handler_table;
private bool allow_comments;
private bool allow_single_quoted_strings;
private bool end_of_input;
private FsmContext fsm_context;
private int input_buffer;
private int input_char;
private TextReader reader;
private int state;
private StringBuilder string_buffer;
private string string_value;
private int token;
private int unichar;
#endregion
#region Properties
public bool AllowComments {
get { return allow_comments; }
set { allow_comments = value; }
}
public bool AllowSingleQuotedStrings {
get { return allow_single_quoted_strings; }
set { allow_single_quoted_strings = value; }
}
public bool EndOfInput {
get { return end_of_input; }
}
public int Token {
get { return token; }
}
public string StringValue {
get { return string_value; }
}
#endregion
#region Constructors
static Lexer ()
{
PopulateFsmTables ();
}
public Lexer (TextReader reader)
{
allow_comments = true;
allow_single_quoted_strings = true;
input_buffer = 0;
string_buffer = new StringBuilder (128);
state = 1;
end_of_input = false;
this.reader = reader;
fsm_context = new FsmContext ();
fsm_context.L = this;
}
#endregion
#region Static Methods
private static int HexValue (int digit)
{
switch (digit) {
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return digit - '0';
}
}
private static void PopulateFsmTables ()
{
fsm_handler_table = new StateHandler[28] {
State1,
State2,
State3,
State4,
State5,
State6,
State7,
State8,
State9,
State10,
State11,
State12,
State13,
State14,
State15,
State16,
State17,
State18,
State19,
State20,
State21,
State22,
State23,
State24,
State25,
State26,
State27,
State28
};
fsm_return_table = new int[28] {
(int) ParserToken.Char,
0,
(int) ParserToken.Number,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
0,
(int) ParserToken.True,
0,
0,
0,
(int) ParserToken.False,
0,
0,
(int) ParserToken.Null,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
0,
0
};
}
private static char ProcessEscChar (int esc_char)
{
switch (esc_char) {
case '"':
case '\'':
case '\\':
case '/':
return Convert.ToChar (esc_char);
case 'n':
return '\n';
case 't':
return '\t';
case 'r':
return '\r';
case 'b':
return '\b';
case 'f':
return '\f';
default:
// Unreachable
return '?';
}
}
private static bool State1 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r')
continue;
if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '"':
ctx.NextState = 19;
ctx.Return = true;
return true;
case ',':
case ':':
case '[':
case ']':
case '{':
case '}':
ctx.NextState = 1;
ctx.Return = true;
return true;
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 2;
return true;
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
case 'f':
ctx.NextState = 12;
return true;
case 'n':
ctx.NextState = 16;
return true;
case 't':
ctx.NextState = 9;
return true;
case '\'':
if (! ctx.L.allow_single_quoted_strings)
return false;
ctx.L.input_char = '"';
ctx.NextState = 23;
ctx.Return = true;
return true;
case '/':
if (! ctx.L.allow_comments)
return false;
ctx.NextState = 25;
return true;
default:
return false;
}
}
return true;
}
private static bool State2 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '1' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
default:
return false;
}
}
private static bool State3 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State4 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
private static bool State5 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 6;
return true;
}
return false;
}
private static bool State6 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State7 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
}
switch (ctx.L.input_char) {
case '+':
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
default:
return false;
}
}
private static bool State8 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char<= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
return true;
}
private static bool State9 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'r':
ctx.NextState = 10;
return true;
default:
return false;
}
}
private static bool State10 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 11;
return true;
default:
return false;
}
}
private static bool State11 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State12 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'a':
ctx.NextState = 13;
return true;
default:
return false;
}
}
private static bool State13 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 14;
return true;
default:
return false;
}
}
private static bool State14 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 's':
ctx.NextState = 15;
return true;
default:
return false;
}
}
private static bool State15 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State16 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 17;
return true;
default:
return false;
}
}
private static bool State17 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 18;
return true;
default:
return false;
}
}
private static bool State18 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State19 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '"':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 20;
return true;
case '\\':
ctx.StateStack = 19;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State20 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '"':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State21 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 22;
return true;
case '"':
case '\'':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
ctx.L.string_buffer.Append (
ProcessEscChar (ctx.L.input_char));
ctx.NextState = ctx.StateStack;
return true;
default:
return false;
}
}
private static bool State22 (FsmContext ctx)
{
int counter = 0;
int mult = 4096;
ctx.L.unichar = 0;
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' ||
ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' ||
ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') {
ctx.L.unichar += HexValue (ctx.L.input_char) * mult;
counter++;
mult /= 16;
if (counter == 4) {
ctx.L.string_buffer.Append (
Convert.ToChar (ctx.L.unichar));
ctx.NextState = ctx.StateStack;
return true;
}
continue;
}
return false;
}
return true;
}
private static bool State23 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '\'':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 24;
return true;
case '\\':
ctx.StateStack = 23;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State24 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '\'':
ctx.L.input_char = '"';
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State25 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '*':
ctx.NextState = 27;
return true;
case '/':
ctx.NextState = 26;
return true;
default:
return false;
}
}
private static bool State26 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '\n') {
ctx.NextState = 1;
return true;
}
}
return true;
}
private static bool State27 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '*') {
ctx.NextState = 28;
return true;
}
}
return true;
}
private static bool State28 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '*')
continue;
if (ctx.L.input_char == '/') {
ctx.NextState = 1;
return true;
}
ctx.NextState = 27;
return true;
}
return true;
}
#endregion
private bool GetChar ()
{
if ((input_char = NextChar ()) != -1)
return true;
end_of_input = true;
return false;
}
private int NextChar ()
{
if (input_buffer != 0) {
int tmp = input_buffer;
input_buffer = 0;
return tmp;
}
return reader.Read ();
}
public bool NextToken ()
{
StateHandler handler;
fsm_context.Return = false;
while (true) {
handler = fsm_handler_table[state - 1];
if (! handler (fsm_context))
throw new JsonException (input_char);
if (end_of_input)
return false;
if (fsm_context.Return) {
string_value = string_buffer.ToString ();
string_buffer.Remove (0, string_buffer.Length);
token = fsm_return_table[state - 1];
if (token == (int) ParserToken.Char)
token = input_char;
state = fsm_context.NextState;
return true;
}
state = fsm_context.NextState;
}
}
private void UngetChar ()
{
input_buffer = input_char;
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) Rick Brewster, Tom Jackson, and past contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
/////////////////////////////////////////////////////////////////////////////////
using System;
using Cairo;
namespace Pinta.Core
{
public abstract class LocalHistogramEffect : BaseEffect
{
public LocalHistogramEffect ()
{
}
protected static int GetMaxAreaForRadius(int radius)
{
int area = 0;
int cutoff = ((radius * 2 + 1) * (radius * 2 + 1) + 2) / 4;
for (int v = -radius; v <= radius; ++v) {
for (int u = -radius; u <= radius; ++u) {
if (u * u + v * v <= cutoff)
++area;
}
}
return area;
}
public virtual unsafe ColorBgra Apply(ColorBgra src, int area, int* hb, int* hg, int* hr, int* ha)
{
return src;
}
//same as Aply, except the histogram is alpha-weighted instead of keeping a separate alpha channel histogram.
public virtual unsafe ColorBgra ApplyWithAlpha(ColorBgra src, int area, int sum, int* hb, int* hg, int* hr)
{
return src;
}
public static unsafe ColorBgra GetPercentile(int percentile, int area, int* hb, int* hg, int* hr, int* ha)
{
int minCount = area * percentile / 100;
int b = 0;
int bCount = 0;
while (b < 255 && hb[b] == 0)
{
++b;
}
while (b < 255 && bCount < minCount)
{
bCount += hb[b];
++b;
}
int g = 0;
int gCount = 0;
while (g < 255 && hg[g] == 0)
{
++g;
}
while (g < 255 && gCount < minCount)
{
gCount += hg[g];
++g;
}
int r = 0;
int rCount = 0;
while (r < 255 && hr[r] == 0)
{
++r;
}
while (r < 255 && rCount < minCount)
{
rCount += hr[r];
++r;
}
int a = 0;
int aCount = 0;
while (a < 255 && ha[a] == 0)
{
++a;
}
while (a < 255 && aCount < minCount)
{
aCount += ha[a];
++a;
}
return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, (byte)a);
}
public unsafe void RenderRect(
int rad,
ImageSurface src,
ImageSurface dst,
Rectangle rect)
{
int width = src.Width;
int height = src.Height;
int* leadingEdgeX = stackalloc int[rad + 1];
int stride = src.Stride / sizeof(ColorBgra);
// approximately (rad + 0.5)^2
int cutoff = ((rad * 2 + 1) * (rad * 2 + 1) + 2) / 4;
for (int v = 0; v <= rad; ++v)
{
for (int u = 0; u <= rad; ++u)
{
if (u * u + v * v <= cutoff)
{
leadingEdgeX[v] = u;
}
}
}
const int hLength = 256;
int* hb = stackalloc int[hLength];
int* hg = stackalloc int[hLength];
int* hr = stackalloc int[hLength];
int* ha = stackalloc int[hLength];
for (int y = (int)rect.Y; y < rect.Y + rect.Height; y++)
{
MemorySetToZero (hb, hLength);
MemorySetToZero (hg, hLength);
MemorySetToZero (hr, hLength);
MemorySetToZero (ha, hLength);
int area = 0;
ColorBgra* ps = src.GetPointAddressUnchecked((int)rect.X, y);
ColorBgra* pd = dst.GetPointAddressUnchecked((int)rect.X, y);
// assert: v + y >= 0
int top = -Math.Min(rad, y);
// assert: v + y <= height - 1
int bottom = Math.Min(rad, height - 1 - y);
// assert: u + x >= 0
int left = -Math.Min(rad, (int)rect.X);
// assert: u + x <= width - 1
int right = Math.Min(rad, width - 1 - (int)rect.X);
for (int v = top; v <= bottom; ++v)
{
ColorBgra* psamp = src.GetPointAddressUnchecked((int)rect.X + left, y + v);
for (int u = left; u <= right; ++u)
{
if ((u * u + v * v) <= cutoff)
{
++area;
++hb[psamp->B];
++hg[psamp->G];
++hr[psamp->R];
++ha[psamp->A];
}
++psamp;
}
}
for (int x = (int)rect.X; x < rect.X + rect.Width; x++)
{
*pd = Apply(*ps, area, hb, hg, hr, ha);
// assert: u + x >= 0
left = -Math.Min(rad, x);
// assert: u + x <= width - 1
right = Math.Min(rad + 1, width - 1 - x);
// Subtract trailing edge top half
int v = -1;
while (v >= top)
{
int u = leadingEdgeX[-v];
if (-u >= left)
{
break;
}
--v;
}
while (v >= top)
{
int u = leadingEdgeX[-v];
ColorBgra* p = unchecked(ps + (v * stride)) - u;
--hb[p->B];
--hg[p->G];
--hr[p->R];
--ha[p->A];
--area;
--v;
}
// add leading edge top half
v = -1;
while (v >= top)
{
int u = leadingEdgeX[-v];
if (u + 1 <= right)
{
break;
}
--v;
}
while (v >= top)
{
int u = leadingEdgeX[-v];
ColorBgra* p = unchecked(ps + (v * stride)) + u + 1;
++hb[p->B];
++hg[p->G];
++hr[p->R];
++ha[p->A];
++area;
--v;
}
// Subtract trailing edge bottom half
v = 0;
while (v <= bottom)
{
int u = leadingEdgeX[v];
if (-u >= left)
{
break;
}
++v;
}
while (v <= bottom)
{
int u = leadingEdgeX[v];
ColorBgra* p = ps + v * stride - u;
--hb[p->B];
--hg[p->G];
--hr[p->R];
--ha[p->A];
--area;
++v;
}
// add leading edge bottom half
v = 0;
while (v <= bottom)
{
int u = leadingEdgeX[v];
if (u + 1 <= right)
{
break;
}
++v;
}
while (v <= bottom)
{
int u = leadingEdgeX[v];
ColorBgra* p = ps + v * stride + u + 1;
++hb[p->B];
++hg[p->G];
++hr[p->R];
++ha[p->A];
++area;
++v;
}
++ps;
++pd;
}
}
}
//same as RenderRect, except the histogram is alpha-weighted instead of keeping a separate alpha channel histogram.
public unsafe void RenderRectWithAlpha(
int rad,
ImageSurface src,
ImageSurface dst,
Rectangle rect)
{
int width = src.Width;
int height = src.Height;
int* leadingEdgeX = stackalloc int[rad + 1];
int stride = src.Stride / sizeof(ColorBgra);
// approximately (rad + 0.5)^2
int cutoff = ((rad * 2 + 1) * (rad * 2 + 1) + 2) / 4;
for (int v = 0; v <= rad; ++v)
{
for (int u = 0; u <= rad; ++u)
{
if (u * u + v * v <= cutoff)
{
leadingEdgeX[v] = u;
}
}
}
const int hLength = 256;
int* hb = stackalloc int[hLength];
int* hg = stackalloc int[hLength];
int* hr = stackalloc int[hLength];
for (int y = (int)rect.Y; y < rect.Y + rect.Height; y++)
{
MemorySetToZero (hb, hLength);
MemorySetToZero (hg, hLength);
MemorySetToZero (hr, hLength);
int area = 0;
int sum = 0;
ColorBgra* ps = src.GetPointAddressUnchecked((int)rect.X, y);
ColorBgra* pd = dst.GetPointAddressUnchecked((int)rect.X, y);
// assert: v + y >= 0
int top = -Math.Min(rad, y);
// assert: v + y <= height - 1
int bottom = Math.Min(rad, height - 1 - y);
// assert: u + x >= 0
int left = -Math.Min(rad, (int)rect.X);
// assert: u + x <= width - 1
int right = Math.Min(rad, width - 1 - (int)rect.Y);
for (int v = top; v <= bottom; ++v)
{
ColorBgra* psamp = src.GetPointAddressUnchecked((int)rect.Y + left, y + v);
for (int u = left; u <= right; ++u)
{
byte w = psamp->A;
if ((u * u + v * v) <= cutoff)
{
++area;
sum += w;
hb[psamp->B] += w;
hg[psamp->G] += w;
hr[psamp->R] += w;
}
++psamp;
}
}
for (int x = (int)rect.X; x < rect.X + rect.Width; x++)
{
*pd = ApplyWithAlpha(*ps, area, sum, hb, hg, hr);
// assert: u + x >= 0
left = -Math.Min(rad, x);
// assert: u + x <= width - 1
right = Math.Min(rad + 1, width - 1 - x);
// Subtract trailing edge top half
int v = -1;
while (v >= top)
{
int u = leadingEdgeX[-v];
if (-u >= left)
{
break;
}
--v;
}
while (v >= top)
{
int u = leadingEdgeX[-v];
ColorBgra* p = unchecked(ps + (v * stride)) - u;
byte w = p->A;
hb[p->B] -= w;
hg[p->G] -= w;
hr[p->R] -= w;
sum -= w;
--area;
--v;
}
// add leading edge top half
v = -1;
while (v >= top)
{
int u = leadingEdgeX[-v];
if (u + 1 <= right)
{
break;
}
--v;
}
while (v >= top)
{
int u = leadingEdgeX[-v];
ColorBgra* p = unchecked(ps + (v * stride)) + u + 1;
byte w = p->A;
hb[p->B] += w;
hg[p->G] += w;
hr[p->R] += w;
sum += w;
++area;
--v;
}
// Subtract trailing edge bottom half
v = 0;
while (v <= bottom)
{
int u = leadingEdgeX[v];
if (-u >= left)
{
break;
}
++v;
}
while (v <= bottom)
{
int u = leadingEdgeX[v];
ColorBgra* p = ps + v * stride - u;
byte w = p->A;
hb[p->B] -= w;
hg[p->G] -= w;
hr[p->R] -= w;
sum -= w;
--area;
++v;
}
// add leading edge bottom half
v = 0;
while (v <= bottom)
{
int u = leadingEdgeX[v];
if (u + 1 <= right)
{
break;
}
++v;
}
while (v <= bottom)
{
int u = leadingEdgeX[v];
ColorBgra* p = ps + v * stride + u + 1;
byte w = p->A;
hb[p->B] += w;
hg[p->G] += w;
hr[p->R] += w;
sum += w;
++area;
++v;
}
++ps;
++pd;
}
}
}
//must be more efficient way to zero memory array
private unsafe void MemorySetToZero(int* ptr, int size)
{
for (int i = 0; i < size; i++)
ptr [i] = 0;
}
}
}
| |
//
// 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.
//
namespace NLog.UnitTests.Config
{
using NLog.Config;
using NLog.Filters;
using Xunit;
public class RuleConfigurationTests : NLogTestBase
{
[Fact]
public void NoRulesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
</rules>
</nlog>");
Assert.Equal(0, c.LoggingRules.Count);
}
[Fact]
public void SimpleRuleTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal("*", rule.LoggerNamePattern);
Assert.Equal(4, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Info));
Assert.True(rule.Levels.Contains(LogLevel.Warn));
Assert.True(rule.Levels.Contains(LogLevel.Error));
Assert.True(rule.Levels.Contains(LogLevel.Fatal));
Assert.Equal(1, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.False(rule.Final);
Assert.Equal(0, rule.Filters.Count);
}
[Fact]
public void SingleLevelTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(1, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Warn));
}
[Fact]
public void MinMaxLevelTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' maxLevel='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Info));
Assert.True(rule.Levels.Contains(LogLevel.Warn));
}
[Fact]
public void NoLevelsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(6, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Trace));
Assert.True(rule.Levels.Contains(LogLevel.Debug));
Assert.True(rule.Levels.Contains(LogLevel.Info));
Assert.True(rule.Levels.Contains(LogLevel.Warn));
Assert.True(rule.Levels.Contains(LogLevel.Error));
Assert.True(rule.Levels.Contains(LogLevel.Fatal));
}
[Fact]
public void ExplicitLevelsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' levels='Trace,Info,Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Trace));
Assert.True(rule.Levels.Contains(LogLevel.Info));
Assert.True(rule.Levels.Contains(LogLevel.Warn));
}
[Fact]
public void MultipleTargetsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.Same(c.FindTargetByName("d2"), rule.Targets[1]);
Assert.Same(c.FindTargetByName("d3"), rule.Targets[2]);
}
[Fact]
public void MultipleRulesSameTargetTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
<target name='d3' type='Debug' layout='${message}' />
<target name='d4' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
<logger name='*' level='Warn' writeTo='d2' />
<logger name='*' level='Warn' writeTo='d3' />
</rules>
</nlog>");
LogFactory factory = new LogFactory(c);
var loggerConfig = factory.GetConfigurationForLogger("AAA", c);
var targets = loggerConfig.GetTargetsForLevel(LogLevel.Warn);
Assert.Equal("d1", targets.Target.Name);
Assert.Equal("d2", targets.NextInChain.Target.Name);
Assert.Equal("d3", targets.NextInChain.NextInChain.Target.Name);
Assert.Null(targets.NextInChain.NextInChain.NextInChain);
LogManager.Configuration = c;
var logger = LogManager.GetLogger("BBB");
logger.Warn("test1234");
this.AssertDebugLastMessage("d1", "test1234");
this.AssertDebugLastMessage("d2", "test1234");
this.AssertDebugLastMessage("d3", "test1234");
this.AssertDebugLastMessage("d4", string.Empty);
}
[Fact]
public void ChildRulesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<logger name='Foo*' writeTo='d4' />
<logger name='Bar*' writeTo='d4' />
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.ChildRules.Count);
Assert.Equal("Foo*", rule.ChildRules[0].LoggerNamePattern);
Assert.Equal("Bar*", rule.ChildRules[1].LoggerNamePattern);
}
[Fact]
public void FiltersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<filters>
<when condition=""starts-with(message, 'x')"" action='Ignore' />
<when condition=""starts-with(message, 'z')"" action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Filters.Count);
var conditionBasedFilter = rule.Filters[0] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'x')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
conditionBasedFilter = rule.Filters[1] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'z')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
}
}
}
| |
using System;
using System.Linq;
using Castle.DynamicProxy.Contributors;
using NUnit.Framework;
using StructureMap.Pipeline;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
namespace StructureMap.Testing.Pipeline
{
[TestFixture]
public class SmartInstanceTester
{
private SmartInstance<T, T> For<T>()
{
var instance = new SmartInstance<T, T>();
return instance;
}
public T build<T>(Action<SmartInstance<T, T>> action)
{
var instance = For<T>();
action(instance);
var container = new Container(r => r.For<T>().UseInstance(instance));
return container.GetInstance<T>();
}
[Test]
public void specify_a_constructor_dependency()
{
var widget = new ColorWidget("Red");
build<ClassWithWidget>(instance => instance.Ctor<IWidget>("widget").IsSpecial(x => x.Object(widget))).
Widget.
ShouldBeTheSameAs(widget);
}
[Test]
public void specify_a_constructor_dependency_by_type()
{
var widget = new ColorWidget("Red");
build<ClassWithWidget>(i => i.Ctor<IWidget>().IsSpecial(x => x.Object(widget))).Widget.ShouldBeTheSameAs(
widget);
}
[Test]
public void specify_a_non_simple_property_with_equal_to()
{
var widget = new ColorWidget("Red");
var container = new Container(x => x.For<ClassWithWidgetProperty>()
.Use<ClassWithWidgetProperty>()
.Setter(o => o.Widget).Is(widget));
Assert.AreSame(widget, container.GetInstance<ClassWithWidgetProperty>().Widget);
}
[Test]
public void specify_a_property_dependency()
{
var widget = new ColorWidget("Red");
build<ClassWithWidgetProperty>(i => i.Setter(x => x.Widget).IsSpecial(x => x.Object(widget))).Widget.
ShouldBeTheSameAs(widget);
var container = new Container(x => {
x.ForConcreteType<ClassWithWidgetProperty>().Configure
.Setter(o => o.Widget).IsSpecial(o => o.Object(new ColorWidget("Red")));
});
}
[Test]
public void specify_a_simple_property()
{
build<SimplePropertyTarget>(instance => instance.SetProperty(x => x.Name = "Jeremy")).Name.ShouldEqual(
"Jeremy");
build<SimplePropertyTarget>(i => i.SetProperty(x => x.Age = 16)).Age.ShouldEqual(16);
var container = new Container(x => {
x.ForConcreteType<SimplePropertyTarget>().Configure
.SetProperty(target => {
target.Name = "Max";
target.Age = 4;
});
});
}
[Test]
public void specify_a_simple_property_name_with_equal_to()
{
build<SimplePropertyTarget>(i => i.Setter(x => x.Name).Is("Scott")).Name.ShouldEqual("Scott");
}
[Test]
public void specify_a_simple_property_with_equal_to()
{
build<SimplePropertyTarget>(i => i.Setter(x => x.Name).Is("Bret")).Name.ShouldEqual("Bret");
}
[Test]
public void specify_an_array_as_a_constructor()
{
IWidget widget1 = new AWidget();
IWidget widget2 = new AWidget();
IWidget widget3 = new AWidget();
build<ClassWithWidgetArrayCtor>(i => i.EnumerableOf<IWidget>().Contains(x => {
x.Object(widget1);
x.Object(widget2);
x.Object(widget3);
})).Widgets.ShouldEqual(new[] {widget1, widget2, widget3});
}
[Test]
public void specify_an_array_as_a_property()
{
IWidget widget1 = new AWidget();
IWidget widget2 = new AWidget();
IWidget widget3 = new AWidget();
build<ClassWithWidgetArraySetter>(i => i.EnumerableOf<IWidget>().Contains(x => {
x.Object(widget1);
x.Object(widget2);
x.Object(widget3);
})).Widgets.ShouldEqual(new[] {widget1, widget2, widget3});
}
[Test]
public void specify_ctorarg_with_non_simple_argument()
{
var widget = new ColorWidget("Red");
var container = new Container(x => x.For<ClassWithWidget>()
.Use<ClassWithWidget>()
.Ctor<IWidget>().Is(widget));
Assert.AreSame(widget, container.GetInstance<ClassWithWidget>().Widget);
}
[Test]
public void successfully_specify_the_constructor_argument_of_a_string()
{
build<ColorRule>(i => i.Ctor<string>("color").Is("Red")).Color.ShouldEqual("Red");
}
[Test]
public void specify_a_constructor_dependency_by_name()
{
var container = new Container(r => {
r.For<ClassA>().Use<ClassA>().Ctor<ClassB>().Named("classB");
r.For<ClassB>().Use<ClassB>().Named("classB").Ctor<string>("b").Is("named");
r.For<ClassB>().Use<ClassB>().Ctor<string>("b").Is("default");
});
container.GetInstance<ClassA>()
.B.B.ShouldEqual("named");
}
[Test]
public void smart_instance_can_specify_the_constructor()
{
new SmartInstance<ClassWithMultipleConstructors>(() => new ClassWithMultipleConstructors(null)).As<IConfiguredInstance>().Constructor.GetParameters().Select(x => x.ParameterType)
.ShouldHaveTheSameElementsAs(typeof(IGateway));
new SmartInstance<ClassWithMultipleConstructors>(() => new ClassWithMultipleConstructors(null, null)).As<IConfiguredInstance>().Constructor.GetParameters().Select(x => x.ParameterType)
.ShouldHaveTheSameElementsAs(typeof(IGateway), typeof(IService));
}
[Test]
public void integrated_building_with_distinct_ctor_selection()
{
var container = new Container(x => {
x.For<ClassWithMultipleConstructors>().AddInstances(o => {
o.Type<ClassWithMultipleConstructors>().SelectConstructor(() => new ClassWithMultipleConstructors(null)).Named("One");
o.Type<ClassWithMultipleConstructors>().SelectConstructor(() => new ClassWithMultipleConstructors(null, null)).Named("Two");
o.Type<ClassWithMultipleConstructors>().Named("Default");
});
x.For<IGateway>().Use<StubbedGateway>();
x.For<IService>().Use<WhateverService>();
x.For<IWidget>().Use<AWidget>();
});
container.GetInstance<ClassWithMultipleConstructors>("One")
.CtorUsed.ShouldEqual("One Arg");
container.GetInstance<ClassWithMultipleConstructors>("Two")
.CtorUsed.ShouldEqual("Two Args");
container.GetInstance<ClassWithMultipleConstructors>("Default")
.CtorUsed.ShouldEqual("Three Args");
}
private class ClassA
{
public ClassB B { get; private set; }
public ClassA(ClassB b)
{
B = b;
}
}
private class ClassB
{
public string B { get; private set; }
public ClassB(string b)
{
B = b;
}
}
}
public class ClassWithWidgetArrayCtor
{
private readonly IWidget[] _widgets;
public ClassWithWidgetArrayCtor(IWidget[] widgets)
{
_widgets = widgets;
}
public IWidget[] Widgets
{
get { return _widgets; }
}
}
public class ClassWithDoubleProperty
{
public double Double { get; set; }
}
public class ClassWithWidgetArraySetter
{
public IWidget[] Widgets { get; set; }
}
public class SimplePropertyTarget
{
public string Name { get; set; }
public int Age { get; set; }
}
public class ClassWithWidget
{
private readonly IWidget _widget;
public ClassWithWidget(IWidget widget)
{
_widget = widget;
}
public IWidget Widget
{
get { return _widget; }
}
}
public class ClassWithWidgetProperty
{
public IWidget Widget { get; set; }
}
public class ClassWithMultipleConstructors
{
public string CtorUsed;
public ClassWithMultipleConstructors(IGateway gateway, IService service, IWidget widget)
{
CtorUsed = "Three Args";
}
public ClassWithMultipleConstructors(IGateway gateway, IService service)
{
CtorUsed = "Two Args";
}
public ClassWithMultipleConstructors(IGateway gateway)
{
CtorUsed = "One Arg";
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute
{
/// <summary>
/// The Service Management API includes operations for managing the disks
/// in your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157188.aspx for
/// more information)
/// </summary>
public partial interface IVirtualMachineDiskOperations
{
/// <summary>
/// The Create Data Disk operation adds a data disk to a virtual
/// machine. There are three ways to create the data disk using the
/// Add Data Disk operation. Option 1 - Attach an empty data disk to
/// the role by specifying the disk label and location of the disk
/// image. Do not include the DiskName and SourceMediaLink elements in
/// the request body. Include the MediaLink element and reference a
/// blob that is in the same geographical region as the role. You can
/// also omit the MediaLink element. In this usage, Azure will create
/// the data disk in the storage account configured as default for the
/// role. Option 2 - Attach an existing data disk that is in the image
/// repository. Do not include the DiskName and SourceMediaLink
/// elements in the request body. Specify the data disk to use by
/// including the DiskName element. Note: If included the in the
/// response body, the MediaLink and LogicalDiskSizeInGB elements are
/// ignored. Option 3 - Specify the location of a blob in your storage
/// account that contain a disk image to use. Include the
/// SourceMediaLink element. Note: If the MediaLink element
/// isincluded, it is ignored. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of your service.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='roleName'>
/// The name of the role to add the data disk to.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine Data Disk
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> BeginCreatingDataDiskAsync(string serviceName, string deploymentName, string roleName, VirtualMachineDataDiskCreateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Begin Deleting Data Disk operation removes the specified data
/// disk from a virtual machine. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of your service.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='roleName'>
/// The name of the role to delete the data disk from.
/// </param>
/// <param name='logicalUnitNumber'>
/// The logical unit number of the disk.
/// </param>
/// <param name='deleteFromStorage'>
/// Specifies that the source blob for the disk should also be deleted
/// from storage.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> BeginDeletingDataDiskAsync(string serviceName, string deploymentName, string roleName, int logicalUnitNumber, bool deleteFromStorage, CancellationToken cancellationToken);
/// <summary>
/// The Add Disk operation adds a disk to the user image repository.
/// The disk can be an operating system disk or a data disk. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx
/// for more information)
/// </summary>
/// <param name='name'>
/// The name of the disk being updated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine Disk operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> BeginUpdatingDiskAsync(string name, VirtualMachineDiskUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Create Data Disk operation adds a data disk to a virtual
/// machine. There are three ways to create the data disk using the
/// Add Data Disk operation. Option 1 - Attach an empty data disk to
/// the role by specifying the disk label and location of the disk
/// image. Do not include the DiskName and SourceMediaLink elements in
/// the request body. Include the MediaLink element and reference a
/// blob that is in the same geographical region as the role. You can
/// also omit the MediaLink element. In this usage, Azure will create
/// the data disk in the storage account configured as default for the
/// role. Option 2 - Attach an existing data disk that is in the image
/// repository. Do not include the DiskName and SourceMediaLink
/// elements in the request body. Specify the data disk to use by
/// including the DiskName element. Note: If included the in the
/// response body, the MediaLink and LogicalDiskSizeInGB elements are
/// ignored. Option 3 - Specify the location of a blob in your storage
/// account that contain a disk image to use. Include the
/// SourceMediaLink element. Note: If the MediaLink element
/// isincluded, it is ignored. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of your service.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='roleName'>
/// The name of the role to add the data disk to.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine Data Disk
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> CreateDataDiskAsync(string serviceName, string deploymentName, string roleName, VirtualMachineDataDiskCreateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Create Disk operation adds a disk to the user image repository.
/// The disk can be an operating system disk or a data disk. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine Disk operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A virtual machine disk associated with your subscription.
/// </returns>
Task<VirtualMachineDiskCreateResponse> CreateDiskAsync(VirtualMachineDiskCreateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Delete Data Disk operation removes the specified data disk from
/// a virtual machine. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of your service.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='roleName'>
/// The name of the role to delete the data disk from.
/// </param>
/// <param name='logicalUnitNumber'>
/// The logical unit number of the disk.
/// </param>
/// <param name='deleteFromStorage'>
/// Specifies that the source blob for the disk should also be deleted
/// from storage.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> DeleteDataDiskAsync(string serviceName, string deploymentName, string roleName, int logicalUnitNumber, bool deleteFromStorage, CancellationToken cancellationToken);
/// <summary>
/// The Delete Disk operation deletes the specified data or operating
/// system disk from your image repository. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157200.aspx
/// for more information)
/// </summary>
/// <param name='name'>
/// The name of the disk to delete.
/// </param>
/// <param name='deleteFromStorage'>
/// Specifies that the source blob for the disk should also be deleted
/// from storage.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> DeleteDiskAsync(string name, bool deleteFromStorage, CancellationToken cancellationToken);
/// <summary>
/// The Get Data Disk operation retrieves the specified data disk from
/// a virtual machine. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157180.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of your service.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='roleName'>
/// The name of the role.
/// </param>
/// <param name='logicalUnitNumber'>
/// The logical unit number of the disk.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Data Disk operation response.
/// </returns>
Task<VirtualMachineDataDiskGetResponse> GetDataDiskAsync(string serviceName, string deploymentName, string roleName, int logicalUnitNumber, CancellationToken cancellationToken);
/// <summary>
/// The Get Disk operation retrieves a disk from the user image
/// repository. The disk can be an operating system disk or a data
/// disk. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx
/// for more information)
/// </summary>
/// <param name='name'>
/// The name of the disk.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A virtual machine disk associated with your subscription.
/// </returns>
Task<VirtualMachineDiskGetResponse> GetDiskAsync(string name, CancellationToken cancellationToken);
/// <summary>
/// The List Disks operation retrieves a list of the disks in your
/// image repository. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157176.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Disks operation response.
/// </returns>
Task<VirtualMachineDiskListResponse> ListDisksAsync(CancellationToken cancellationToken);
/// <summary>
/// The Update Data Disk operation updates the specified data disk
/// attached to the specified virtual machine. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157190.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of your service.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='roleName'>
/// The name of the role to add the data disk to.
/// </param>
/// <param name='logicalUnitNumber'>
/// The logical unit number of the disk.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine Data Disk
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> UpdateDataDiskAsync(string serviceName, string deploymentName, string roleName, int logicalUnitNumber, VirtualMachineDataDiskUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Add Disk operation adds a disk to the user image repository.
/// The disk can be an operating system disk or a data disk. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx
/// for more information)
/// </summary>
/// <param name='name'>
/// The name of the disk being updated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine Disk operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A virtual machine disk associated with your subscription.
/// </returns>
Task<VirtualMachineDiskUpdateResponse> UpdateDiskAsync(string name, VirtualMachineDiskUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Add Disk operation adds a disk to the user image repository.
/// The disk can be an operating system disk or a data disk. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx
/// for more information)
/// </summary>
/// <param name='name'>
/// The name of the disk being updated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine Disk operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> UpdateDiskSizeAsync(string name, VirtualMachineDiskUpdateParameters parameters, CancellationToken cancellationToken);
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Decorator.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.AI.BehaviorTrees.Implementations.Decorators
{
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Slash.AI.BehaviorTrees.Editor;
using Slash.AI.BehaviorTrees.Enums;
using Slash.AI.BehaviorTrees.Interfaces;
using Slash.AI.BehaviorTrees.Tree;
/// <summary>
/// Base class for a decorator.
/// </summary>
[Serializable]
public class Decorator : Task, IComposite
{
#region Public Events
/// <summary>
/// Called when a child was added to the composite.
/// </summary>
public event CompositeChildAddedDelegate ChildAdded;
/// <summary>
/// Called when a child was removed from the composite.
/// </summary>
public event CompositeChildRemovedDelegate ChildRemoved;
#endregion
#region Public Properties
/// <summary>
/// Maximum number of children that the composite can take.
/// </summary>
[XmlIgnore]
public int Capacity
{
get
{
return 1;
}
}
/// <summary>
/// Collection of children. Read-only.
/// </summary>
[XmlIgnore]
public IList<ITask> Children
{
get
{
return this.Task != null ? new List<ITask> { this.Task } : new List<ITask>();
}
}
/// <summary>
/// Xml serialization for decorated task.
/// </summary>
[XmlElement("Child")]
public XmlWrapper DeciderSerialized
{
get
{
return new XmlWrapper(this.Task);
}
set
{
this.Task = value.Task;
}
}
/// <summary>
/// Decorated task.
/// </summary>
[XmlIgnore]
public ITask Task { get; set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data to use in activate method. </param>
/// <returns> Execution status after activation. </returns>
public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
{
return this.ActivateChild(agentData, decisionData);
}
/// <summary>
/// Adds a child to this group task.
/// </summary>
/// <param name="child"> Child to add. </param>
/// <exception cref="Exception">Thrown if child couldn't be added because capacity was reached.</exception>
public void AddChild(ITask child)
{
if (this.Task != null)
{
throw new Exception("Decorator already has a child.");
}
this.Task = child;
this.InvokeChildAdded(child);
}
/// <summary>
/// Deactivation.
/// </summary>
/// <param name="agentData"> Agent data. </param>
public override void Deactivate(IAgentData agentData)
{
this.DeactivateChild(agentData);
}
/// <summary>
/// Depending on the group policy of its parent, the floating point return value indicates whether the task will be activated.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data to use in activate method. </param>
/// <returns> Floating point value used to decide if the task will be activated. </returns>
public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
{
return this.Task != null ? this.DecideChild(agentData, ref decisionData) : 0.0f;
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="other"> The other. </param>
/// <returns> The System.Boolean. </returns>
public bool Equals(Decorator other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return base.Equals(other) && Equals(other.Task, this.Task);
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="obj"> The obj. </param>
/// <returns> The System.Boolean. </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
return this.Equals(obj as Decorator);
}
/// <summary>
/// Searches for tasks which forfill the passed predicate.
/// </summary>
/// <param name="taskNode"> Task node of this task. </param>
/// <param name="predicate"> Predicate to forfill. </param>
/// <param name="tasks"> List of tasks which forfill the passed predicate. </param>
public override void FindTasks(TaskNode taskNode, Func<ITask, bool> predicate, ref ICollection<TaskNode> tasks)
{
if (this.Task == null)
{
return;
}
// Check child.
TaskNode childTaskNode = taskNode.CreateChildNode(this.Task, 0);
if (predicate(this.Task))
{
tasks.Add(childTaskNode);
}
// Find tasks in child.
this.Task.FindTasks(childTaskNode, predicate, ref tasks);
}
/// <summary>
/// The get hash code.
/// </summary>
/// <returns> The System.Int32. </returns>
public override int GetHashCode()
{
unchecked
{
return (base.GetHashCode() * 397) ^ (this.Task != null ? this.Task.GetHashCode() : 0);
}
}
/// <summary>
/// Inserts a child to this group task at the passed index.
/// </summary>
/// <param name="index"> Position to add child to. </param>
/// <param name="child"> Child to insert. </param>
/// <exception cref="ArgumentOutOfRangeException">Thrown if passed index isn't between 0 and Children.Count (inclusive).</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if passed index isn't between 0 and Capacity (exclusive).</exception>
/// <exception cref="Exception">Thrown if child couldn't be inserted because capacity was reached.</exception>
public void InsertChild(int index, ITask child)
{
if (this.Task != null)
{
throw new Exception("Decorator already has a child.");
}
if (index != 0)
{
throw new ArgumentOutOfRangeException("Decorator only has slot 0 to store a child in.");
}
this.Task = child;
this.InvokeChildAdded(child);
}
/// <summary>
/// Moves a child to the passed position inside the group.
/// </summary>
/// <param name="oldIndex"> Old position of the child. </param>
/// <param name="newIndex"> New position of the child. </param>
/// <exception cref="ArgumentOutOfRangeException">Thrown if passed old index isn't between 0 and Children.Count (exclusive).</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if passed new index isn't between 0 and Children.Count (exclusive).</exception>
public void MoveChild(int oldIndex, int newIndex)
{
if (oldIndex != 0 || newIndex != 0)
{
throw new ArgumentOutOfRangeException("Decorator only has slot 0 to store a child in.");
}
}
/// <summary>
/// Removes a child from this group task.
/// </summary>
/// <param name="child"> Child to remove. </param>
/// <returns> Indicates if the child was removed. </returns>
public bool RemoveChild(ITask child)
{
if (this.Task != child)
{
return false;
}
this.Task = null;
this.InvokeChildRemoved(child);
return true;
}
/// <summary>
/// Per frame update.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <returns> Execution status after this update. </returns>
public override ExecutionStatus Update(IAgentData agentData)
{
return this.UpdateChild(agentData);
}
#endregion
#region Methods
/// <summary>
/// Activates the child of the decorator.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data. </param>
/// <returns> Execution status after activation. </returns>
protected ExecutionStatus ActivateChild(IAgentData agentData, IDecisionData decisionData)
{
++agentData.CurrentDeciderLevel;
ExecutionStatus result = this.Task.Activate(agentData, decisionData);
--agentData.CurrentDeciderLevel;
return result;
}
/// <summary>
/// Deactivates the child of the decorator.
/// </summary>
/// <param name="agentData"> Agent data. </param>
protected void DeactivateChild(IAgentData agentData)
{
++agentData.CurrentDeciderLevel;
this.Task.Deactivate(agentData);
--agentData.CurrentDeciderLevel;
}
/// <summary>
/// Let's the child decide.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data to use in activate method. </param>
/// <returns> Floating point value used to decide if the task will be activated. </returns>
protected float DecideChild(IAgentData agentData, ref IDecisionData decisionData)
{
++agentData.CurrentDeciderLevel;
float decisionValue = this.Task.Decide(agentData, ref decisionData);
--agentData.CurrentDeciderLevel;
return decisionValue;
}
/// <summary>
/// Updates the child of the decorator.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <returns> Execution status after update. </returns>
protected ExecutionStatus UpdateChild(IAgentData agentData)
{
++agentData.CurrentDeciderLevel;
ExecutionStatus result = this.Task.Update(agentData);
--agentData.CurrentDeciderLevel;
return result;
}
private void InvokeChildAdded(ITask childTask)
{
CompositeChildAddedDelegate handler = this.ChildAdded;
if (handler != null)
{
handler(this, childTask);
}
}
private void InvokeChildRemoved(ITask childTask)
{
CompositeChildRemovedDelegate handler = this.ChildRemoved;
if (handler != null)
{
handler(this, childTask);
}
}
#endregion
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ISSE.SafetyChecking.Utilities
{
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
/// <summary>
/// Represents a memory buffer.
/// </summary>
internal sealed unsafe class MemoryBuffer : DisposableObject
{
/// <summary>
/// The number of additional bytes to allocate in front of and behind the buffer to check for out of bounds writes.
/// </summary>
private const int CheckBytes = 128;
/// <summary>
/// The value that is used check for out of bounds writes.
/// </summary>
private const int CheckValue = 0xAF;
/// <summary>
/// Gets the size of the memory buffer in bytes.
/// </summary>
public long SizeInBytes { get; private set; }
/// <summary>
/// Gets a pointer to the underlying memory of the buffer.
/// </summary>
public byte* Pointer { get; private set; }
/// <summary>
/// Resizes the buffer so that it can contain at least <paramref name="sizeInBytes" /> bytes.
/// </summary>
/// <param name="sizeInBytes">The buffer's new size in bytes.</param>
/// <param name="zeroMemory">Indicates whether the buffer's contents should be initialized to zero.</param>
public void Resize(long sizeInBytes, bool zeroMemory)
{
Requires.That(sizeInBytes >= 0, nameof(sizeInBytes), $"Cannot allocate {sizeInBytes} bytes.");
// We don't resize if less space is requested
if (sizeInBytes <= SizeInBytes)
return;
var allocatedBytes = sizeInBytes + 2 * CheckBytes;
var oldBuffer = Pointer;
byte* newBuffer;
try
{
newBuffer = (byte*)Marshal.AllocHGlobal(new IntPtr(allocatedBytes)).ToPointer();
GC.AddMemoryPressure(allocatedBytes);
}
catch (OutOfMemoryException)
{
throw new InvalidOperationException(
$"Unable to allocate {allocatedBytes:n0} bytes. Try optimizing state vector sizes or decrease the state capacity.");
}
if (zeroMemory)
ZeroMemory(new IntPtr(newBuffer + CheckBytes), new IntPtr(sizeInBytes));
if (oldBuffer != null)
Copy(oldBuffer, newBuffer + CheckBytes, SizeInBytes);
OnDisposing(true);
Pointer = newBuffer + CheckBytes;
SizeInBytes = sizeInBytes;
for (var i = 0; i < CheckBytes; ++i)
{
*(newBuffer + i) = CheckValue;
*(Pointer + sizeInBytes + i) = CheckValue;
}
}
/// <summary>
/// Clears the data stored in the buffer, overwriting everything with zeroes.
/// </summary>
public void Clear()
{
ZeroMemory(new IntPtr(Pointer), new IntPtr(SizeInBytes));
}
/// <summary>
/// Compares the two buffers <paramref name="buffer1" /> and <paramref name="buffer2" />, returning <c>true</c> when the
/// buffers are equivalent.
/// </summary>
/// <param name="buffer1">The first buffer of memory to compare.</param>
/// <param name="buffer2">The second buffer of memory to compare.</param>
/// <param name="sizeInBytes">The size of the buffers in bytes.</param>
public static bool AreEqual(byte* buffer1, byte* buffer2, int sizeInBytes)
{
if (buffer1 == buffer2)
return true;
for (var i = sizeInBytes / 8; i > 0; --i)
{
if (*(long*)buffer1 != *(long*)buffer2)
return false;
buffer1 += 8;
buffer2 += 8;
}
for (var i = sizeInBytes % 8; i > 0; --i)
{
if (*buffer1 != *buffer2)
return false;
buffer1 += 1;
buffer2 += 1;
}
return true;
}
/// <summary>
/// Copies <paramref name="sizeInBytes" />-many bytes from <paramref name="source" /> to <see cref="destination" />.
/// </summary>
/// <param name="source">The first buffer of memory to compare.</param>
/// <param name="destination">The second buffer of memory to compare.</param>
/// <param name="sizeInBytes">The size of the buffers in bytes.</param>
public static void Copy(byte* source, byte* destination, long sizeInBytes)
{
for (var i = sizeInBytes / 8; i > 0; --i)
{
*(long*)destination = *(long*)source;
source += 8;
destination += 8;
}
var remaining = sizeInBytes % 8;
if (remaining >= 4)
{
*(int*)destination = *(int*)source;
source += 4;
destination += 4;
remaining -= 4;
}
for (var i = 0; i < remaining; ++i)
{
*destination = *source;
source += 1;
destination += 1;
}
}
/// <summary>
/// Hashes the <paramref name="buffer" />.
/// </summary>
/// <param name="buffer">The buffer of memory that should be hashed.</param>
/// <param name="sizeInBytes">The size of the buffer in bytes.</param>
/// <param name="seed">The seed value for the hash.</param>
/// <remarks>See also https://en.wikipedia.org/wiki/MurmurHash (MurmurHash3 implementation)</remarks>
public static uint Hash(byte* buffer, int sizeInBytes, int seed)
{
const uint c1 = 0xcc9e2d51;
const uint c2 = 0x1b873593;
const int r1 = 15;
const int r2 = 13;
const uint m = 5;
const uint n = 0xe6546b64;
var hash = (uint)seed;
var numBlocks = sizeInBytes / 4;
var blocks = (uint*)buffer;
for (var i = 0; i < numBlocks; i++)
{
var k = blocks[i];
k *= c1;
k = (k << r1) | (k >> (32 - r1));
k *= c2;
hash ^= k;
hash = ((hash << r2) | (hash >> (32 - r2))) * m + n;
}
var tail = buffer + numBlocks * 4;
var k1 = 0u;
switch (sizeInBytes & 3)
{
case 3:
k1 ^= (uint)tail[2] << 16;
goto case 2;
case 2:
k1 ^= (uint)tail[1] << 8;
goto case 1;
case 1:
k1 ^= tail[0];
k1 *= c1;
k1 = (k1 << r1) | (k1 >> (32 - r1));
k1 *= c2;
hash ^= k1;
break;
}
hash ^= (uint)sizeInBytes;
hash ^= hash >> 16;
hash *= (0x85ebca6b);
hash ^= hash >> 13;
hash *= (0xc2b2ae35);
hash ^= hash >> 16;
return hash;
}
/// <summary>
/// Disposes the object, releasing all managed and unmanaged resources.
/// </summary>
/// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param>
protected override void OnDisposing(bool disposing)
{
CheckBounds();
if (Pointer == null)
return;
Marshal.FreeHGlobal(new IntPtr(Pointer - CheckBytes));
GC.RemoveMemoryPressure(SizeInBytes + 2 * CheckBytes);
Pointer = null;
}
/// <summary>
/// Checks whether any writes have been out of bounds.
/// </summary>
internal void CheckBounds()
{
if (Pointer == null)
return;
for (var i = 0; i < CheckBytes; ++i)
{
if (*(Pointer - i - 1) != CheckValue || *(Pointer + SizeInBytes + i) != CheckValue)
throw new InvalidOperationException("Out of bounds write detected.");
}
}
[DllImport("Kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false)]
private static extern void ZeroMemory(IntPtr memory, IntPtr size);
internal static class ZeroMemoryWithInitblk
{
// see https://msdn.microsoft.com/de-de/library/system.reflection.emit.opcodes.ldc_i4_0(v=vs.110).aspx
// parameters are "IntPtr memoryPtr" and "int size"
internal static readonly Action<IntPtr,int> Delegate;
static ZeroMemoryWithInitblk()
{
var method = new DynamicMethod(
name: "ZeroMemoryWithInitBlk",
returnType: typeof(void),
parameterTypes: new[] { typeof(IntPtr), typeof(int) },
m: typeof(object).Assembly.ManifestModule,
skipVisibility: true);
method.DefineParameter(1, ParameterAttributes.In, "memoryPtr");
method.DefineParameter(2, ParameterAttributes.In, "size");
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // push address on stack
il.Emit(OpCodes.Ldc_I4_0); // push "0" on stack
il.Emit(OpCodes.Ldarg_1); // number of bytes as integer
il.Emit(OpCodes.Initblk); //do the magic
il.Emit(OpCodes.Ret);
//compile
Delegate = (Action<IntPtr, int>)method.CreateDelegate(typeof(Action<IntPtr, int>));
}
public static void ClearWithZero(byte* memoryStart, long elements)
{
var bytesToErase = elements;
if (bytesToErase <= Int32.MaxValue)
{
Delegate(new IntPtr(memoryStart), (int)bytesToErase);
}
else
{
Console.WriteLine($"{nameof(MemoryBuffer)}: Using slow memory clearing");
for (var i = 0; i < elements; i++)
{
memoryStart[i] = 0;
}
}
}
public static void ClearWithZero(int* memoryStart, long elements)
{
var bytesToErase = elements * sizeof(int);
if (bytesToErase <= Int32.MaxValue)
{
Delegate(new IntPtr(memoryStart), (int)bytesToErase);
}
else
{
Console.WriteLine($"{nameof(MemoryBuffer)}: Using slow memory clearing");
for (var i = 0; i < elements; i++)
{
memoryStart[i] = 0;
}
}
}
}
internal static class SetAllBitsMemoryWithInitblk
{
// see https://msdn.microsoft.com/de-de/library/system.reflection.emit.opcodes.ldc_i4_0(v=vs.110).aspx
// parameters are "IntPtr memoryPtr" and "uint size"
internal static readonly Action<IntPtr, uint> Delegate;
static SetAllBitsMemoryWithInitblk()
{
var method = new DynamicMethod(
name: "SetAllBitsMemoryWithInitblk",
returnType: typeof(void),
parameterTypes: new[] { typeof(IntPtr), typeof(uint) },
m: typeof(object).Assembly.ManifestModule,
skipVisibility: true);
method.DefineParameter(1, ParameterAttributes.In, "memoryPtr");
method.DefineParameter(2, ParameterAttributes.In, "size");
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // push address on stack
il.Emit(OpCodes.Ldc_I4_M1); // push "-1" on stack
il.Emit(OpCodes.Ldarg_1); // number of bytes as integer
il.Emit(OpCodes.Initblk); //do the magic
il.Emit(OpCodes.Ret);
//compile
Delegate = (Action<IntPtr, uint>)method.CreateDelegate(typeof(Action<IntPtr, uint>));
}
public static void ClearWithMinus1(byte* memoryStart, long elements)
{
var bytesToErase = elements * sizeof(byte);
if (bytesToErase <= uint.MaxValue)
{
Delegate(new IntPtr(memoryStart), (uint)bytesToErase);
}
else
{
Console.WriteLine($"{nameof(MemoryBuffer)}: Using slow memory clearing");
for (var i = 0; i < elements; i++)
{
memoryStart[i] = 255; //byte goes from 0-255.
}
}
}
public static void ClearWithMinus1(int* memoryStart, long elements)
{
var bytesToErase = elements * sizeof(int);
if (bytesToErase <= uint.MaxValue)
{
Delegate(new IntPtr(memoryStart), (uint)bytesToErase);
}
else
{
Console.WriteLine($"{nameof(MemoryBuffer)}: Using slow memory clearing");
for (var i = 0; i < elements; i++)
{
memoryStart[i] = -1;
}
}
}
public static void ClearWithMinus1(long* memoryStart, long elements)
{
var bytesToErase = elements * sizeof(long);
if (bytesToErase <= uint.MaxValue)
{
Delegate(new IntPtr(memoryStart), (uint)bytesToErase);
}
else
{
Console.WriteLine($"{nameof(MemoryBuffer)}: Using slow memory clearing");
for (var i = 0; i < elements; i++)
{
memoryStart[i] = -1L;
}
}
}
}
}
}
| |
// 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.
// Dummy implementations of non-portable interop methods that just throw PlatformNotSupportedException
namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
public static int GetHRForException(Exception e)
{
return (e != null) ? e.HResult : 0;
}
public static int AddRef(System.IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool AreComObjectsAvailableForCleanup()
{
return false;
}
public static System.IntPtr CreateAggregatedObject(System.IntPtr pOuter, object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Object BindToMoniker(String monikerName)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void CleanupUnusedObjectsInCurrentContext()
{
return;
}
public static System.IntPtr CreateAggregatedObject<T>(System.IntPtr pOuter, T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object CreateWrapperOfType(object o, System.Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int FinalReleaseComObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.IntPtr GetComInterfaceForObject(object o, System.Type T)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.IntPtr GetComInterfaceForObject(object o, System.Type T, System.Runtime.InteropServices.CustomQueryInterfaceMode mode)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.IntPtr GetHINSTANCE(System.Reflection.Module m)
{
if (m == null)
{
throw new ArgumentNullException(nameof(m));
}
return (System.IntPtr) (-1);
}
public static System.IntPtr GetIUnknownForObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject(object obj, System.IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject<T>(T obj, System.IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Object GetTypedObjectForIUnknown(System.IntPtr pUnk, System.Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForIUnknown(System.IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForNativeVariant(System.IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T GetObjectForNativeVariant<T>(System.IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object[] GetObjectsForNativeVariants(System.IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T[] GetObjectsForNativeVariants<T>(System.IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int GetStartComSlot(System.Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.Type GetTypeFromCLSID(System.Guid clsid)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static string GetTypeInfoName(System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetUniqueObjectForIUnknown(System.IntPtr unknown)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool IsComObject(object o)
{
return false;
}
public static int QueryInterface(System.IntPtr pUnk, ref System.Guid iid, out System.IntPtr ppv)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int Release(System.IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int ReleaseComObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void ZeroFreeBSTR(System.IntPtr s)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
public class DispatchWrapper
{
public DispatchWrapper(object obj)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public object WrappedObject
{
get
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
}
public static class ComEventsHelper
{
public static void Combine(object rcw, System.Guid iid, int dispid, System.Delegate d)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.Delegate Remove(object rcw, System.Guid iid, int dispid, System.Delegate d)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
}
| |
/*
* 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.Linq;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using pCampBot.Interfaces;
namespace pCampBot
{
/// <summary>
/// Thread/Bot manager for the application
/// </summary>
public class BotManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int DefaultLoginDelay = 5000;
/// <summary>
/// Is pCampbot in the process of connecting bots?
/// </summary>
public bool ConnectingBots { get; private set; }
/// <summary>
/// Is pCampbot in the process of disconnecting bots?
/// </summary>
public bool DisconnectingBots { get; private set; }
/// <summary>
/// Delay between logins of multiple bots.
/// </summary>
/// <remarks>TODO: This value needs to be configurable by a command line argument.</remarks>
public int LoginDelay { get; set; }
/// <summary>
/// Command console
/// </summary>
protected CommandConsole m_console;
/// <summary>
/// Controls whether bots start out sending agent updates on connection.
/// </summary>
public bool InitBotSendAgentUpdates { get; set; }
/// <summary>
/// Controls whether bots request textures for the object information they receive
/// </summary>
public bool InitBotRequestObjectTextures { get; set; }
/// <summary>
/// Created bots, whether active or inactive.
/// </summary>
protected List<Bot> m_bots;
/// <summary>
/// Random number generator.
/// </summary>
public Random Rng { get; private set; }
/// <summary>
/// Track the assets we have and have not received so we don't endlessly repeat requests.
/// </summary>
public Dictionary<UUID, bool> AssetsReceived { get; private set; }
/// <summary>
/// The regions that we know about.
/// </summary>
public Dictionary<ulong, GridRegion> RegionsKnown { get; private set; }
/// <summary>
/// First name for bots
/// </summary>
private string m_firstName;
/// <summary>
/// Last name stem for bots
/// </summary>
private string m_lastNameStem;
/// <summary>
/// Password for bots
/// </summary>
private string m_password;
/// <summary>
/// Login URI for bots.
/// </summary>
private string m_loginUri;
/// <summary>
/// Start location for bots.
/// </summary>
private string m_startUri;
/// <summary>
/// Postfix bot number at which bot sequence starts.
/// </summary>
private int m_fromBotNumber;
/// <summary>
/// Wear setting for bots.
/// </summary>
private string m_wearSetting;
/// <summary>
/// Behaviour switches for bots.
/// </summary>
private HashSet<string> m_defaultBehaviourSwitches = new HashSet<string>();
/// <summary>
/// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
/// </summary>
public BotManager()
{
InitBotSendAgentUpdates = true;
InitBotRequestObjectTextures = true;
LoginDelay = DefaultLoginDelay;
Rng = new Random(Environment.TickCount);
AssetsReceived = new Dictionary<UUID, bool>();
RegionsKnown = new Dictionary<ulong, GridRegion>();
m_console = CreateConsole();
MainConsole.Instance = m_console;
// Make log4net see the console
//
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
OpenSimAppender consoleAppender = null;
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
consoleAppender = (OpenSimAppender)appender;
consoleAppender.Console = m_console;
break;
}
}
m_console.Commands.AddCommand(
"Bots", false, "shutdown", "shutdown", "Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand(
"Bots", false, "quit", "quit", "Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand(
"Bots", false, "connect", "connect [<n>]", "Connect bots",
"If an <n> is given, then the first <n> disconnected bots by postfix number are connected.\n"
+ "If no <n> is given, then all currently disconnected bots are connected.",
HandleConnect);
m_console.Commands.AddCommand(
"Bots", false, "disconnect", "disconnect [<n>]", "Disconnect bots",
"Disconnecting bots will interupt any bot connection process, including connection on startup.\n"
+ "If an <n> is given, then the last <n> connected bots by postfix number are disconnected.\n"
+ "If no <n> is given, then all currently connected bots are disconnected.",
HandleDisconnect);
m_console.Commands.AddCommand(
"Bots", false, "add behaviour", "add behaviour <abbreviated-name> [<bot-number>]",
"Add a behaviour to a bot",
"If no bot number is specified then behaviour is added to all bots.\n"
+ "Can be performed on connected or disconnected bots.",
HandleAddBehaviour);
m_console.Commands.AddCommand(
"Bots", false, "remove behaviour", "remove behaviour <abbreviated-name> [<bot-number>]",
"Remove a behaviour from a bot",
"If no bot number is specified then behaviour is added to all bots.\n"
+ "Can be performed on connected or disconnected bots.",
HandleRemoveBehaviour);
m_console.Commands.AddCommand(
"Bots", false, "sit", "sit", "Sit all bots on the ground.",
HandleSit);
m_console.Commands.AddCommand(
"Bots", false, "stand", "stand", "Stand all bots.",
HandleStand);
m_console.Commands.AddCommand(
"Bots", false, "set bots", "set bots <key> <value>", "Set a setting for all bots.", HandleSetBots);
m_console.Commands.AddCommand(
"Bots", false, "show regions", "show regions", "Show regions known to bots", HandleShowRegions);
m_console.Commands.AddCommand(
"Bots", false, "show bots", "show bots", "Shows the status of all bots", HandleShowBotsStatus);
m_console.Commands.AddCommand(
"Bots", false, "show bot", "show bot <bot-number>",
"Shows the detailed status and settings of a particular bot.", HandleShowBotStatus);
m_bots = new List<Bot>();
}
/// <summary>
/// Startup number of bots specified in the starting arguments
/// </summary>
/// <param name="botcount">How many bots to start up</param>
/// <param name="cs">The configuration for the bots to use</param>
public void CreateBots(int botcount, IConfig startupConfig)
{
m_firstName = startupConfig.GetString("firstname");
m_lastNameStem = startupConfig.GetString("lastname");
m_password = startupConfig.GetString("password");
m_loginUri = startupConfig.GetString("loginuri");
m_fromBotNumber = startupConfig.GetInt("from", 0);
m_wearSetting = startupConfig.GetString("wear", "no");
m_startUri = ParseInputStartLocationToUri(startupConfig.GetString("start", "last"));
Array.ForEach<string>(
startupConfig.GetString("behaviours", "p").Split(new char[] { ',' }), b => m_defaultBehaviourSwitches.Add(b));
for (int i = 0; i < botcount; i++)
{
lock (m_bots)
{
string lastName = string.Format("{0}_{1}", m_lastNameStem, i + m_fromBotNumber);
CreateBot(
this,
CreateBehavioursFromAbbreviatedNames(m_defaultBehaviourSwitches),
m_firstName, lastName, m_password, m_loginUri, m_startUri, m_wearSetting);
}
}
}
private List<IBehaviour> CreateBehavioursFromAbbreviatedNames(HashSet<string> abbreviatedNames)
{
// We must give each bot its own list of instantiated behaviours since they store state.
List<IBehaviour> behaviours = new List<IBehaviour>();
// Hard-coded for now
foreach (string abName in abbreviatedNames)
{
IBehaviour newBehaviour = null;
if (abName == "c")
newBehaviour = new CrossBehaviour();
if (abName == "g")
newBehaviour = new GrabbingBehaviour();
if (abName == "n")
newBehaviour = new NoneBehaviour();
if (abName == "p")
newBehaviour = new PhysicsBehaviour();
if (abName == "t")
newBehaviour = new TeleportBehaviour();
if (newBehaviour != null)
{
behaviours.Add(newBehaviour);
}
else
{
MainConsole.Instance.OutputFormat("No behaviour with abbreviated name {0} found", abName);
}
}
return behaviours;
}
public void ConnectBots(int botcount)
{
ConnectingBots = true;
Thread connectBotThread = new Thread(o => ConnectBotsInternal(botcount));
connectBotThread.Name = "Bots connection thread";
connectBotThread.Start();
}
private void ConnectBotsInternal(int botCount)
{
MainConsole.Instance.OutputFormat(
"[BOT MANAGER]: Starting {0} bots connecting to {1}, location {2}, named {3} {4}_<n>",
botCount,
m_loginUri,
m_startUri,
m_firstName,
m_lastNameStem);
MainConsole.Instance.OutputFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
MainConsole.Instance.OutputFormat("[BOT MANAGER]: BotsSendAgentUpdates is {0}", InitBotSendAgentUpdates);
MainConsole.Instance.OutputFormat("[BOT MANAGER]: InitBotRequestObjectTextures is {0}", InitBotRequestObjectTextures);
int connectedBots = 0;
for (int i = 0; i < m_bots.Count; i++)
{
lock (m_bots)
{
if (DisconnectingBots)
{
MainConsole.Instance.Output(
"[BOT MANAGER]: Aborting bot connection due to user-initiated disconnection");
break;
}
if (m_bots[i].ConnectionState == ConnectionState.Disconnected)
{
m_bots[i].Connect();
connectedBots++;
if (connectedBots >= botCount)
break;
// Stagger logins
Thread.Sleep(LoginDelay);
}
}
}
ConnectingBots = false;
}
/// <summary>
/// Parses the command line start location to a start string/uri that the login mechanism will recognize.
/// </summary>
/// <returns>
/// The input start location to URI.
/// </returns>
/// <param name='startLocation'>
/// Start location.
/// </param>
private string ParseInputStartLocationToUri(string startLocation)
{
if (startLocation == "home" || startLocation == "last")
return startLocation;
string regionName;
// Just a region name or only one (!) extra component. Like a viewer, we will stick 128/128/0 on the end
Vector3 startPos = new Vector3(128, 128, 0);
string[] startLocationComponents = startLocation.Split('/');
regionName = startLocationComponents[0];
if (startLocationComponents.Length >= 2)
{
float.TryParse(startLocationComponents[1], out startPos.X);
if (startLocationComponents.Length >= 3)
{
float.TryParse(startLocationComponents[2], out startPos.Y);
if (startLocationComponents.Length >= 4)
float.TryParse(startLocationComponents[3], out startPos.Z);
}
}
return string.Format("uri:{0}&{1}&{2}&{3}", regionName, startPos.X, startPos.Y, startPos.Z);
}
/// <summary>
/// This creates a bot but does not start it.
/// </summary>
/// <param name="bm"></param>
/// <param name="behaviours">Behaviours for this bot to perform.</param>
/// <param name="firstName">First name</param>
/// <param name="lastName">Last name</param>
/// <param name="password">Password</param>
/// <param name="loginUri">Login URI</param>
/// <param name="startLocation">Location to start the bot. Can be "last", "home" or a specific sim name.</param>
/// <param name="wearSetting"></param>
public void CreateBot(
BotManager bm, List<IBehaviour> behaviours,
string firstName, string lastName, string password, string loginUri, string startLocation, string wearSetting)
{
MainConsole.Instance.OutputFormat(
"[BOT MANAGER]: Creating bot {0} {1}, behaviours are {2}",
firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
Bot pb = new Bot(bm, behaviours, firstName, lastName, password, startLocation, loginUri);
pb.wear = wearSetting;
pb.Client.Settings.SEND_AGENT_UPDATES = InitBotSendAgentUpdates;
pb.RequestObjectTextures = InitBotRequestObjectTextures;
pb.OnConnected += handlebotEvent;
pb.OnDisconnected += handlebotEvent;
m_bots.Add(pb);
}
/// <summary>
/// High level connnected/disconnected events so we can keep track of our threads by proxy
/// </summary>
/// <param name="callbot"></param>
/// <param name="eventt"></param>
private void handlebotEvent(Bot callbot, EventType eventt)
{
switch (eventt)
{
case EventType.CONNECTED:
{
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
break;
}
case EventType.DISCONNECTED:
{
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
break;
}
}
}
/// <summary>
/// Standard CreateConsole routine
/// </summary>
/// <returns></returns>
protected CommandConsole CreateConsole()
{
return new LocalConsole("pCampbot");
}
private void HandleConnect(string module, string[] cmd)
{
if (ConnectingBots)
{
MainConsole.Instance.Output("Still connecting bots. Please wait for previous process to complete.");
return;
}
lock (m_bots)
{
int botsToConnect;
int disconnectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Disconnected);
if (cmd.Length == 1)
{
botsToConnect = disconnectedBots;
}
else
{
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToConnect))
return;
botsToConnect = Math.Min(botsToConnect, disconnectedBots);
}
MainConsole.Instance.OutputFormat("Connecting {0} bots", botsToConnect);
ConnectBots(botsToConnect);
}
}
private void HandleAddBehaviour(string module, string[] cmd)
{
if (cmd.Length < 3 || cmd.Length > 4)
{
MainConsole.Instance.OutputFormat("Usage: add behaviour <abbreviated-behaviour> [<bot-number>]");
return;
}
string rawBehaviours = cmd[2];
List<Bot> botsToEffect = new List<Bot>();
if (cmd.Length == 3)
{
lock (m_bots)
botsToEffect.AddRange(m_bots);
}
else
{
int botNumber;
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
botsToEffect.Add(bot);
}
HashSet<string> rawAbbreviatedSwitchesToAdd = new HashSet<string>();
Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => rawAbbreviatedSwitchesToAdd.Add(b));
foreach (Bot bot in botsToEffect)
{
List<IBehaviour> behavioursAdded = new List<IBehaviour>();
foreach (IBehaviour behaviour in CreateBehavioursFromAbbreviatedNames(rawAbbreviatedSwitchesToAdd))
{
if (bot.AddBehaviour(behaviour))
behavioursAdded.Add(behaviour);
}
MainConsole.Instance.OutputFormat(
"Added behaviours {0} to bot {1}",
string.Join(", ", behavioursAdded.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
}
}
private void HandleRemoveBehaviour(string module, string[] cmd)
{
if (cmd.Length < 3 || cmd.Length > 4)
{
MainConsole.Instance.OutputFormat("Usage: remove behaviour <abbreviated-behaviour> [<bot-number>]");
return;
}
string rawBehaviours = cmd[2];
List<Bot> botsToEffect = new List<Bot>();
if (cmd.Length == 3)
{
lock (m_bots)
botsToEffect.AddRange(m_bots);
}
else
{
int botNumber;
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
botsToEffect.Add(bot);
}
HashSet<string> abbreviatedBehavioursToRemove = new HashSet<string>();
Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => abbreviatedBehavioursToRemove.Add(b));
foreach (Bot bot in botsToEffect)
{
List<IBehaviour> behavioursRemoved = new List<IBehaviour>();
foreach (string b in abbreviatedBehavioursToRemove)
{
IBehaviour behaviour;
if (bot.TryGetBehaviour(b, out behaviour))
{
bot.RemoveBehaviour(b);
behavioursRemoved.Add(behaviour);
}
}
MainConsole.Instance.OutputFormat(
"Removed behaviours {0} to bot {1}",
string.Join(", ", behavioursRemoved.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
}
}
private void HandleDisconnect(string module, string[] cmd)
{
lock (m_bots)
{
int botsToDisconnect;
int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
if (cmd.Length == 1)
{
botsToDisconnect = connectedBots;
}
else
{
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToDisconnect))
return;
botsToDisconnect = Math.Min(botsToDisconnect, connectedBots);
}
DisconnectingBots = true;
MainConsole.Instance.OutputFormat("Disconnecting {0} bots", botsToDisconnect);
int disconnectedBots = 0;
for (int i = m_bots.Count - 1; i >= 0; i--)
{
if (disconnectedBots >= botsToDisconnect)
break;
Bot thisBot = m_bots[i];
if (thisBot.ConnectionState == ConnectionState.Connected)
{
Util.FireAndForget(o => thisBot.Disconnect());
disconnectedBots++;
}
}
DisconnectingBots = false;
}
}
private void HandleSit(string module, string[] cmd)
{
lock (m_bots)
{
m_bots.ForEach(b => b.SitOnGround());
}
}
private void HandleStand(string module, string[] cmd)
{
lock (m_bots)
{
m_bots.ForEach(b => b.Stand());
}
}
private void HandleShutdown(string module, string[] cmd)
{
lock (m_bots)
{
int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
if (connectedBots > 0)
{
MainConsole.Instance.OutputFormat("Please disconnect {0} connected bots first", connectedBots);
return;
}
}
MainConsole.Instance.Output("Shutting down");
Environment.Exit(0);
}
private void HandleSetBots(string module, string[] cmd)
{
string key = cmd[2];
string rawValue = cmd[3];
if (key == "SEND_AGENT_UPDATES")
{
bool newSendAgentUpdatesSetting;
if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newSendAgentUpdatesSetting))
return;
MainConsole.Instance.OutputFormat(
"Setting SEND_AGENT_UPDATES to {0} for all bots", newSendAgentUpdatesSetting);
lock (m_bots)
m_bots.ForEach(b => b.Client.Settings.SEND_AGENT_UPDATES = newSendAgentUpdatesSetting);
}
else
{
MainConsole.Instance.Output("Error: Only setting currently available is SEND_AGENT_UPDATES");
}
}
private void HandleShowRegions(string module, string[] cmd)
{
string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
lock (RegionsKnown)
{
foreach (GridRegion region in RegionsKnown.Values)
{
MainConsole.Instance.OutputFormat(
outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
}
}
}
private void HandleShowBotsStatus(string module, string[] cmd)
{
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Name", 24);
cdt.AddColumn("Region", 24);
cdt.AddColumn("Status", 13);
cdt.AddColumn("Conns", 5);
cdt.AddColumn("Behaviours", 20);
Dictionary<ConnectionState, int> totals = new Dictionary<ConnectionState, int>();
foreach (object o in Enum.GetValues(typeof(ConnectionState)))
totals[(ConnectionState)o] = 0;
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
Simulator currentSim = bot.Client.Network.CurrentSim;
totals[bot.ConnectionState]++;
cdt.AddRow(
bot.Name,
currentSim != null ? currentSim.Name : "(none)",
bot.ConnectionState,
bot.SimulatorsCount,
string.Join(",", bot.Behaviours.Keys.ToArray()));
}
}
MainConsole.Instance.Output(cdt.ToString());
ConsoleDisplayList cdl = new ConsoleDisplayList();
foreach (KeyValuePair<ConnectionState, int> kvp in totals)
cdl.AddRow(kvp.Key, kvp.Value);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleShowBotStatus(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.Output("Usage: show bot <n>");
return;
}
int botNumber;
if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, cmd[2], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("Name", bot.Name);
cdl.AddRow("Status", bot.ConnectionState);
Simulator currentSim = bot.Client.Network.CurrentSim;
cdl.AddRow("Region", currentSim != null ? currentSim.Name : "(none)");
List<Simulator> connectedSimulators = bot.Simulators;
List<string> simulatorNames = connectedSimulators.ConvertAll<string>(cs => cs.Name);
cdl.AddRow("Connections", string.Join(", ", simulatorNames.ToArray()));
MainConsole.Instance.Output(cdl.ToString());
MainConsole.Instance.Output("Settings");
ConsoleDisplayList statusCdl = new ConsoleDisplayList();
statusCdl.AddRow(
"Behaviours",
string.Join(", ", bot.Behaviours.Values.ToList().ConvertAll<string>(b => b.Name).ToArray()));
GridClient botClient = bot.Client;
statusCdl.AddRow("SEND_AGENT_UPDATES", botClient.Settings.SEND_AGENT_UPDATES);
MainConsole.Instance.Output(statusCdl.ToString());
}
/// <summary>
/// Get a specific bot from its number.
/// </summary>
/// <returns>null if no bot was found</returns>
/// <param name='botNumber'></param>
private Bot GetBotFromNumber(int botNumber)
{
string name = GenerateBotNameFromNumber(botNumber);
Bot bot;
lock (m_bots)
bot = m_bots.Find(b => b.Name == name);
return bot;
}
private string GenerateBotNameFromNumber(int botNumber)
{
return string.Format("{0} {1}_{2}", m_firstName, m_lastNameStem, botNumber);
}
internal void Grid_GridRegion(object o, GridRegionEventArgs args)
{
lock (RegionsKnown)
{
GridRegion newRegion = args.Region;
if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
{
return;
}
else
{
m_log.DebugFormat(
"[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
RegionsKnown[newRegion.RegionHandle] = newRegion;
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowConcatSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Util.Internal;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowConcatSpec : BaseTwoStreamsSetup<int>
{
public FlowConcatSpec(ITestOutputHelper output = null) : base(output)
{
}
protected override TestSubscriber.Probe<int> Setup(IPublisher<int> p1, IPublisher<int> p2)
{
var subscriber = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(p1)
.Concat(Source.FromPublisher(p2))
.RunWith(Sink.FromSubscriber(subscriber), Materializer);
return subscriber;
}
[Fact]
public void A_Concat_for_Flow_must_be_able_to_concat_Flow_with_Source()
{
var f1 = Flow.Create<int>().Select(x => x + "-s");
var s1 = Source.From(new[] {1, 2, 3});
var s2 = Source.From(new[] { 4,5,6 }).Select(x=> x + "-s");
var subs = TestSubscriber.CreateManualProbe<string>(this);
var subSink = Sink.AsPublisher<string>(false);
var res = f1.Concat(s2).RunWith(s1, subSink, Materializer).Item2;
res.Subscribe(subs);
var sub = subs.ExpectSubscription();
sub.Request(9);
Enumerable.Range(1, 6).ForEach(e=>subs.ExpectNext(e + "-s"));
subs.ExpectComplete();
}
[Fact]
public void A_Concat_for_Flow_must_be_able_to_prepend_a_Source_to_a_Flow()
{
var s1 = Source.From(new[] { 1, 2, 3 }).Select(x => x + "-s");
var s2 = Source.From(new[] { 4, 5, 6 });
var f2 = Flow.Create<int>().Select(x => x + "-s");
var subs = TestSubscriber.CreateManualProbe<string>(this);
var subSink = Sink.AsPublisher<string>(false);
var res = f2.Prepend(s1).RunWith(s2, subSink, Materializer).Item2;
res.Subscribe(subs);
var sub = subs.ExpectSubscription();
sub.Request(9);
Enumerable.Range(1, 6).ForEach(e => subs.ExpectNext(e + "-s"));
subs.ExpectComplete();
}
[Fact]
public void A_Concat_for_Flow_must_work_with_one_immediately_completed_and_one_nonempty_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber1 = Setup(CompletedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
var subscription1 = subscriber1.ExpectSubscription();
subscription1.Request(5);
Enumerable.Range(1, 4).ForEach(x => subscriber1.ExpectNext(x));
subscriber1.ExpectComplete();
var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), CompletedPublisher<int>());
var subscription2 = subscriber2.ExpectSubscription();
subscription2.Request(5);
Enumerable.Range(1, 4).ForEach(x => subscriber2.ExpectNext(x));
subscriber2.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Concat_for_Flow_must_work_with_one_immediately_failed_and_one_nonempty_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber = Setup(FailedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
subscriber.ExpectSubscriptionAndError().Should().BeOfType<TestException>();
}, Materializer);
}
[Fact]
public void A_Concat_for_Flow_must_work_with_one_nonempty_and_one_immediately_failed_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), FailedPublisher<int>());
subscriber.ExpectSubscription().Request(5);
var errorSignalled = Enumerable.Range(1, 4)
.Aggregate(false, (b, e) => b || subscriber.ExpectNextOrError() is TestException);
if (!errorSignalled)
subscriber.ExpectSubscriptionAndError().Should().BeOfType<TestException>();
}, Materializer);
}
[Fact]
public void A_Concat_for_Flow_must_work_with_one_delayed_failed_and_one_nonempty_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber = Setup(SoonToFailPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
subscriber.ExpectSubscriptionAndError().Should().BeOfType<TestException>();
}, Materializer);
}
[Fact]
public void A_Concat_for_Flow_must_work_with_one_nonempty_and_one_delayed_failed_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), SoonToFailPublisher<int>());
subscriber.ExpectSubscription().Request(5);
var errorSignalled = Enumerable.Range(1, 4)
.Aggregate(false, (b, e) => b || subscriber.ExpectNextOrError() is TestException);
if (!errorSignalled)
subscriber.ExpectSubscriptionAndError().Should().BeOfType<TestException>();
}, Materializer);
}
[Fact]
public void A_Concat_for_Flow_must_correctly_handle_async_errors_in_secondary_upstream()
{
this.AssertAllStagesStopped(() =>
{
var promise = new TaskCompletionSource<int>();
var subscriber = TestSubscriber.CreateManualProbe<int>(this);
Source.From(Enumerable.Range(1, 3))
.Concat(Source.FromTask(promise.Task))
.RunWith(Sink.FromSubscriber(subscriber), Materializer);
var subscription = subscriber.ExpectSubscription();
subscription.Request(4);
Enumerable.Range(1, 3).ForEach(x => subscriber.ExpectNext(x));
promise.SetException(TestException());
subscriber.ExpectError().Should().BeOfType<TestException>();
}, Materializer);
}
[Fact]
public void A_Concat_for_Flow_must_work_with_Source_DSL()
{
this.AssertAllStagesStopped(() =>
{
var testSource =
Source.From(Enumerable.Range(1, 5))
.ConcatMaterialized(Source.From(Enumerable.Range(6, 5)), Keep.Both)
.Grouped(1000);
var task = testSource.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1,10));
var runnable = testSource.ToMaterialized(Sink.Ignore<IEnumerable<int>>(), Keep.Left);
var t = runnable.Run(Materializer);
t.Item1.Should().BeOfType<NotUsed>();
t.Item2.Should().BeOfType<NotUsed>();
runnable.MapMaterializedValue(_ => "boo").Run(Materializer).Should().Be("boo");
}, Materializer);
}
[Fact]
public void A_Concat_for_Flow_must_work_with_Flow_DSL()
{
this.AssertAllStagesStopped(() =>
{
var testFlow = Flow.Create<int>()
.ConcatMaterialized(Source.From(Enumerable.Range(6, 5)), Keep.Both)
.Grouped(1000);
var task = Source.From(Enumerable.Range(1, 5))
.ViaMaterialized(testFlow, Keep.Both)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
var runnable =
Source.From(Enumerable.Range(1, 5))
.ViaMaterialized(testFlow, Keep.Both)
.To(Sink.Ignore<IEnumerable<int>>());
runnable.Invoking(r => r.Run(Materializer)).ShouldNotThrow();
runnable.MapMaterializedValue(_ => "boo").Run(Materializer).Should().Be("boo");
}, Materializer);
}
[Fact(Skip = "ConcatMaterialized type conflict")]
public void A_Concat_for_Flow_must_work_with_Flow_DSL2()
{
this.AssertAllStagesStopped(() =>
{
var testFlow = Flow.Create<int>()
.ConcatMaterialized(Source.From(Enumerable.Range(6, 5)), Keep.Both)
.Grouped(1000);
var task = Source.From(Enumerable.Range(1, 5))
.ViaMaterialized(testFlow, Keep.Both)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
//var sink = testFlow.ConcatMaterialized(Source.From(Enumerable.Range(1, 5)), Keep.Both)
// .To(Sink.Ignore<IEnumerable<int>>())
// .MapMaterializedValue(
// x =>
// {
// x.Item1.Item1.Should().BeOfType<NotUsed>();
// x.Item1.Item2.Should().BeOfType<NotUsed>();
// x.Item2.Should().BeOfType<NotUsed>();
// return "boo";
// });
//Source.From(Enumerable.Range(10, 6)).RunWith(sink, Materializer).Should().Be("boo");
}, Materializer);
}
[Fact]
public void A_Concat_for_Flow_must_subscribe_at_one_to_initial_source_and_to_one_that_it_is_concat_to()
{
this.AssertAllStagesStopped(() =>
{
var publisher1 = TestPublisher.CreateProbe<int>(this);
var publisher2 = TestPublisher.CreateProbe<int>(this);
var probeSink =
Source.FromPublisher(publisher1)
.Concat(Source.FromPublisher(publisher2))
.RunWith(this.SinkProbe<int>(), Materializer);
var sub1 = publisher1.ExpectSubscription();
var sub2 = publisher2.ExpectSubscription();
var subSink = probeSink.ExpectSubscription();
sub1.SendNext(1);
subSink.Request(1);
probeSink.ExpectNext(1);
sub1.SendComplete();
sub2.SendNext(2);
subSink.Request(1);
probeSink.ExpectNext(2);
sub2.SendComplete();
probeSink.ExpectComplete();
}, Materializer);
}
}
}
| |
namespace SPALM.SPSF.Library
{
partial class SelectionForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SelectionForm));
this.panel1 = new System.Windows.Forms.Panel();
this.searchgroup = new System.Windows.Forms.Panel();
this.button_clear = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.button_find = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.panel2 = new System.Windows.Forms.Panel();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.groupBox3 = new System.Windows.Forms.Panel();
this.treeView = new System.Windows.Forms.TreeView();
this.selectedItem = new System.Windows.Forms.Panel();
this.selectedGroup = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.selectedDescription = new System.Windows.Forms.Label();
this.selectedValue = new System.Windows.Forms.Label();
this.selectedName = new System.Windows.Forms.Label();
this.panel3 = new System.Windows.Forms.Panel();
this.button_cancel = new System.Windows.Forms.Button();
this.buton_ok = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.searchgroup.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.groupBox3.SuspendLayout();
this.selectedItem.SuspendLayout();
this.panel3.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.searchgroup);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Padding = new System.Windows.Forms.Padding(5);
this.panel1.Size = new System.Drawing.Size(528, 38);
this.panel1.TabIndex = 0;
//
// searchgroup
//
this.searchgroup.Controls.Add(this.button_clear);
this.searchgroup.Controls.Add(this.label1);
this.searchgroup.Controls.Add(this.button_find);
this.searchgroup.Controls.Add(this.textBox1);
this.searchgroup.Dock = System.Windows.Forms.DockStyle.Fill;
this.searchgroup.Location = new System.Drawing.Point(5, 5);
this.searchgroup.Name = "searchgroup";
this.searchgroup.Size = new System.Drawing.Size(518, 28);
this.searchgroup.TabIndex = 0;
this.searchgroup.Text = "Search";
//
// button_clear
//
this.button_clear.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button_clear.Location = new System.Drawing.Point(456, 1);
this.button_clear.Name = "button_clear";
this.button_clear.Size = new System.Drawing.Size(61, 23);
this.button_clear.TabIndex = 3;
this.button_clear.Text = "Clear";
this.button_clear.UseVisualStyleBackColor = true;
this.button_clear.Click += new System.EventHandler(this.button1_Click_1);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 6);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(41, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Search";
//
// button_find
//
this.button_find.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button_find.Location = new System.Drawing.Point(389, 1);
this.button_find.Name = "button_find";
this.button_find.Size = new System.Drawing.Size(61, 23);
this.button_find.TabIndex = 1;
this.button_find.Text = "Find";
this.button_find.UseVisualStyleBackColor = true;
this.button_find.Click += new System.EventHandler(this.button3_Click);
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(64, 3);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(313, 20);
this.textBox1.TabIndex = 0;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
this.textBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyUp);
//
// panel2
//
this.panel2.Controls.Add(this.splitContainer1);
this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel2.Location = new System.Drawing.Point(0, 38);
this.panel2.Name = "panel2";
this.panel2.Padding = new System.Windows.Forms.Padding(5);
this.panel2.Size = new System.Drawing.Size(528, 357);
this.panel2.TabIndex = 1;
this.panel2.Paint += new System.Windows.Forms.PaintEventHandler(this.panel2_Paint);
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
this.splitContainer1.Location = new System.Drawing.Point(5, 5);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.groupBox3);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.selectedItem);
this.splitContainer1.Size = new System.Drawing.Size(518, 347);
this.splitContainer1.SplitterDistance = 241;
this.splitContainer1.TabIndex = 0;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.treeView);
this.groupBox3.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox3.Location = new System.Drawing.Point(0, 0);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(518, 241);
this.groupBox3.TabIndex = 0;
this.groupBox3.Text = "Available Items";
//
// treeView
//
this.treeView.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView.Location = new System.Drawing.Point(0, 0);
this.treeView.Name = "treeView";
this.treeView.ShowNodeToolTips = true;
this.treeView.Size = new System.Drawing.Size(518, 241);
this.treeView.TabIndex = 0;
this.treeView.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.treeView_AfterCheck);
this.treeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView_AfterSelect);
this.treeView.DoubleClick += new System.EventHandler(this.treeView_DoubleClick);
//
// selectedItem
//
this.selectedItem.Controls.Add(this.selectedGroup);
this.selectedItem.Controls.Add(this.label5);
this.selectedItem.Controls.Add(this.label4);
this.selectedItem.Controls.Add(this.label3);
this.selectedItem.Controls.Add(this.label2);
this.selectedItem.Controls.Add(this.selectedDescription);
this.selectedItem.Controls.Add(this.selectedValue);
this.selectedItem.Controls.Add(this.selectedName);
this.selectedItem.Dock = System.Windows.Forms.DockStyle.Fill;
this.selectedItem.Location = new System.Drawing.Point(0, 0);
this.selectedItem.Name = "selectedItem";
this.selectedItem.Size = new System.Drawing.Size(518, 102);
this.selectedItem.TabIndex = 0;
this.selectedItem.Text = "Selected Item";
//
// selectedGroup
//
this.selectedGroup.Location = new System.Drawing.Point(74, 46);
this.selectedGroup.Name = "selectedGroup";
this.selectedGroup.Size = new System.Drawing.Size(437, 14);
this.selectedGroup.TabIndex = 7;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(9, 46);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(39, 13);
this.label5.TabIndex = 6;
this.label5.Text = "Group:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(9, 66);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(63, 13);
this.label4.TabIndex = 5;
this.label4.Text = "Description:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(9, 27);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(37, 13);
this.label3.TabIndex = 4;
this.label3.Text = "Value:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(10, 7);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(38, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Name:";
//
// selectedDescription
//
this.selectedDescription.Location = new System.Drawing.Point(74, 66);
this.selectedDescription.Name = "selectedDescription";
this.selectedDescription.Size = new System.Drawing.Size(437, 36);
this.selectedDescription.TabIndex = 2;
//
// selectedValue
//
this.selectedValue.Location = new System.Drawing.Point(74, 27);
this.selectedValue.Name = "selectedValue";
this.selectedValue.Size = new System.Drawing.Size(437, 13);
this.selectedValue.TabIndex = 1;
//
// selectedName
//
this.selectedName.Location = new System.Drawing.Point(74, 5);
this.selectedName.Name = "selectedName";
this.selectedName.Size = new System.Drawing.Size(438, 15);
this.selectedName.TabIndex = 0;
//
// panel3
//
this.panel3.Controls.Add(this.button_cancel);
this.panel3.Controls.Add(this.buton_ok);
this.panel3.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel3.Location = new System.Drawing.Point(0, 395);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(528, 37);
this.panel3.TabIndex = 2;
//
// button_cancel
//
this.button_cancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button_cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button_cancel.Location = new System.Drawing.Point(447, 6);
this.button_cancel.Name = "button_cancel";
this.button_cancel.Size = new System.Drawing.Size(75, 23);
this.button_cancel.TabIndex = 1;
this.button_cancel.Text = "Cancel";
this.button_cancel.UseVisualStyleBackColor = true;
//
// buton_ok
//
this.buton_ok.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buton_ok.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buton_ok.Location = new System.Drawing.Point(366, 6);
this.buton_ok.Name = "buton_ok";
this.buton_ok.Size = new System.Drawing.Size(75, 23);
this.buton_ok.TabIndex = 0;
this.buton_ok.Text = "OK";
this.buton_ok.UseVisualStyleBackColor = true;
this.buton_ok.Click += new System.EventHandler(this.button1_Click);
//
// SelectionForm
//
this.AcceptButton = this.button_find;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.button_cancel;
this.ClientSize = new System.Drawing.Size(528, 432);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Controls.Add(this.panel3);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "SelectionForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Selection";
this.panel1.ResumeLayout(false);
this.searchgroup.ResumeLayout(false);
this.searchgroup.PerformLayout();
this.panel2.ResumeLayout(false);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.selectedItem.ResumeLayout(false);
this.selectedItem.PerformLayout();
this.panel3.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Button button_cancel;
private System.Windows.Forms.Button buton_ok;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.Panel groupBox3;
private System.Windows.Forms.TreeView treeView;
private System.Windows.Forms.Panel selectedItem;
private System.Windows.Forms.Button button_find;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label selectedName;
private System.Windows.Forms.Label selectedValue;
private System.Windows.Forms.Label selectedDescription;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button_clear;
private System.Windows.Forms.Label selectedGroup;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Panel searchgroup;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
{
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
public abstract class TextReader : IDisposable
{
public static readonly TextReader Null = new NullTextReader();
protected TextReader() { }
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
[Pure]
public virtual int Peek()
{
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int n = 0;
do
{
int ch = Read();
if (ch == -1)
{
break;
}
buffer[index + n++] = (char)ch;
} while (n < count);
return n;
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual string ReadToEnd()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(char[] buffer, int index, int count)
{
int i, n = 0;
do
{
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual string ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true)
{
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n')
{
Read();
}
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0)
{
return sb.ToString();
}
return null;
}
#region Task based Async APIs
public virtual Task<string> ReadLineAsync()
{
return Task<String>.Factory.StartNew(state =>
{
return ((TextReader)state).ReadLine();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public async virtual Task<string> ReadToEndAsync()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = await ReadAsyncInternal(chars, 0, chars.Length).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncInternal(buffer, index, count);
}
internal virtual Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length - index >= count);
var tuple = new Tuple<TextReader, char[], int, int>(this, buffer, index, count);
return Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, char[], int, int>)state;
return t.Item1.Read(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadBlockAsyncInternal(buffer, index, count);
}
private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length - index >= count);
int i, n = 0;
do
{
i = await ReadAsyncInternal(buffer, index + n, count - n).ConfigureAwait(false);
n += i;
} while (i > 0 && n < count);
return n;
}
#endregion
private sealed class NullTextReader : TextReader
{
public NullTextReader() { }
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override string ReadLine()
{
return null;
}
}
}
}
| |
// <copyright file="Keys.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
namespace OpenQA.Selenium
{
/// <summary>
/// Representations of keys able to be pressed that are not text keys for sending to the browser.
/// </summary>
public static class Keys
{
/// <summary>
/// Represents the NUL keystroke.
/// </summary>
public static readonly string Null = Convert.ToString(Convert.ToChar(0xE000, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Cancel keystroke.
/// </summary>
public static readonly string Cancel = Convert.ToString(Convert.ToChar(0xE001, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Help keystroke.
/// </summary>
public static readonly string Help = Convert.ToString(Convert.ToChar(0xE002, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Backspace key.
/// </summary>
public static readonly string Backspace = Convert.ToString(Convert.ToChar(0xE003, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Tab key.
/// </summary>
public static readonly string Tab = Convert.ToString(Convert.ToChar(0xE004, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Clear keystroke.
/// </summary>
public static readonly string Clear = Convert.ToString(Convert.ToChar(0xE005, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Return key.
/// </summary>
public static readonly string Return = Convert.ToString(Convert.ToChar(0xE006, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Enter key.
/// </summary>
public static readonly string Enter = Convert.ToString(Convert.ToChar(0xE007, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Shift key.
/// </summary>
public static readonly string Shift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Shift key.
/// </summary>
public static readonly string LeftShift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Control key.
/// </summary>
public static readonly string Control = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Control key.
/// </summary>
public static readonly string LeftControl = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Alt key.
/// </summary>
public static readonly string Alt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Alt key.
/// </summary>
public static readonly string LeftAlt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Pause key.
/// </summary>
public static readonly string Pause = Convert.ToString(Convert.ToChar(0xE00B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Escape key.
/// </summary>
public static readonly string Escape = Convert.ToString(Convert.ToChar(0xE00C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Spacebar key.
/// </summary>
public static readonly string Space = Convert.ToString(Convert.ToChar(0xE00D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Page Up key.
/// </summary>
public static readonly string PageUp = Convert.ToString(Convert.ToChar(0xE00E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Page Down key.
/// </summary>
public static readonly string PageDown = Convert.ToString(Convert.ToChar(0xE00F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the End key.
/// </summary>
public static readonly string End = Convert.ToString(Convert.ToChar(0xE010, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Home key.
/// </summary>
public static readonly string Home = Convert.ToString(Convert.ToChar(0xE011, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the left arrow key.
/// </summary>
public static readonly string Left = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the left arrow key.
/// </summary>
public static readonly string ArrowLeft = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the up arrow key.
/// </summary>
public static readonly string Up = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the up arrow key.
/// </summary>
public static readonly string ArrowUp = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the right arrow key.
/// </summary>
public static readonly string Right = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the right arrow key.
/// </summary>
public static readonly string ArrowRight = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the down arrow key.
/// </summary>
public static readonly string Down = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the down arrow key.
/// </summary>
public static readonly string ArrowDown = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Insert key.
/// </summary>
public static readonly string Insert = Convert.ToString(Convert.ToChar(0xE016, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Delete key.
/// </summary>
public static readonly string Delete = Convert.ToString(Convert.ToChar(0xE017, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the semi-colon key.
/// </summary>
public static readonly string Semicolon = Convert.ToString(Convert.ToChar(0xE018, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the equal sign key.
/// </summary>
public static readonly string Equal = Convert.ToString(Convert.ToChar(0xE019, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
// Number pad keys
/// <summary>
/// Represents the number pad 0 key.
/// </summary>
public static readonly string NumberPad0 = Convert.ToString(Convert.ToChar(0xE01A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 1 key.
/// </summary>
public static readonly string NumberPad1 = Convert.ToString(Convert.ToChar(0xE01B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 2 key.
/// </summary>
public static readonly string NumberPad2 = Convert.ToString(Convert.ToChar(0xE01C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 3 key.
/// </summary>
public static readonly string NumberPad3 = Convert.ToString(Convert.ToChar(0xE01D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 4 key.
/// </summary>
public static readonly string NumberPad4 = Convert.ToString(Convert.ToChar(0xE01E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 5 key.
/// </summary>
public static readonly string NumberPad5 = Convert.ToString(Convert.ToChar(0xE01F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 6 key.
/// </summary>
public static readonly string NumberPad6 = Convert.ToString(Convert.ToChar(0xE020, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 7 key.
/// </summary>
public static readonly string NumberPad7 = Convert.ToString(Convert.ToChar(0xE021, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 8 key.
/// </summary>
public static readonly string NumberPad8 = Convert.ToString(Convert.ToChar(0xE022, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 9 key.
/// </summary>
public static readonly string NumberPad9 = Convert.ToString(Convert.ToChar(0xE023, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad multiplication key.
/// </summary>
public static readonly string Multiply = Convert.ToString(Convert.ToChar(0xE024, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad addition key.
/// </summary>
public static readonly string Add = Convert.ToString(Convert.ToChar(0xE025, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad thousands separator key.
/// </summary>
public static readonly string Separator = Convert.ToString(Convert.ToChar(0xE026, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad subtraction key.
/// </summary>
public static readonly string Subtract = Convert.ToString(Convert.ToChar(0xE027, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad decimal separator key.
/// </summary>
public static readonly string Decimal = Convert.ToString(Convert.ToChar(0xE028, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad division key.
/// </summary>
public static readonly string Divide = Convert.ToString(Convert.ToChar(0xE029, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
// Function keys
/// <summary>
/// Represents the function key F1.
/// </summary>
public static readonly string F1 = Convert.ToString(Convert.ToChar(0xE031, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F2.
/// </summary>
public static readonly string F2 = Convert.ToString(Convert.ToChar(0xE032, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F3.
/// </summary>
public static readonly string F3 = Convert.ToString(Convert.ToChar(0xE033, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F4.
/// </summary>
public static readonly string F4 = Convert.ToString(Convert.ToChar(0xE034, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F5.
/// </summary>
public static readonly string F5 = Convert.ToString(Convert.ToChar(0xE035, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F6.
/// </summary>
public static readonly string F6 = Convert.ToString(Convert.ToChar(0xE036, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F7.
/// </summary>
public static readonly string F7 = Convert.ToString(Convert.ToChar(0xE037, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F8.
/// </summary>
public static readonly string F8 = Convert.ToString(Convert.ToChar(0xE038, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F9.
/// </summary>
public static readonly string F9 = Convert.ToString(Convert.ToChar(0xE039, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F10.
/// </summary>
public static readonly string F10 = Convert.ToString(Convert.ToChar(0xE03A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F11.
/// </summary>
public static readonly string F11 = Convert.ToString(Convert.ToChar(0xE03B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F12.
/// </summary>
public static readonly string F12 = Convert.ToString(Convert.ToChar(0xE03C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key META.
/// </summary>
public static readonly string Meta = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key COMMAND.
/// </summary>
public static readonly string Command = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Zenkaku/Hankaku key.
/// </summary>
public static readonly string ZenkakuHankaku = Convert.ToString(Convert.ToChar(0xE040, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
private static Dictionary<string, string> descriptions;
/// <summary>
/// Gets the description of a specific key.
/// </summary>
/// <param name="value">The key value for which to get the description.</param>
/// <returns>The description of the key.</returns>
internal static object GetDescription(string value)
{
if (descriptions == null)
{
descriptions = new Dictionary<string, string>();
descriptions.Add(Null, "Null");
descriptions.Add(Cancel, "Cancel");
descriptions.Add(Help, "Help");
descriptions.Add(Backspace, "Backspace");
descriptions.Add(Tab, "Tab");
descriptions.Add(Clear, "Clear");
descriptions.Add(Return, "Return");
descriptions.Add(Enter, "Enter");
descriptions.Add(Shift, "Shift");
descriptions.Add(Control, "Control");
descriptions.Add(Alt, "Alt");
descriptions.Add(Pause, "Pause");
descriptions.Add(Escape, "Escape");
descriptions.Add(Space, "Space");
descriptions.Add(PageUp, "Page Up");
descriptions.Add(PageDown, "PageDown");
descriptions.Add(End, "End");
descriptions.Add(Home, "Home");
descriptions.Add(Left, "Left");
descriptions.Add(Up, "Up");
descriptions.Add(Right, "Right");
descriptions.Add(Down, "Down");
descriptions.Add(Insert, "Insert");
descriptions.Add(Delete, "Delete");
descriptions.Add(Semicolon, "Semicolon");
descriptions.Add(Equal, "Equal");
descriptions.Add(NumberPad0, "Number Pad 0");
descriptions.Add(NumberPad1, "Number Pad 1");
descriptions.Add(NumberPad2, "Number Pad 2");
descriptions.Add(NumberPad3, "Number Pad 3");
descriptions.Add(NumberPad4, "Number Pad 4");
descriptions.Add(NumberPad5, "Number Pad 5");
descriptions.Add(NumberPad6, "Number Pad 6");
descriptions.Add(NumberPad7, "Number Pad 7");
descriptions.Add(NumberPad8, "Number Pad 8");
descriptions.Add(NumberPad9, "Number Pad 9");
descriptions.Add(Multiply, "Multiply");
descriptions.Add(Add, "Add");
descriptions.Add(Separator, "Separator");
descriptions.Add(Subtract, "Subtract");
descriptions.Add(Decimal, "Decimal");
descriptions.Add(Divide, "Divide");
descriptions.Add(F1, "F1");
descriptions.Add(F2, "F2");
descriptions.Add(F3, "F3");
descriptions.Add(F4, "F4");
descriptions.Add(F5, "F5");
descriptions.Add(F6, "F6");
descriptions.Add(F7, "F7");
descriptions.Add(F8, "F8");
descriptions.Add(F9, "F9");
descriptions.Add(F10, "F10");
descriptions.Add(F11, "F11");
descriptions.Add(F12, "F12");
descriptions.Add(Meta, "Meta");
descriptions.Add(Command, "Command");
descriptions.Add(ZenkakuHankaku, "Zenkaku Hankaku");
}
if (descriptions.ContainsKey(value))
{
return descriptions[value];
}
return value;
}
}
}
| |
using ClosedXML.Excel;
using ClosedXML.Excel.Drawings;
using NUnit.Framework;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ClosedXML_Tests
{
[TestFixture]
public class PictureTests
{
[Test]
public void CanAddPictureFromBitmap()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML_Examples.BasicTable)).GetManifestResourceStream("ClosedXML_Examples.Resources.SampleImage.jpg"))
using (var bitmap = Bitmap.FromStream(resourceStream) as Bitmap)
{
var picture = ws.AddPicture(bitmap, "MyPicture")
.WithPlacement(XLPicturePlacement.FreeFloating)
.MoveTo(50, 50)
.WithSize(200, 200);
Assert.AreEqual(XLPictureFormat.Jpeg, picture.Format);
Assert.AreEqual(200, picture.Width);
Assert.AreEqual(200, picture.Height);
}
}
}
[Test]
public void CanAddPictureFromFile()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
var path = Path.ChangeExtension(Path.GetTempFileName(), "jpg");
try
{
using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML_Examples.BasicTable)).GetManifestResourceStream("ClosedXML_Examples.Resources.SampleImage.jpg"))
using (var fileStream = File.Create(path))
{
resourceStream.Seek(0, SeekOrigin.Begin);
resourceStream.CopyTo(fileStream);
fileStream.Close();
}
var picture = ws.AddPicture(path)
.WithPlacement(XLPicturePlacement.FreeFloating)
.MoveTo(50, 50);
Assert.AreEqual(XLPictureFormat.Jpeg, picture.Format);
Assert.AreEqual(400, picture.Width);
Assert.AreEqual(400, picture.Height);
}
finally
{
if (File.Exists(path))
File.Delete(path);
}
}
}
[Test]
public void CanScaleImage()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML_Tests.Resource.Images.ImageHandling.png"))
using (var bitmap = Bitmap.FromStream(resourceStream) as Bitmap)
{
var pic = ws.AddPicture(bitmap, "MyPicture")
.WithPlacement(XLPicturePlacement.FreeFloating)
.MoveTo(50, 50);
Assert.AreEqual(252, pic.OriginalWidth);
Assert.AreEqual(152, pic.OriginalHeight);
Assert.AreEqual(252, pic.Width);
Assert.AreEqual(152, pic.Height);
pic.ScaleHeight(0.7);
pic.ScaleWidth(1.2);
Assert.AreEqual(252, pic.OriginalWidth);
Assert.AreEqual(152, pic.OriginalHeight);
Assert.AreEqual(302, pic.Width);
Assert.AreEqual(106, pic.Height);
pic.ScaleHeight(0.7);
pic.ScaleWidth(1.2);
Assert.AreEqual(252, pic.OriginalWidth);
Assert.AreEqual(152, pic.OriginalHeight);
Assert.AreEqual(362, pic.Width);
Assert.AreEqual(74, pic.Height);
pic.ScaleHeight(0.8, true);
pic.ScaleWidth(1.1, true);
Assert.AreEqual(252, pic.OriginalWidth);
Assert.AreEqual(152, pic.OriginalHeight);
Assert.AreEqual(277, pic.Width);
Assert.AreEqual(122, pic.Height);
}
}
}
[Test]
public void TestDefaultPictureNames()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML_Tests.Resource.Images.ImageHandling.png"))
{
ws.AddPicture(stream, XLPictureFormat.Png);
stream.Position = 0;
ws.AddPicture(stream, XLPictureFormat.Png);
stream.Position = 0;
ws.AddPicture(stream, XLPictureFormat.Png).Name = "Picture 4";
stream.Position = 0;
ws.AddPicture(stream, XLPictureFormat.Png);
stream.Position = 0;
}
Assert.AreEqual("Picture 1", ws.Pictures.Skip(0).First().Name);
Assert.AreEqual("Picture 2", ws.Pictures.Skip(1).First().Name);
Assert.AreEqual("Picture 4", ws.Pictures.Skip(2).First().Name);
Assert.AreEqual("Picture 5", ws.Pictures.Skip(3).First().Name);
}
}
[Test]
public void TestDefaultIds()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML_Tests.Resource.Images.ImageHandling.png"))
{
ws.AddPicture(stream, XLPictureFormat.Png);
stream.Position = 0;
ws.AddPicture(stream, XLPictureFormat.Png);
stream.Position = 0;
ws.AddPicture(stream, XLPictureFormat.Png).Name = "Picture 4";
stream.Position = 0;
ws.AddPicture(stream, XLPictureFormat.Png);
stream.Position = 0;
}
Assert.AreEqual(1, ws.Pictures.Skip(0).First().Id);
Assert.AreEqual(2, ws.Pictures.Skip(1).First().Id);
Assert.AreEqual(3, ws.Pictures.Skip(2).First().Id);
Assert.AreEqual(4, ws.Pictures.Skip(3).First().Id);
}
}
[Test]
public void XLMarkerTests()
{
IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1");
XLMarker firstMarker = new XLMarker(ws.Cell(1, 10).Address, new Point(100, 0));
Assert.AreEqual("J", firstMarker.Address.ColumnLetter);
Assert.AreEqual(1, firstMarker.Address.RowNumber);
Assert.AreEqual(100, firstMarker.Offset.X);
Assert.AreEqual(0, firstMarker.Offset.Y);
}
[Test]
public void XLPictureTests()
{
using (var wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("Sheet1");
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML_Tests.Resource.Images.ImageHandling.png"))
{
var pic = ws.AddPicture(stream, XLPictureFormat.Png, "Image1")
.WithPlacement(XLPicturePlacement.FreeFloating)
.MoveTo(220, 155);
Assert.AreEqual(XLPicturePlacement.FreeFloating, pic.Placement);
Assert.AreEqual("Image1", pic.Name);
Assert.AreEqual(XLPictureFormat.Png, pic.Format);
Assert.AreEqual(252, pic.OriginalWidth);
Assert.AreEqual(152, pic.OriginalHeight);
Assert.AreEqual(252, pic.Width);
Assert.AreEqual(152, pic.Height);
Assert.AreEqual(220, pic.Left);
Assert.AreEqual(155, pic.Top);
}
}
}
[Test]
public void CanLoadFileWithImagesAndCopyImagesToNewSheet()
{
using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx")))
using (var wb = new XLWorkbook(stream))
{
var ws = wb.Worksheets.First();
Assert.AreEqual(2, ws.Pictures.Count);
var copy = ws.CopyTo("NewSheet");
Assert.AreEqual(2, copy.Pictures.Count);
}
}
[Test]
public void CanDeletePictures()
{
using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx")))
using (var wb = new XLWorkbook(stream))
{
var ws = wb.Worksheets.First();
ws.Pictures.Delete(ws.Pictures.First());
var pictureName = ws.Pictures.First().Name;
ws.Pictures.Delete(pictureName);
}
}
[Test]
public void PictureRenameTests()
{
using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx")))
using (var wb = new XLWorkbook(stream))
{
var ws = wb.Worksheet("Images3");
var picture = ws.Pictures.First();
Assert.AreEqual("Picture 1", picture.Name);
picture.Name = "picture 1";
picture.Name = "pICture 1";
picture.Name = "Picture 1";
picture = ws.Pictures.Last();
picture.Name = "new name";
Assert.Throws<ArgumentException>(() => picture.Name = "Picture 1");
Assert.Throws<ArgumentException>(() => picture.Name = "picTURE 1");
}
}
[Test]
public void HandleDuplicatePictureIdsAcrossWorksheets()
{
using (var wb = new XLWorkbook())
{
var ws1 = wb.AddWorksheet("Sheet1");
var ws2 = wb.AddWorksheet("Sheet2");
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML_Tests.Resource.Images.ImageHandling.png"))
{
(ws1 as XLWorksheet).AddPicture(stream, "Picture 1", 2);
(ws1 as XLWorksheet).AddPicture(stream, "Picture 2", 3);
//Internal method - used for loading files
var pic = (ws2 as XLWorksheet).AddPicture(stream, "Picture 1", 2)
.WithPlacement(XLPicturePlacement.FreeFloating)
.MoveTo(220, 155) as XLPicture;
var id = pic.Id;
pic.Id = id;
Assert.AreEqual(id, pic.Id);
pic.Id = 3;
Assert.AreEqual(3, pic.Id);
pic.Id = id;
var pic2 = (ws2 as XLWorksheet).AddPicture(stream, "Picture 2", 3)
.WithPlacement(XLPicturePlacement.FreeFloating)
.MoveTo(440, 300) as XLPicture;
}
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class GameController : MonoBehaviour {
public bool isGameStartedFirstTime; // used for initialization
public static GameController instance;
private GameData data;
public bool isMusicOn; // keep track of the music
public int selectedPlayer; // which skin has been selected
public int highScore;
public int currentScore;
public String name;
public bool[] players; //how much skins are unlocked ?
public bool[] achievements;
void Start () {
}
private void Awake()
{
//MakeSingleton();
InitializeGameVariables();
}
public int getPlayed(){
return this.data.getSelectedPlayer();
}
public void setPlayed(int character){
print (character);
this.data.setSelectedPlayer(character);
}
public String getName(){
return this.data.getName ();
}
public void setName(String nom){
print (nom);
this.name = nom;
}
void InitializeGameVariables()
{
Load();
if(data != null)
{
isGameStartedFirstTime = data.getIsGameStartedFirstTime();
}
else
{
isGameStartedFirstTime = true;
}
if (isGameStartedFirstTime)
{
// The game is started for the first time
// Initialisation of the variables
highScore = 0;
selectedPlayer = 0;
name = "Bob";
isGameStartedFirstTime = false;
isMusicOn = false;
players = new bool[2];
achievements = new bool[8];
players[0] = true;
for(int i = 1; i < players.Length; i++)
{
players[i] = false;
}
for(int i = 0; i < achievements.Length; i++)
{
achievements[i] = false;
}
data = new GameData();
data.setHighScore(highScore);
data.setSelectedPlayer(selectedPlayer);
data.setIsGameStartedFirstTime(isGameStartedFirstTime);
data.setIsMusicOn(isMusicOn);
data.setPlayers(players);
data.setAchivements(achievements);
Save();
Load();
}
else
{
// The game has been played already so load game data
highScore = data.getHighScore();
selectedPlayer = data.getSelectedPlayer();
isGameStartedFirstTime = data.getIsGameStartedFirstTime();
isMusicOn = data.getIsGameStartedFirstTime();
players = data.getPlayers();
achievements = data.getAchievements();
}
}
public void MakeSingleton()
{
if(instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
public void Load()
{
FileStream file = null;
try
{
BinaryFormatter bf = new BinaryFormatter();
// We open the encrypted save file
file = File.Open(Application.persistentDataPath + "/GameData.dat", FileMode.Open);
data = (GameData)bf.Deserialize(file);
} catch(Exception e)
{
}finally
{
if(file != null)
{
file.Close();
}
}
}
/**
* Encrypted saves, so that the lurky hacky players
* can't hack their stats :3
**/
public void Save()
{
FileStream file = null;
try
{
BinaryFormatter bf = new BinaryFormatter();
// we create a encrypted file with all the saves from the current player
file = File.Create(Application.persistentDataPath + "/GameData.dat");
if(data != null)
{
// setting our data
data.setHighScore(highScore);
data.setIsGameStartedFirstTime(isGameStartedFirstTime);
data.setPlayers(players);
data.setSelectedPlayer(selectedPlayer);
data.setAchivements(achievements);
data.setIsMusicOn(isMusicOn);
bf.Serialize(file, data);
}
}
// no crash if the file don't yet exists
catch (Exception e)
{
print (e);
}
// executed no matter what
finally
{
if(file != null)
{
file.Close();
}
}
}
}
[Serializable]
class GameData
{
private bool isGameStartedFirstTime; // used for initialization
private bool isMusicOn; // keep track of the music
private int selectedPlayer; // which skin has been selected
private int highScore;
private String name;
private bool[] players; //how much skins are unlocked ?
private bool[] achievements;
// GETTERS - SETTERS
public void setIsGameStartedFirstTime(bool isGameStartedFirstTime)
{
this.isGameStartedFirstTime = isGameStartedFirstTime;
}
public bool getIsGameStartedFirstTime()
{
return this.isGameStartedFirstTime;
}
public void setIsMusicOn(bool isMusicOn)
{
this.isMusicOn = isMusicOn;
}
public bool getIsMusicOn()
{
return this.isMusicOn;
}
public String getName(){
return this.name;
}
public void setName(String nom){
this.name = nom;
}
public void setSelectedPlayer(int selectedPlayer)
{
this.selectedPlayer = selectedPlayer;
}
public int getSelectedPlayer()
{
return this.selectedPlayer;
}
public void setHighScore(int highScore)
{
this.highScore = highScore;
}
public int getHighScore()
{
return this.highScore;
}
public bool[] getPlayers()
{
return this.players;
}
public void setPlayers(bool[] players)
{
this.players = players;
}
public void setAchivements(bool[] achievements)
{
this.achievements = achievements;
}
public bool[] getAchievements()
{
return this.achievements;
}
}
| |
// 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.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Moq;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo
{
public class InteractiveNavigateToTests
{
private readonly Mock<IGlyphService> _glyphServiceMock = new Mock<IGlyphService>(MockBehavior.Strict);
private INavigateToItemProvider _provider;
private NavigateToTestAggregator _aggregator;
private async Task<TestWorkspace> SetupWorkspaceAsync(params string[] files)
{
var workspace = await TestWorkspace.CreateCSharpAsync(files, parseOptions: Options.Script);
var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener();
_provider = new NavigateToItemProvider(
workspace,
_glyphServiceMock.Object,
aggregateListener);
_aggregator = new NavigateToTestAggregator(_provider);
return workspace;
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task NoItemsForEmptyFile()
{
using (var workspace = await SetupWorkspaceAsync())
{
Assert.Empty(_aggregator.GetItems("Hello"));
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindClass()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindNestedClass()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { class Bar { internal class DogBed { } } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("DogBed").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "DogBed", MatchKind.Exact, NavigateToItemKind.Class);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindMemberInANestedClass()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { class Bar { class DogBed { public void Method() { } } } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("Method").Single();
VerifyNavigateToResultItem(item, "Method", MatchKind.Exact, NavigateToItemKind.Method, "Method()", $"{EditorFeaturesResources.type}Foo.Bar.DogBed");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindGenericClassWithConstraints()
{
using (var workspace = await SetupWorkspaceAsync("using System.Collections; class Foo<T> where T : IEnumerable { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class, displayName: "Foo<T>");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindGenericMethodWithConstraints()
{
using (var workspace = await SetupWorkspaceAsync("using System; class Foo<U> { public void Bar<T>(T item) where T:IComparable<T> {} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("Bar").Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar<T>(T)", $"{EditorFeaturesResources.type}Foo<U>");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialClass()
{
using (var workspace = await SetupWorkspaceAsync("public partial class Foo { int a; } partial class Foo { int b; }"))
{
var expecteditem1 = new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = _aggregator.GetItems("Foo");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindTypesInMetadata()
{
using (var workspace = await SetupWorkspaceAsync("using System; Class Program {FileStyleUriParser f;}"))
{
var items = _aggregator.GetItems("FileStyleUriParser");
Assert.Equal(items.Count(), 0);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindClassInNamespace()
{
using (var workspace = await SetupWorkspaceAsync("namespace Bar { class Foo { } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindStruct()
{
using (var workspace = await SetupWorkspaceAsync("struct Bar { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("B").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Structure);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEnum()
{
using (var workspace = await SetupWorkspaceAsync("enum Colors {Red, Green, Blue}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("Colors").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Colors", MatchKind.Exact, NavigateToItemKind.Enum);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEnumMember()
{
using (var workspace = await SetupWorkspaceAsync("enum Colors {Red, Green, Blue}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("R").Single();
VerifyNavigateToResultItem(item, "Red", MatchKind.Prefix, NavigateToItemKind.EnumItem);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindConstField()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { const int bar = 7;}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupConstant, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("ba").Single();
VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Constant);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindVerbatimIdentifier()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { string @string; }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("string").Single();
VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindIndexer()
{
var program = @"class Foo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }";
using (var workspace = await SetupWorkspaceAsync(program))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("this").Single();
VerifyNavigateToResultItem(item, "this[]", MatchKind.Exact, NavigateToItemKind.Property, displayName: "this[int]", additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEvent()
{
var program = "class Foo { public event EventHandler ChangedEventHandler; }";
using (var workspace = await SetupWorkspaceAsync(program))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEvent, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("CEH").Single();
VerifyNavigateToResultItem(item, "ChangedEventHandler", MatchKind.Regular, NavigateToItemKind.Event, additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindAutoProperty()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { int Bar { get; set; } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("B").Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Property, additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindMethod()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { void DoSomething(); }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("DS").Single();
VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindParameterizedMethod()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { void DoSomething(int a, string b) {} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("DS").Single();
VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething(int, string)", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindConstructor()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { public Foo(){} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method);
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindParameterizedConstructor()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { public Foo(int i){} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method);
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo(int)", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindStaticConstructor()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { static Foo(){} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "static Foo()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialMethods()
{
using (var workspace = await SetupWorkspaceAsync("partial class Foo { partial void Bar(); } partial class Foo { partial void Bar() { Console.Write(\"hello\"); } }"))
{
var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = _aggregator.GetItems("Bar");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialMethodDefinitionOnly()
{
using (var workspace = await SetupWorkspaceAsync("partial class Foo { partial void Bar(); }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("Bar").Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindOverriddenMembers()
{
var program = "class Foo { public virtual string Name { get; set; } } class DogBed : Foo { public override string Name { get { return base.Name; } set {} } }";
using (var workspace = await SetupWorkspaceAsync(program))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = _aggregator.GetItems("Name");
VerifyNavigateToResultItems(expecteditems, items);
var item = items.ElementAt(0);
var itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
var unused = itemDisplay.Glyph;
Assert.Equal("Name", itemDisplay.Name);
Assert.Equal($"{EditorFeaturesResources.type}DogBed", itemDisplay.AdditionalInformation);
_glyphServiceMock.Verify();
item = items.ElementAt(1);
itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
unused = itemDisplay.Glyph;
Assert.Equal("Name", itemDisplay.Name);
Assert.Equal($"{EditorFeaturesResources.type}Foo", itemDisplay.AdditionalInformation);
_glyphServiceMock.Verify();
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindInterface()
{
using (var workspace = await SetupWorkspaceAsync("public interface IFoo { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("IF").Single();
VerifyNavigateToResultItem(item, "IFoo", MatchKind.Prefix, NavigateToItemKind.Interface, displayName: "IFoo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindDelegateInNamespace()
{
using (var workspace = await SetupWorkspaceAsync("namespace Foo { delegate void DoStuff(); }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupDelegate, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("DoStuff").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "DoStuff", MatchKind.Exact, NavigateToItemKind.Delegate, displayName: "DoStuff");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindLambdaExpression()
{
using (var workspace = await SetupWorkspaceAsync("using System; class Foo { Func<int, int> sqr = x => x*x; }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("sqr").Single();
VerifyNavigateToResultItem(item, "sqr", MatchKind.Exact, NavigateToItemKind.Field, "sqr", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task OrderingOfConstructorsAndTypes()
{
using (var workspace = await SetupWorkspaceAsync(@"
class C1
{
C1(int i) {}
}
class C2
{
C2(float f) {}
static C2() {}
}"))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("C1", NavigateToItemKind.Class, "csharp", "C1", null, MatchKind.Prefix, true, null),
new NavigateToItem("C1", NavigateToItemKind.Method, "csharp", "C1", null, MatchKind.Prefix, true, null),
new NavigateToItem("C2", NavigateToItemKind.Class, "csharp", "C2", null, MatchKind.Prefix, true, null),
new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), // this is the static ctor
new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null),
};
var items = _aggregator.GetItems("C").ToList();
items.Sort(CompareNavigateToItems);
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task StartStopSanity()
{
// Verify that multiple calls to start/stop and dispose don't blow up
using (var workspace = await SetupWorkspaceAsync("public class Foo { }"))
{
// Do one set of queries
Assert.Single(_aggregator.GetItems("Foo").Where(x => x.Kind != "Method"));
_provider.StopSearch();
// Do the same query again, make sure nothing was left over
Assert.Single(_aggregator.GetItems("Foo").Where(x => x.Kind != "Method"));
_provider.StopSearch();
// Dispose the provider
_provider.Dispose();
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DescriptionItems()
{
var code = "public\r\nclass\r\nFoo\r\n{ }";
using (var workspace = await SetupWorkspaceAsync(code))
{
var item = _aggregator.GetItems("F").Single(x => x.Kind != "Method");
var itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
var descriptionItems = itemDisplay.DescriptionItems;
Action<string, string> assertDescription = (label, value) =>
{
var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label);
Assert.Equal(value, descriptionItem.Details.Single().Text);
};
assertDescription("File:", workspace.Documents.Single().Name);
assertDescription("Line:", "3"); // one based line number
assertDescription("Project:", "Test");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest1()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem3 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2, expecteditem3 };
var items = _aggregator.GetItems("GK");
Assert.Equal(expecteditems.Count(), items.Count());
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest2()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 };
var items = _aggregator.GetItems("GKW");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest3()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 };
var items = _aggregator.GetItems("K W");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest4()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var items = _aggregator.GetItems("WKG");
Assert.Empty(items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest5()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("G_K_W").Single();
VerifyNavigateToResultItem(item, "get_key_word", MatchKind.Regular, NavigateToItemKind.Field);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest7()
{
////Diff from dev10
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 };
var items = _aggregator.GetItems("K*W");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest8()
{
////Diff from dev10
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var items = _aggregator.GetItems("GTW");
Assert.Empty(items);
}
}
private void VerifyNavigateToResultItems(List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items)
{
expecteditems = expecteditems.OrderBy(i => i.Name).ToList();
items = items.OrderBy(i => i.Name).ToList();
Assert.Equal(expecteditems.Count(), items.Count());
for (int i = 0; i < expecteditems.Count; i++)
{
var expectedItem = expecteditems[i];
var actualItem = items.ElementAt(i);
Assert.Equal(expectedItem.Name, actualItem.Name);
Assert.Equal(expectedItem.MatchKind, actualItem.MatchKind);
Assert.Equal(expectedItem.Language, actualItem.Language);
Assert.Equal(expectedItem.Kind, actualItem.Kind);
Assert.Equal(expectedItem.IsCaseSensitive, actualItem.IsCaseSensitive);
if (!string.IsNullOrEmpty(expectedItem.SecondarySort))
{
Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal);
}
}
}
private void VerifyNavigateToResultItem(NavigateToItem result, string name, MatchKind matchKind, string navigateToItemKind,
string displayName = " ", string additionalInfo = " ")
{
string itemDisplayName;
// Verify symbol information
Assert.Equal(name, result.Name);
Assert.Equal(matchKind, result.MatchKind);
Assert.Equal("csharp", result.Language);
Assert.Equal(navigateToItemKind, result.Kind);
// Verify display
var itemDisplay = result.DisplayFactory.CreateItemDisplay(result);
itemDisplayName = string.IsNullOrWhiteSpace(displayName) ? name : displayName;
Assert.Equal(itemDisplayName, itemDisplay.Name);
if (!string.IsNullOrWhiteSpace(additionalInfo))
{
Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation);
}
// Make sure to fetch the glyph
var unused = itemDisplay.Glyph;
_glyphServiceMock.Verify();
}
private void SetupVerifiableGlyph(StandardGlyphGroup standardGlyphGroup, StandardGlyphItem standardGlyphItem)
{
_glyphServiceMock.Setup(service => service.GetGlyph(standardGlyphGroup, standardGlyphItem))
.Returns(CreateIconBitmapSource())
.Verifiable();
}
private BitmapSource CreateIconBitmapSource()
{
int stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16;
return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride);
}
// For ordering of NavigateToItems, see
// http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx
private static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b)
{
int result = ((int)a.MatchKind) - ((int)b.MatchKind);
if (result != 0)
{
return result;
}
result = a.Name.CompareTo(b.Name);
if (result != 0)
{
return result;
}
result = a.Kind.CompareTo(b.Kind);
if (result != 0)
{
return result;
}
result = a.SecondarySort.CompareTo(b.SecondarySort);
return result;
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace TapeDriveIO
{
/// <summary>
/// Publically holds all Win32 tape drive functions and associated structures
/// </summary>
public class TapeDriveFunctions
{
[StructLayout(LayoutKind.Sequential)]
public class SecurityAttributes
{
public UInt32 size;
public IntPtr securityDescripter;
public UInt32 inheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
public struct FileTime
{
public UInt32 dwLowDateTime;
public UInt32 dwHighDateTime;
}
[StructLayout(LayoutKind.Sequential)]
public class Overlapped
{
public IntPtr Internal;
public IntPtr InternalHigh;
public UInt32 Offset;
public UInt32 OffsetHigh;
public UInt32 hEvent;
}
[DllImport("kernel32.dll")]
public static extern UInt32 CreateFile(
string lpFileName, // file name
UInt32 dwDesiredAccess, // access mode
UInt32 dwShareMode, // share mode
SecurityAttributes lpSecurityAttributes, // SD
UInt32 dwCreationDisposition, // how to create
UInt32 dwFlagsAndAttributes, // file attributes
UInt32 hTemplateFile // handle to template file
);
[DllImport("kernel32.dll")]
public static extern bool BackupRead(
UInt32 hFile, // handle to file or directory
byte[] lpBuffer, // read buffer
UInt32 nNumberOfBytesToRead, // number of bytes to read
out UInt32 lpNumberOfBytesRead, // number of bytes read
bool bAbort, // termination type
bool bProcessSecurity, // process security options
IntPtr lpContext // context information
);
[DllImport("kernel32.dll")]
public static extern bool WriteFile(
UInt32 hFile, // handle to file
byte[] lpBuffer, // data buffer
UInt32 nNumberOfBytesToWrite, // number of bytes to write
out UInt32 lpNumberOfBytesWritten, // number of bytes written
Overlapped lpOverlapped // overlapped buffer
);
[DllImport("kernel32.dll")]
public static extern bool BackupWrite(
UInt32 hFile, // handle to file or directory
byte[] lpBuffer, // write buffer
UInt32 nNumberOfBytesToWrite, // number of bytes to write
out UInt32 lpNumberOfBytesWritten, // number of bytes written
bool bAbort, // termination type
bool bProcessSecurity, // process security
IntPtr lpContext // context information
);
[DllImport("kernel32.dll")]
public static extern bool ReadFile(
UInt32 hFile, // handle to file
byte[] lpBuffer, // data buffer
UInt32 nNumberOfBytesToRead, // number of bytes to read
out UInt32 lpNumberOfBytesRead, // number of bytes read
Overlapped lpOverlapped // overlapped buffer
);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(
UInt32 hObject // handle to object
);
[DllImport("kernel32.dll")]
public static extern UInt32 PrepareTape(
UInt32 hDevice, // handle to device
UInt32 dwOperation, // preparation method
bool bImmediate // return after operation begins
);
[DllImport("kernel32.dll")]
public static extern UInt32 CreateTapePartition(
UInt32 hDevice, // handle to device
UInt32 dwPartitionMethod, // new partition type
UInt32 dwCount, // number of new partitions
UInt32 dwSize // size of new partition
);
[StructLayout(LayoutKind.Sequential)]
public class TapeMediaInformation
{
public long Capacity;
public long Remaining;
public UInt32 BlockSize;
public UInt32 PartitionCount;
public UInt32 WriteProtected;
}
[StructLayout(LayoutKind.Sequential)]
public class SetTapeMediaInformation
{
public UInt32 BlockSize;
}
[StructLayout(LayoutKind.Sequential)]
public class TapeDriveInformation
{
public UInt32 ECC;
public UInt32 Compression;
public UInt32 DataPadding;
public UInt32 ReportSetmarks;
public UInt32 DefaultBlockSize;
public UInt32 MaximumBlockSize;
public UInt32 MinimumBlockSize;
public UInt32 MaximumPartitionCount;
public UInt32 FeaturesLow;
public UInt32 FeaturesHigh;
public UInt32 EOTWarningZoneSize;
}
[StructLayout(LayoutKind.Sequential)]
public class SetTapeDriveInformation
{
public UInt32 ECC;
public UInt32 Compression;
public UInt32 DataPadding;
public UInt32 ReportSetmarks;
public UInt32 EOTWarningZoneSize;
}
[DllImport("kernel32.dll")]
public static extern UInt32 GetTapePosition(
UInt32 hDevice, // handle to device
UInt32 dwPositionType, // address type
out UInt32 lpdwPartition, // current tape partition
out UInt32 lpdwOffsetLow, // low-order bits of position
out UInt32 lpdwOffsetHigh // high-order bits of position
);
[DllImport("kernel32.dll")]
public static extern UInt32 SetTapePosition(
UInt32 hDevice, // handle to device
UInt32 dwPositionMethod, // positioning type
UInt32 dwPartition, // new tape partition
UInt32 dwOffsetLow, // low-order bits of position
UInt32 dwOffsetHigh, // high-order bits of position
bool bImmediate // return after operation begins
);
[DllImport("kernel32.dll")]
public static extern UInt32 GetTapeStatus(
UInt32 hDevice // handle to device
);
[DllImport("kernel32.dll")]
public static extern UInt32 GetTapeParameters(
UInt32 hDevice, // handle to device
UInt32 dwOperation, // information type
out UInt32 lpdwSize, // information
TapeMediaInformation lpTapeInformation // tape media or drive information
);
[DllImport("kernel32.dll")]
public static extern UInt32 GetTapeParameters(
UInt32 hDevice, // handle to device
UInt32 dwOperation, // information type
out UInt32 lpdwSize, // information
TapeDriveInformation lpTapeInformation // tape media or drive information
);
[DllImport("kernel32.dll")]
public static extern UInt32 SetTapeParameters(
UInt32 hDevice, // handle to device
UInt32 dwOperation, // information type
SetTapeDriveInformation lpTapeInformation // information buffer
);
[DllImport("kernel32.dll")]
public static extern UInt32 SetTapeParameters(
UInt32 hDevice, // handle to device
UInt32 dwOperation, // information type
SetTapeMediaInformation lpTapeInformation // information buffer
);
[DllImport("kernel32.dll")]
public static extern bool FlushFileBuffers(
UInt32 hFile // handle to file
);
[DllImport("kernel32.dll")]
public static extern UInt32 EraseTape(
UInt32 hDevice, // handle to device
UInt32 dwEraseType, // type of erasure to perform
bool bImmediate // return after erase operation begins
);
[DllImport("kernel32.dll")]
public static extern UInt32 WriteTapemark(
UInt32 hDevice, // handle to device
UInt32 dwTapemarkType, // tapemark type
UInt32 dwTapemarkCount, // number of tapemarks to write
bool bImmediate // return after write begins
);
public static void CheckGeneralError(UInt32 error)
{
switch (error)
{
case 1106: // ERROR_INVALID_BLOCK_LENGTH
throw(new TapeDriveException("Invalid block length"));
case 1107: // ERROR_DEVICE_NOT_PARTITIONED
throw(new TapeDriveException("Device not partitioned"));
case 1109: // ERROR_MEDIA_CHANGED
throw(new MediaChangedException());
case 1111: // ERROR_BUS_RESET
throw(new TapeDriveException("I/O has been reset"));
case 1112: // ERROR_NO_MEDIA_IN_DRIVE
throw(new NoMediaException());
case 50: // ERROR_NOT_SUPPORTED
throw(new NotSupportedException());
}
}
/// <summary>
/// Gets the tape drive parameters
/// </summary>
/// <returns>Class containing drive parameters</returns>
public static TapeDriveInformation GetTapeDriveParameters(TapeDrive tapeDrive)
{
UInt32 size;
TapeDriveInformation tapeMediaInfo = new TapeDriveInformation();
GetTapeParameters(tapeDrive.Handle, 1, out size, tapeMediaInfo);
return tapeMediaInfo;
}
/// <summary>
/// Gets the tape media parameters
/// </summary>
/// <returns>Class containing media parameters</returns>
public static TapeMediaInformation GetTapeMediaParameters(TapeDrive tapeDrive)
{
UInt32 size;
TapeMediaInformation tapeDriveInfo = new TapeMediaInformation();
GetTapeParameters(tapeDrive.Handle, 0, out size, tapeDriveInfo);
return tapeDriveInfo;
}
public static void SetTapeDriveParameters(TapeDrive tapeDrive, SetTapeDriveInformation info)
{
SetTapeParameters(tapeDrive.Handle, 1, info);
}
public static void SetTapeMediaParameters(TapeDrive tapeDrive, SetTapeMediaInformation info)
{
SetTapeParameters(tapeDrive.Handle, 0, info);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Screens;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Textures;
using osu.Framework.Utils;
using osu.Framework.Timing;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets;
using osu.Game.Screens.Backgrounds;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Menu
{
public class IntroTriangles : IntroScreen
{
protected override string BeatmapHash => "a1556d0801b3a6b175dda32ef546f0ec812b400499f575c44fccbe9c67f9b1e5";
protected override string BeatmapFile => "triangles.osz";
protected override BackgroundScreen CreateBackground() => background = new BackgroundScreenDefault(false)
{
Alpha = 0,
};
[Resolved]
private AudioManager audio { get; set; }
private BackgroundScreenDefault background;
private Sample welcome;
private DecoupleableInterpolatingFramedClock decoupledClock;
private TrianglesIntroSequence intro;
public IntroTriangles([CanBeNull] Func<MainMenu> createNextScreen = null)
: base(createNextScreen)
{
}
[BackgroundDependencyLoader]
private void load()
{
if (MenuVoice.Value)
welcome = audio.Samples.Get(@"Intro/welcome");
}
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
if (!resuming)
{
PrepareMenuLoad();
decoupledClock = new DecoupleableInterpolatingFramedClock
{
IsCoupled = false
};
if (UsingThemedIntro)
decoupledClock.ChangeSource(Track);
LoadComponentAsync(intro = new TrianglesIntroSequence(logo, background)
{
RelativeSizeAxes = Axes.Both,
Clock = decoupledClock,
LoadMenu = LoadMenu
}, t =>
{
AddInternal(t);
if (!UsingThemedIntro)
welcome?.Play();
StartTrack();
});
}
}
public override void OnSuspending(IScreen next)
{
base.OnSuspending(next);
// important as there is a clock attached to a track which will likely be disposed before returning to this screen.
intro.Expire();
}
public override void OnResuming(IScreen last)
{
base.OnResuming(last);
background.FadeOut(100);
}
protected override void StartTrack()
{
decoupledClock.Start();
}
private class TrianglesIntroSequence : CompositeDrawable
{
private readonly OsuLogo logo;
private readonly BackgroundScreenDefault background;
private OsuSpriteText welcomeText;
private RulesetFlow rulesets;
private Container rulesetsScale;
private Container logoContainerSecondary;
private LazerLogo lazerLogo;
private GlitchingTriangles triangles;
public Action LoadMenu;
public TrianglesIntroSequence(OsuLogo logo, BackgroundScreenDefault background)
{
this.logo = logo;
this.background = background;
}
[Resolved]
private OsuGameBase game { get; set; }
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
InternalChildren = new Drawable[]
{
triangles = new GlitchingTriangles
{
Alpha = 0,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(0.4f, 0.16f)
},
welcomeText = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Padding = new MarginPadding { Bottom = 10 },
Font = OsuFont.GetFont(weight: FontWeight.Light, size: 42),
Alpha = 1,
Spacing = new Vector2(5),
},
rulesetsScale = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
rulesets = new RulesetFlow()
}
},
logoContainerSecondary = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Child = lazerLogo = new LazerLogo
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
}
},
};
}
private const double text_1 = 200;
private const double text_2 = 400;
private const double text_3 = 700;
private const double text_4 = 900;
private const double text_glitch = 1060;
private const double rulesets_1 = 1450;
private const double rulesets_2 = 1650;
private const double rulesets_3 = 1850;
private const double logo_scale_duration = 920;
private const double logo_1 = 2080;
private const double logo_2 = logo_1 + logo_scale_duration;
protected override void LoadComplete()
{
base.LoadComplete();
const float scale_start = 1.2f;
const float scale_adjust = 0.8f;
rulesets.Hide();
lazerLogo.Hide();
background.ApplyToBackground(b => b.Hide());
using (BeginAbsoluteSequence(0))
{
using (BeginDelayedSequence(text_1))
welcomeText.FadeIn().OnComplete(t => t.Text = "wel");
using (BeginDelayedSequence(text_2))
welcomeText.FadeIn().OnComplete(t => t.Text = "welcome");
using (BeginDelayedSequence(text_3))
welcomeText.FadeIn().OnComplete(t => t.Text = "welcome to");
using (BeginDelayedSequence(text_4))
{
welcomeText.FadeIn().OnComplete(t => t.Text = "welcome to osu!");
welcomeText.TransformTo(nameof(welcomeText.Spacing), new Vector2(50, 0), 5000);
}
using (BeginDelayedSequence(text_glitch))
triangles.FadeIn();
using (BeginDelayedSequence(rulesets_1))
{
rulesetsScale.ScaleTo(0.8f, 1000);
rulesets.FadeIn().ScaleTo(1).TransformSpacingTo(new Vector2(200, 0));
welcomeText.FadeOut();
triangles.FadeOut();
}
using (BeginDelayedSequence(rulesets_2))
{
rulesets.ScaleTo(2).TransformSpacingTo(new Vector2(30, 0));
}
using (BeginDelayedSequence(rulesets_3))
{
rulesets.ScaleTo(4).TransformSpacingTo(new Vector2(10, 0));
rulesetsScale.ScaleTo(1.3f, 1000);
}
using (BeginDelayedSequence(logo_1))
{
rulesets.FadeOut();
// matching flyte curve y = 0.25x^2 + (max(0, x - 0.7) / 0.3) ^ 5
lazerLogo.FadeIn().ScaleTo(scale_start).Then().Delay(logo_scale_duration * 0.7f).ScaleTo(scale_start - scale_adjust, logo_scale_duration * 0.3f, Easing.InQuint);
lazerLogo.TransformTo(nameof(LazerLogo.Progress), 1f, logo_scale_duration);
logoContainerSecondary.ScaleTo(scale_start).Then().ScaleTo(scale_start - scale_adjust * 0.25f, logo_scale_duration, Easing.InQuad);
}
using (BeginDelayedSequence(logo_2))
{
lazerLogo.FadeOut().OnComplete(_ =>
{
logoContainerSecondary.Remove(lazerLogo);
lazerLogo.Dispose(); // explicit disposal as we are pushing a new screen and the expire may not get run.
logo.FadeIn();
background.ApplyToBackground(b => b.Show());
game.Add(new GameWideFlash());
LoadMenu();
});
}
}
}
private class GameWideFlash : Box
{
private const double flash_length = 1000;
public GameWideFlash()
{
Colour = Color4.White;
RelativeSizeAxes = Axes.Both;
Blending = BlendingParameters.Additive;
}
protected override void LoadComplete()
{
base.LoadComplete();
this.FadeOutFromOne(flash_length, Easing.Out);
}
}
private class LazerLogo : CompositeDrawable
{
private LogoAnimation highlight, background;
public float Progress
{
get => background.AnimationProgress;
set
{
background.AnimationProgress = value;
highlight.AnimationProgress = value;
}
}
public LazerLogo()
{
Size = new Vector2(960);
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
InternalChildren = new Drawable[]
{
highlight = new LogoAnimation
{
RelativeSizeAxes = Axes.Both,
Texture = textures.Get(@"Intro/Triangles/logo-highlight"),
Colour = Color4.White,
},
background = new LogoAnimation
{
RelativeSizeAxes = Axes.Both,
Texture = textures.Get(@"Intro/Triangles/logo-background"),
Colour = OsuColour.Gray(0.6f),
},
};
}
}
private class RulesetFlow : FillFlowContainer
{
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
var modes = new List<Drawable>();
foreach (var ruleset in rulesets.AvailableRulesets)
{
var icon = new ConstrainedIconContainer
{
Icon = ruleset.CreateInstance().CreateIcon(),
Size = new Vector2(30),
};
modes.Add(icon);
}
AutoSizeAxes = Axes.Both;
Children = modes;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
}
private class GlitchingTriangles : CompositeDrawable
{
public GlitchingTriangles()
{
RelativeSizeAxes = Axes.Both;
}
private double? lastGenTime;
private const double time_between_triangles = 22;
protected override void Update()
{
base.Update();
if (lastGenTime == null || Time.Current - lastGenTime > time_between_triangles)
{
lastGenTime = (lastGenTime ?? Time.Current) + time_between_triangles;
Drawable triangle = new OutlineTriangle(RNG.NextBool(), (RNG.NextSingle() + 0.2f) * 80)
{
RelativePositionAxes = Axes.Both,
Position = new Vector2(RNG.NextSingle(), RNG.NextSingle()),
};
AddInternal(triangle);
triangle.FadeOutFromOne(120);
}
}
/// <summary>
/// Represents a sprite that is drawn in a triangle shape, instead of a rectangle shape.
/// </summary>
public class OutlineTriangle : BufferedContainer
{
public OutlineTriangle(bool outlineOnly, float size)
{
Size = new Vector2(size);
InternalChildren = new Drawable[]
{
new Triangle { RelativeSizeAxes = Axes.Both },
};
if (outlineOnly)
{
AddInternal(new Triangle
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = Color4.Black,
Size = new Vector2(size - 5),
Blending = BlendingParameters.None,
});
}
Blending = BlendingParameters.Additive;
CacheDrawnFrameBuffer = true;
}
}
}
}
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections.Generic;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Queries;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
namespace Lucene.Net.Tests.Queries
{
public class TermFilterTest : LuceneTestCase
{
[Test]
public void TestCachability()
{
TermFilter a = TermFilter(@"field1", @"a");
var cachedFilters = new HashSet<Filter>();
cachedFilters.Add(a);
assertTrue(@"Must be cached", cachedFilters.Contains(TermFilter(@"field1", @"a")));
assertFalse(@"Must not be cached", cachedFilters.Contains(TermFilter(@"field1", @"b")));
assertFalse(@"Must not be cached", cachedFilters.Contains(TermFilter(@"field2", @"a")));
}
[Test]
public void TestMissingTermAndField()
{
string fieldName = @"field1";
Directory rd = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(Random(), rd, Similarity, TimeZone);
Document doc = new Document();
doc.Add(NewStringField(fieldName, @"value1", Field.Store.NO));
w.AddDocument(doc);
IndexReader reader = SlowCompositeReaderWrapper.Wrap(w.Reader);
assertTrue(reader.Context is AtomicReaderContext);
var context = (AtomicReaderContext)reader.Context;
w.Dispose();
DocIdSet idSet = TermFilter(fieldName, @"value1").GetDocIdSet(context, context.AtomicReader.LiveDocs);
assertNotNull(@"must not be null", idSet);
DocIdSetIterator iter = idSet.GetIterator();
assertEquals(iter.NextDoc(), 0);
assertEquals(iter.NextDoc(), DocIdSetIterator.NO_MORE_DOCS);
idSet = TermFilter(fieldName, @"value2").GetDocIdSet(context, context.AtomicReader.LiveDocs);
assertNull(@"must be null", idSet);
idSet = TermFilter(@"field2", @"value1").GetDocIdSet(context, context.AtomicReader.LiveDocs);
assertNull(@"must be null", idSet);
reader.Dispose();
rd.Dispose();
}
[Test]
public void TestRandom()
{
Directory dir = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);
int num = AtLeast(100);
var terms = new List<Term>();
for (int i = 0; i < num; i++)
{
string field = @"field" + i;
string str = TestUtil.RandomRealisticUnicodeString(Random());
terms.Add(new Term(field, str));
Document doc = new Document();
doc.Add(NewStringField(field, str, Field.Store.NO));
w.AddDocument(doc);
}
IndexReader reader = w.Reader;
w.Dispose();
IndexSearcher searcher = NewSearcher(reader);
int numQueries = AtLeast(10);
for (int i = 0; i < numQueries; i++)
{
Term term = terms[Random().nextInt(num)];
TopDocs queryResult = searcher.Search(new TermQuery(term), reader.MaxDoc);
MatchAllDocsQuery matchAll = new MatchAllDocsQuery();
TermFilter filter = TermFilter(term);
TopDocs filterResult = searcher.Search(matchAll, filter, reader.MaxDoc);
assertEquals(filterResult.TotalHits, queryResult.TotalHits);
ScoreDoc[] scoreDocs = filterResult.ScoreDocs;
for (int j = 0; j < scoreDocs.Length; j++)
{
assertEquals(scoreDocs[j].Doc, queryResult.ScoreDocs[j].Doc);
}
}
reader.Dispose();
dir.Dispose();
}
[Test]
public void TestHashCodeAndEquals()
{
int num = AtLeast(100);
for (int i = 0; i < num; i++)
{
string field1 = @"field" + i;
string field2 = @"field" + i + num;
string value1 = TestUtil.RandomRealisticUnicodeString(Random());
string value2 = value1 + @"x";
TermFilter filter1 = TermFilter(field1, value1);
TermFilter filter2 = TermFilter(field1, value2);
TermFilter filter3 = TermFilter(field2, value1);
TermFilter filter4 = TermFilter(field2, value2);
var filters = new TermFilter[]
{
filter1, filter2, filter3, filter4
};
for (int j = 0; j < filters.Length; j++)
{
TermFilter termFilter = filters[j];
for (int k = 0; k < filters.Length; k++)
{
TermFilter otherTermFilter = filters[k];
if (j == k)
{
assertEquals(termFilter, otherTermFilter);
assertEquals(termFilter.GetHashCode(), otherTermFilter.GetHashCode());
assertTrue(termFilter.Equals(otherTermFilter));
}
else
{
assertFalse(termFilter.Equals(otherTermFilter));
}
}
}
TermFilter filter5 = TermFilter(field2, value2);
assertEquals(filter5, filter4);
assertEquals(filter5.GetHashCode(), filter4.GetHashCode());
assertTrue(filter5.Equals(filter4));
assertEquals(filter5, filter4);
assertTrue(filter5.Equals(filter4));
}
}
[Test]
public void TestNoTerms()
{
try
{
new TermFilter(null);
Fail(@"must fail - no term!");
}
#pragma warning disable 168
catch (ArgumentException e)
#pragma warning restore 168
{
}
try
{
new TermFilter(new Term(null));
Fail(@"must fail - no field!");
}
#pragma warning disable 168
catch (ArgumentException e)
#pragma warning restore 168
{
}
}
[Test]
public void TestToString()
{
var termsFilter = new TermFilter(new Term("field1", "a"));
assertEquals(@"field1:a", termsFilter.ToString());
}
private TermFilter TermFilter(string field, string value)
{
return TermFilter(new Term(field, value));
}
private TermFilter TermFilter(Term term)
{
return new TermFilter(term);
}
}
}
| |
using NUnit.Framework;
using Python.Runtime;
using Python.Runtime.Codecs;
using System;
using System.Linq;
using System.Reflection;
namespace Python.EmbeddingTest
{
public class TestOperator
{
[OneTimeSetUp]
public void SetUp()
{
PythonEngine.Initialize();
}
[OneTimeTearDown]
public void Dispose()
{
PythonEngine.Shutdown();
}
public class OperableObject
{
public int Num { get; set; }
public override int GetHashCode()
{
return unchecked(159832395 + Num.GetHashCode());
}
public override bool Equals(object obj)
{
return obj is OperableObject @object &&
Num == @object.Num;
}
public OperableObject(int num)
{
Num = num;
}
public static OperableObject operator ~(OperableObject a)
{
return new OperableObject(~a.Num);
}
public static OperableObject operator +(OperableObject a)
{
return new OperableObject(+a.Num);
}
public static OperableObject operator -(OperableObject a)
{
return new OperableObject(-a.Num);
}
public static OperableObject operator +(int a, OperableObject b)
{
return new OperableObject(a + b.Num);
}
public static OperableObject operator +(OperableObject a, OperableObject b)
{
return new OperableObject(a.Num + b.Num);
}
public static OperableObject operator +(OperableObject a, int b)
{
return new OperableObject(a.Num + b);
}
public static OperableObject operator -(int a, OperableObject b)
{
return new OperableObject(a - b.Num);
}
public static OperableObject operator -(OperableObject a, OperableObject b)
{
return new OperableObject(a.Num - b.Num);
}
public static OperableObject operator -(OperableObject a, int b)
{
return new OperableObject(a.Num - b);
}
public static OperableObject operator *(int a, OperableObject b)
{
return new OperableObject(a * b.Num);
}
public static OperableObject operator *(OperableObject a, OperableObject b)
{
return new OperableObject(a.Num * b.Num);
}
public static OperableObject operator *(OperableObject a, int b)
{
return new OperableObject(a.Num * b);
}
public static OperableObject operator /(int a, OperableObject b)
{
return new OperableObject(a / b.Num);
}
public static OperableObject operator /(OperableObject a, OperableObject b)
{
return new OperableObject(a.Num / b.Num);
}
public static OperableObject operator /(OperableObject a, int b)
{
return new OperableObject(a.Num / b);
}
public static OperableObject operator %(int a, OperableObject b)
{
return new OperableObject(a % b.Num);
}
public static OperableObject operator %(OperableObject a, OperableObject b)
{
return new OperableObject(a.Num % b.Num);
}
public static OperableObject operator %(OperableObject a, int b)
{
return new OperableObject(a.Num % b);
}
public static OperableObject operator &(int a, OperableObject b)
{
return new OperableObject(a & b.Num);
}
public static OperableObject operator &(OperableObject a, OperableObject b)
{
return new OperableObject(a.Num & b.Num);
}
public static OperableObject operator &(OperableObject a, int b)
{
return new OperableObject(a.Num & b);
}
public static OperableObject operator |(int a, OperableObject b)
{
return new OperableObject(a | b.Num);
}
public static OperableObject operator |(OperableObject a, OperableObject b)
{
return new OperableObject(a.Num | b.Num);
}
public static OperableObject operator |(OperableObject a, int b)
{
return new OperableObject(a.Num | b);
}
public static OperableObject operator ^(int a, OperableObject b)
{
return new OperableObject(a ^ b.Num);
}
public static OperableObject operator ^(OperableObject a, OperableObject b)
{
return new OperableObject(a.Num ^ b.Num);
}
public static OperableObject operator ^(OperableObject a, int b)
{
return new OperableObject(a.Num ^ b);
}
public static bool operator ==(int a, OperableObject b)
{
return (a == b.Num);
}
public static bool operator ==(OperableObject a, OperableObject b)
{
return (a.Num == b.Num);
}
public static bool operator ==(OperableObject a, int b)
{
return (a.Num == b);
}
public static bool operator !=(int a, OperableObject b)
{
return (a != b.Num);
}
public static bool operator !=(OperableObject a, OperableObject b)
{
return (a.Num != b.Num);
}
public static bool operator !=(OperableObject a, int b)
{
return (a.Num != b);
}
public static bool operator <=(int a, OperableObject b)
{
return (a <= b.Num);
}
public static bool operator <=(OperableObject a, OperableObject b)
{
return (a.Num <= b.Num);
}
public static bool operator <=(OperableObject a, int b)
{
return (a.Num <= b);
}
public static bool operator >=(int a, OperableObject b)
{
return (a >= b.Num);
}
public static bool operator >=(OperableObject a, OperableObject b)
{
return (a.Num >= b.Num);
}
public static bool operator >=(OperableObject a, int b)
{
return (a.Num >= b);
}
public static bool operator >=(OperableObject a, (int, int) b)
{
using (Py.GIL())
{
int bNum = b.Item1;
return a.Num >= bNum;
}
}
public static bool operator <=(OperableObject a, (int, int) b)
{
using (Py.GIL())
{
int bNum = b.Item1;
return a.Num <= bNum;
}
}
public static bool operator <(int a, OperableObject b)
{
return (a < b.Num);
}
public static bool operator <(OperableObject a, OperableObject b)
{
return (a.Num < b.Num);
}
public static bool operator <(OperableObject a, int b)
{
return (a.Num < b);
}
public static bool operator >(int a, OperableObject b)
{
return (a > b.Num);
}
public static bool operator >(OperableObject a, OperableObject b)
{
return (a.Num > b.Num);
}
public static bool operator >(OperableObject a, int b)
{
return (a.Num > b);
}
public static OperableObject operator <<(OperableObject a, int offset)
{
return new OperableObject(a.Num << offset);
}
public static OperableObject operator >>(OperableObject a, int offset)
{
return new OperableObject(a.Num >> offset);
}
}
[Test]
public void SymmetricalOperatorOverloads()
{
string name = string.Format("{0}.{1}",
typeof(OperableObject).DeclaringType.Name,
typeof(OperableObject).Name);
string module = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
PythonEngine.Exec($@"
from {module} import *
cls = {name}
a = cls(-2)
b = cls(10)
c = ~a
assert c.Num == ~a.Num
c = +a
assert c.Num == +a.Num
a = cls(2)
c = -a
assert c.Num == -a.Num
c = a + b
assert c.Num == a.Num + b.Num
c = a - b
assert c.Num == a.Num - b.Num
c = a * b
assert c.Num == a.Num * b.Num
c = a / b
assert c.Num == a.Num // b.Num
c = a % b
assert c.Num == a.Num % b.Num
c = a & b
assert c.Num == a.Num & b.Num
c = a | b
assert c.Num == a.Num | b.Num
c = a ^ b
assert c.Num == a.Num ^ b.Num
c = a == b
assert c == (a.Num == b.Num)
c = a != b
assert c == (a.Num != b.Num)
c = a <= b
assert c == (a.Num <= b.Num)
c = a >= b
assert c == (a.Num >= b.Num)
c = a < b
assert c == (a.Num < b.Num)
c = a > b
assert c == (a.Num > b.Num)
");
}
[Test]
public void EnumOperator()
{
PythonEngine.Exec($@"
from System.IO import FileAccess
c = FileAccess.Read | FileAccess.Write");
}
[Test]
public void OperatorOverloadMissingArgument()
{
string name = string.Format("{0}.{1}",
typeof(OperableObject).DeclaringType.Name,
typeof(OperableObject).Name);
string module = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
Assert.Throws<PythonException>(() =>
PythonEngine.Exec($@"
from {module} import *
cls = {name}
a = cls(2)
b = cls(10)
a.op_Addition()
"));
}
[Test]
public void ForwardOperatorOverloads()
{
string name = string.Format("{0}.{1}",
typeof(OperableObject).DeclaringType.Name,
typeof(OperableObject).Name);
string module = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
PythonEngine.Exec($@"
from {module} import *
cls = {name}
a = cls(2)
b = 10
c = a + b
assert c.Num == a.Num + b
c = a - b
assert c.Num == a.Num - b
c = a * b
assert c.Num == a.Num * b
c = a / b
assert c.Num == a.Num // b
c = a % b
assert c.Num == a.Num % b
c = a & b
assert c.Num == a.Num & b
c = a | b
assert c.Num == a.Num | b
c = a ^ b
assert c.Num == a.Num ^ b
c = a == b
assert c == (a.Num == b)
c = a != b
assert c == (a.Num != b)
c = a <= b
assert c == (a.Num <= b)
c = a >= b
assert c == (a.Num >= b)
c = a < b
assert c == (a.Num < b)
c = a > b
assert c == (a.Num > b)
");
}
[Test]
public void TupleComparisonOperatorOverloads()
{
TupleCodec<ValueTuple>.Register();
string name = string.Format("{0}.{1}",
typeof(OperableObject).DeclaringType.Name,
typeof(OperableObject).Name);
string module = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
PythonEngine.Exec($@"
from {module} import *
cls = {name}
a = cls(2)
b = (1, 2)
c = a >= b
assert c == (a.Num >= b[0])
c = a <= b
assert c == (a.Num <= b[0])
c = b >= a
assert c == (b[0] >= a.Num)
c = b <= a
assert c == (b[0] <= a.Num)
");
}
[Test]
public void ReverseOperatorOverloads()
{
string name = string.Format("{0}.{1}",
typeof(OperableObject).DeclaringType.Name,
typeof(OperableObject).Name);
string module = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
PythonEngine.Exec($@"
from {module} import *
cls = {name}
a = 2
b = cls(10)
c = a + b
assert c.Num == a + b.Num
c = a - b
assert c.Num == a - b.Num
c = a * b
assert c.Num == a * b.Num
c = a / b
assert c.Num == a // b.Num
c = a % b
assert c.Num == a % b.Num
c = a & b
assert c.Num == a & b.Num
c = a | b
assert c.Num == a | b.Num
c = a ^ b
assert c.Num == a ^ b.Num
c = a == b
assert c == (a == b.Num)
c = a != b
assert c == (a != b.Num)
c = a <= b
assert c == (a <= b.Num)
c = a >= b
assert c == (a >= b.Num)
c = a < b
assert c == (a < b.Num)
c = a > b
assert c == (a > b.Num)
");
}
[Test]
public void ShiftOperatorOverloads()
{
string name = string.Format("{0}.{1}",
typeof(OperableObject).DeclaringType.Name,
typeof(OperableObject).Name);
string module = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
PythonEngine.Exec($@"
from {module} import *
cls = {name}
a = cls(2)
b = cls(10)
c = a << b.Num
assert c.Num == a.Num << b.Num
c = a >> b.Num
assert c.Num == a.Num >> b.Num
");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Microsoft.Research.AbstractDomains.Expressions;
using Microsoft.Research.DataStructures;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Research.CodeAnalysis;
namespace Microsoft.Research.AbstractDomains.Numerical
{
/// <summary>
/// The abstract domain to keep track of relations in the form of "x \leq y".
/// It does not (always) close, so it is less precise than octagons
/// </summary>
[ContractVerification(true)]
public class WeakUpperBoundsEqual<Variable, Expression> :
FunctionalAbstractDomain<WeakUpperBoundsEqual<Variable, Expression>, Variable, SetOfConstraints<Variable>>,
INumericalAbstractDomain<Variable, Expression>
{
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(constraintsForAssignment != null);
Contract.Invariant(this.ExpressionManager != null);
}
#region Private state
readonly protected ExpressionManagerWithEncoder<Variable, Expression> ExpressionManager;
private int closureSteps;
[ThreadStatic]
private static int defaultClosureSteps;
public static int DefaultClosureSteps
{
get { return defaultClosureSteps; }
set { defaultClosureSteps = value; }
}
readonly private List<IConstraintsForAssignment<Variable, Expression, INumericalAbstractDomainQuery<Variable, Expression>>> constraintsForAssignment;
#endregion
#region Constructor
public WeakUpperBoundsEqual(ExpressionManagerWithEncoder<Variable, Expression> expManager)
{
Contract.Requires(expManager != null);
this.ExpressionManager = expManager;
constraintsForAssignment = new List<IConstraintsForAssignment<Variable, Expression, INumericalAbstractDomainQuery<Variable, Expression>>>()
{
new LessEqualThanConstraints<Variable, Expression>(this.ExpressionManager),
new LessThanConstraints<Variable, Expression>(this.ExpressionManager),
new GreaterEqualThanZeroConstraints<Variable, Expression>(this.ExpressionManager)
};
}
private WeakUpperBoundsEqual(WeakUpperBoundsEqual<Variable, Expression> other)
: base(other)
{
Contract.Requires(other != null);
// F: We do not assume the object invariant for now
Contract.Assume(other.ExpressionManager != null);
Contract.Assume(other.constraintsForAssignment != null);
this.ExpressionManager = other.ExpressionManager;
constraintsForAssignment = other.constraintsForAssignment;
}
#endregion
public override object Clone()
{
return this.DuplicateMe();
}
public WeakUpperBoundsEqual<Variable, Expression> DuplicateMe()
{
return new WeakUpperBoundsEqual<Variable, Expression>(this);
}
#region IPureExpressionAssignmentsWithForward<Expression> Members
/// <summary>
/// Do the assignment, improving the precision using the oracle domain
/// </summary>
public void Assign(Expression x, Expression exp, INumericalAbstractDomainQuery<Variable, Expression> oracleDomain)
{
var LEQConstraints = new Set<Expression>();
// Discover new constraints
foreach (var constraintsFetcher in constraintsForAssignment)
{
Contract.Assume(constraintsFetcher != null);
LEQConstraints.AddRange(constraintsFetcher.InferConstraints(x, exp, oracleDomain));
}
// Assume them
foreach (var newConstraint in LEQConstraints)
{
this.TestTrue(newConstraint);
}
}
public void Assign(Expression x, Expression exp)
{
Contract.Assume(x != null);
Contract.Assume(exp != null);
Assign(x, exp, TopNumericalDomain<Variable, Expression>.Singleton);
}
#endregion
#region Easy ones
public DisInterval BoundsFor(Expression exp)
{
Expression left, right;
switch (this.ExpressionManager.Decoder.OperatorFor(exp))
{
case ExpressionOperator.Subtraction:
left = this.ExpressionManager.Decoder.LeftExpressionFor(exp);
right = this.ExpressionManager.Decoder.RightExpressionFor(exp);
var isPositive = this.CheckIfLessEqualThan(right, left); // right <= left
if (isPositive.IsNormal())
{
return isPositive.BoxedElement ? DisInterval.Positive : DisInterval.Negative;
}
else
{
return DisInterval.UnknownInterval;
}
default:
return DisInterval.UnknownInterval;
}
}
public DisInterval BoundsFor(Variable v)
{
return this.BoundsFor(this.ExpressionManager.Encoder.VariableFor(v));
}
public FlatAbstractDomain<bool> CheckIfHolds(Expression exp)
{
return this.CheckIfHolds(exp, TopNumericalDomain<Variable, Expression>.Singleton);
}
public FlatAbstractDomain<bool> CheckIfHolds(Expression exp, INumericalAbstractDomain<Variable, Expression> oracleDomain)
{
var operatorForExp = this.ExpressionManager.Decoder.OperatorFor(exp);
if (operatorForExp.IsBinary() && operatorForExp.IsRelationalOperator())
{
Expression left, right;
left = this.ExpressionManager.Decoder.LeftExpressionFor(exp);
right = this.ExpressionManager.Decoder.RightExpressionFor(exp);
switch (operatorForExp)
{
case ExpressionOperator.Equal:
case ExpressionOperator.Equal_Obj:
ExpressionOperator op;
Expression e11, e12;
if (this.ExpressionManager.Decoder.Match_E1relopE2eq0(left, right, out op, out e11, out e12))
{
return ChechIfHoldsNegative(op, e11, e12);
}
break;
case ExpressionOperator.GreaterThan:
case ExpressionOperator.GreaterThan_Un:
return CheckIfLessThan(right, left);
case ExpressionOperator.LessThan:
case ExpressionOperator.LessThan_Un:
return CheckIfLessThan(left, right);
case ExpressionOperator.LessEqualThan:
case ExpressionOperator.LessEqualThan_Un:
return CheckIfLessEqualThan(left, right);
case ExpressionOperator.GreaterEqualThan:
case ExpressionOperator.GreaterEqualThan_Un:
return CheckIfLessEqualThan(right, left);
default:
return CheckOutcome.Top;
}
}
return CheckOutcome.Top;
}
private FlatAbstractDomain<bool> ChechIfHoldsNegative(ExpressionOperator op, Expression a, Expression b)
{
switch (op)
{
case ExpressionOperator.GreaterEqualThan:
case ExpressionOperator.GreaterEqualThan_Un:
// !(a >= b) == a < b
return CheckIfLessThan(a, b);
case ExpressionOperator.GreaterThan:
case ExpressionOperator.GreaterThan_Un:
// !(a > b) == a <= b
return CheckIfLessEqualThan(a, b);
case ExpressionOperator.LessEqualThan:
case ExpressionOperator.LessEqualThan_Un:
// !(a <= b) == a > b =+ b < a
return CheckIfLessThan(b, a);
case ExpressionOperator.LessThan:
case ExpressionOperator.LessThan_Un:
// !(a < b) =+ a >= b == b <= a
return CheckIfLessEqualThan(b, a);
default:
return CheckOutcome.Top;
}
}
/// <summary>
/// Add or materialize the map entry and add the value
/// </summary>
[ContractVerification(false)]
static internal void AddUpperBound(Variable key, Variable upperBound, Dictionary<Variable, Set<Variable>> map)
{
Contract.Requires(map != null);
Set<Variable> bounds;
if (!map.TryGetValue(key, out bounds))
{
bounds = new Set<Variable>();
map[key] = bounds;
}
Contract.Assume(bounds != null);
bounds.Add(upperBound);
}
public FlatAbstractDomain<bool> CheckIfNonZero(Expression exp)
{
return CheckOutcome.Top;
}
public FlatAbstractDomain<bool> CheckIfGreaterEqualThanZero(Expression exp)
{
Polynomial<Variable, Expression> pol;
Variable x, y;
Rational k;
if (/*this.ExpressionManager.Encoder != null && */
Polynomial<Variable, Expression>.TryToPolynomialForm(exp, this.ExpressionManager.Decoder, out pol)
&& pol.TryMatch_XMinusYPlusK(out x, out y, out k))
{
var xExp = this.ExpressionManager.Encoder.VariableFor(x);
var yExp = this.ExpressionManager.Encoder.VariableFor(y);
var lt = this.CheckIfLessEqualThan(yExp, xExp);
if (lt.IsNormal() && lt.BoxedElement == true && k >= -1)
{ // if we have to check x - y + k >= 0, and we know that k >= -1 and x - y > 0, then this is true
return lt; // that is true
}
}
return CheckOutcome.Top;
}
public FlatAbstractDomain<bool> CheckIfLessThan(Expression e1, Expression e2, INumericalAbstractDomain<Variable, Expression> oracleDomain)
{
Contract.Requires(oracleDomain != null);
if (this.IsTop)
{
return CheckOutcome.Top;
}
Polynomial<Variable, Expression> pol;
if (Polynomial<Variable, Expression>.TryToPolynomialForm(e1, this.ExpressionManager.Decoder, out pol))
{
Variable x, y;
Rational k;
if (pol.TryMatch_XMinusYPlusK(out x, out y, out k))
{
var xExp = this.ExpressionManager.Encoder.VariableFor(x);
if (this.CheckIfLessEqualThan(xExp, e2).IsTrue() && oracleDomain.BoundsFor(y).LowerBound > k)
{
return CheckOutcome.True;
}
}
else if (pol.TryMatch_YMinusK(out x, out k))
{
var xExp = this.ExpressionManager.Encoder.VariableFor(x);
if (this.CheckIfLessEqualThan(xExp, e2).IsTrue())
{
return CheckOutcome.True;
}
}
}
switch (this.ExpressionManager.Decoder.OperatorFor(e2))
{
case ExpressionOperator.Addition:
{
// try to match the case e1 < e2 + k, with k > 0. In this case we can check if e1 <= e2
var e2Left = this.ExpressionManager.Decoder.LeftExpressionFor(e2);
var e2Right = this.ExpressionManager.Decoder.RightExpressionFor(e2);
int k;
if (this.ExpressionManager.Decoder.IsConstantInt(e2Right, out k) && k > 0)
{
if (this.CheckIfLessEqualThan(e1, e2Left).IsTrue())
{
return CheckOutcome.True;
}
// if the check if false, we cannot say
}
}
break;
}
return CheckOutcome.Top;
}
/// <summary>
/// Check if the expression <code>e1</code> is strictly smaller than <code>e2</code> using,
/// if needed the abstract domain <code>oracleDomain</code> to refine the information
/// </summary>
public FlatAbstractDomain<bool> CheckIfLessEqualThan(Expression e1, Expression e2, INumericalAbstractDomain<Variable, Expression> oracleDomain)
{
// First we try it without the oracle domain
var directTry = CheckIfLessEqualThan(e1, e2);
if (directTry.IsTop)
{
return CommonChecks.CheckLessEqualThan(e1, e2, oracleDomain, this.ExpressionManager.Decoder);
}
return directTry;
}
public List<Pair<Variable, Int32>> IntConstants
{
get
{
return new List<Pair<Variable, Int32>>();
}
}
public IEnumerable<Expression> LowerBoundsFor(Expression v, bool strict)
{
return this.LowerBoundsFor(this.ExpressionManager.Decoder.UnderlyingVariable(v), strict);
}
public IEnumerable<Expression> LowerBoundsFor(Variable v, bool strict)
{
var result = new Set<Expression>();
if (strict)
{
return result;
}
foreach (var pair in this.Elements)
{
var valueSet = pair.Value;
if (valueSet.IsNormal() && valueSet.Contains(v))
{
result.Add(this.ExpressionManager.Encoder.VariableFor(pair.Key));
}
}
return result;
}
public IEnumerable<Expression> UpperBoundsFor(Expression v, bool strict)
{
return UpperBoundsFor(this.ExpressionManager.Decoder.UnderlyingVariable(v), strict);
}
public IEnumerable<Expression> UpperBoundsFor(Variable v, bool strict)
{
var result = new Set<Expression>();
SetOfConstraints<Variable> value;
if (!strict && this.TryGetValue(v, out value) && value.IsNormal())
{
foreach (var x in value.Values)
{
result.Add(this.ExpressionManager.Encoder.VariableFor(x));
}
}
return result;
}
public IEnumerable<Variable> EqualitiesFor(Variable v)
{
var result = new Set<Variable>();
SetOfConstraints<Variable> upperBounds;
if (this.TryGetValue(v, out upperBounds) && upperBounds.IsNormal())
{
foreach (var x in upperBounds.Values)
{
SetOfConstraints<Variable> other;
if (!x.Equals(v) && this.TryGetValue(x, out other) && other.IsNormal() && other.Contains(v))
{
result.Add(x);
}
}
}
return result;
}
///<summary>By default, it does nothing</summary>
public void AssumeInDisInterval(Variable x, DisInterval value)
{
// does nothing
}
public FlatAbstractDomain<bool> CheckIfLessThan(Expression e1, Expression e2)
{
return CheckIfLessThan(e1, e2, TopNumericalDomain<Variable, Expression>.Singleton);
}
public FlatAbstractDomain<bool> CheckIfLessThanIncomplete(Expression e1, Expression e2)
{
return this.CheckIfLessThan(e1, e2);
}
public FlatAbstractDomain<bool> CheckIfLessThan(Variable v1, Variable v2)
{
return this.CheckIfLessThan(this.ExpressionManager.Encoder.VariableFor(v1), this.ExpressionManager.Encoder.VariableFor(v2));
}
public FlatAbstractDomain<bool> CheckIfLessThan_Un(Expression e1, Expression e2)
{
return this.CheckIfLessThan(e1, e2);
}
public FlatAbstractDomain<bool> CheckIfLessEqualThan(Expression e1, Expression e2)
{
if (this.IsTop)
{
return CheckOutcome.Top;
}
var decoder = this.ExpressionManager.Decoder;
var stripped1Var = decoder.UnderlyingVariable(decoder.Stripped(e1));
SetOfConstraints<Variable> value;
if (this.TryGetValue(stripped1Var, out value) && value.IsNormal())
{
if (value.Contains(decoder.UnderlyingVariable(e2)))
{
return CheckOutcome.True;
}
if (value.Contains(decoder.UnderlyingVariable(decoder.Stripped(e2))))
{
return CheckOutcome.True;
}
foreach (var eTmp in value.Values)
{
SetOfConstraints<Variable> bounds;
if (this.TryGetValue(eTmp, out bounds) &&
(bounds.Contains(decoder.UnderlyingVariable(e2)) || bounds.Contains(decoder.UnderlyingVariable(decoder.Stripped(e2)))))
{ // e1 <= eTmp , eTmp <= e2 => e1 <= e2
return CheckOutcome.True;
}
}
}
if (this.TryGetValue(decoder.UnderlyingVariable(e2), out value) && value.IsNormal())
{
if (this.CheckIfLessThan(e2, decoder.Stripped(e1), TopNumericalDomain<Variable, Expression>.Singleton) == CheckOutcome.True)
{
return CheckOutcome.False;
}
}
// This is a useful case when the underlying framework has not assigned a value to the variable
Variable v1, v2;
int k1, k2;
if (decoder.TryMatchVarPlusConst(e1, out v1, out k1) && decoder.TryMatchVarPlusConst(e2, out v2, out k2) && k1 == k2)
{
return this.CheckIfLessEqualThan(v1, v2);
}
switch (decoder.OperatorFor(e2))
{
case ExpressionOperator.Addition:
{
// try to match e1 <= e21 + k, k > 0
var e2Left = decoder.LeftExpressionFor(e2);
var e2Right = decoder.RightExpressionFor(e2);
int k;
if (decoder.IsConstantInt(e2Right, out k) && k > 0)
{
if (this.CheckIfLessEqualThan(e1, e2Left).IsTrue())
{
return CheckOutcome.True;
}
}
}
break;
}
return CheckOutcome.Top;
}
public FlatAbstractDomain<bool> CheckIfLessEqualThan(Variable v1, Variable v2)
{
return this.CheckIfLessEqualThan(this.ExpressionManager.Encoder.VariableFor(v1), this.ExpressionManager.Encoder.VariableFor(v2));
}
public FlatAbstractDomain<bool> CheckIfLessEqualThan_Un(Expression e1, Expression e2)
{
return this.CheckIfLessEqualThan(e1, e2);
}
public FlatAbstractDomain<bool> CheckIfLessEqualThanIncomplete(Expression e1, Expression e2)
{
if (this.IsTop)
{
return CheckOutcome.Top;
}
var decoder = this.ExpressionManager.Decoder;
var stripped1Var = decoder.UnderlyingVariable(decoder.Stripped(e1));
SetOfConstraints<Variable> value;
if (this.TryGetValue(stripped1Var, out value) && value.IsNormal())
{
if (value.Contains(decoder.UnderlyingVariable(e2)))
{
return CheckOutcome.True;
}
if (value.Contains(decoder.UnderlyingVariable(decoder.Stripped(e2))))
{
return CheckOutcome.True;
}
}
if (this.TryGetValue(decoder.UnderlyingVariable(e2), out value) && value.IsNormal())
{
if (this.CheckIfLessThan(e2, decoder.Stripped(e1), TopNumericalDomain<Variable, Expression>.Singleton) == CheckOutcome.True)
{
return CheckOutcome.False;
}
}
switch (decoder.OperatorFor(e2))
{
case ExpressionOperator.Addition:
{
// try to match e1 <= e21 + k, k > 0
var e2Left = decoder.LeftExpressionFor(e2);
var e2Right = decoder.RightExpressionFor(e2);
int k;
if (decoder.IsConstantInt(e2Right, out k) && k > 0)
{
if (this.CheckIfLessEqualThanIncomplete(e1, e2Left).IsTrue())
{
return CheckOutcome.True;
}
}
}
break;
}
return CheckOutcome.Top;
}
public FlatAbstractDomain<bool> CheckIfEqual(Expression e1, Expression e2)
{
FlatAbstractDomain<bool> c1, c2;
if ((c1 = CheckIfLessEqualThan(e1, e2)).IsNormal() && (c2 = CheckIfLessEqualThan(e2, e1)).IsNormal())
{
return new FlatAbstractDomain<bool>(c1.BoxedElement && c2.BoxedElement);
}
return CheckOutcome.Top;
}
public FlatAbstractDomain<bool> CheckIfEqualIncomplete(Expression e1, Expression e2)
{
FlatAbstractDomain<bool> c1, c2;
if ((c1 = CheckIfLessEqualThan(e1, e2)).IsNormal() && (c2 = CheckIfLessEqualThan(e2, e1)).IsNormal())
{
return new FlatAbstractDomain<bool>(c1.BoxedElement && c2.BoxedElement);
}
return CheckOutcome.Top;
}
override protected WeakUpperBoundsEqual<Variable, Expression> Factory()
{
return new WeakUpperBoundsEqual<Variable, Expression>(this.ExpressionManager);
}
#endregion
#region INumericalAbstractDomain<Variable, Expression> Members
/// <summary>
/// Perform the parallel assignment, and improved the precision using the information from the oracle domain
/// </summary>
/// <param name="sourcesToTargets"></param>
[SuppressMessage("Microsoft.Contracts", "Assert-1-0")]
public void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> convert)
{
Debug.Assert(false); // Should not be called in the current Clousot setting
// Recall that we are solving the following problem. We have a new alphabet of variables V and an old alphabet of variables V'.
// The current state holds constraints over old variables v'1 <= v'2.
//
// The sourcesToTargets map represents assignments from old variables to new variables. An entry
// v' -> v1, v2, ... vn represents the assignments v1 := v', v2 := v', ... vn := v'
//
// Thus, if the current state holds v'1 <= v'2, and we have
// v'1 -> v11, v12, ..., v1n
// v'2 -> v21, v22, ..., v2m
//
// Then "all" information about v'1 <= v'2 expressed in the new state would be the conjunction of constraints
// v1i <= v2j, for i=1..n and j=1..m
//
// Clearly, we don't generally want to produce this quadratic number of constraints (although in practice it is rare
// to see more than 1 new variable assigned the same old variable).
//
// Thus, in practice, we might pick a "canonical" new name for an old variable, say the first in the list (v11 and v21).
// This would then give us a single new constraint for v'1 <= v'2, namely v11 <= v21.
//
// To compute this, we use the sourcesToTargets map as our canonical map M from old to new, by simply using the first in the list
// as the canonical new variable.
// Then it is simple to produce the new state: iterate over all constraints v'1 <= v'2 in the old state, and simply put
// M(v'1) <= M(v'2) into the new state.
//
// The fact that we have to do this computation "in-place" is annoying. It would be simpler to produce a new state.
// Thus, we will compute the new mappings on the side, then clear the current state, then add the new mappings back.
// adding the domain-generated variables to the map as identity
var oldToNewMap = new Dictionary<Variable, FList<Variable>>(sourcesToTargets);
if (!this.IsTop)
{
foreach (var e in this.Variables)
{
if (this.ExpressionManager.Decoder.IsSlackVariable(e))
oldToNewMap.Add(e, FList<Variable>.Cons(e, FList<Variable>.Empty));
}
}
// when x has several targets including itself, the canonical element shouldn't be itself
foreach (var sourceToTargets in sourcesToTargets)
{
var source = sourceToTargets.Key;
var targets = sourceToTargets.Value;
if (targets.Length() > 1 && targets.Head.Equals(source))
{
var newTargets = FList<Variable>.Cons(targets.Tail.Head, FList<Variable>.Cons(source, targets.Tail.Tail));
oldToNewMap[source] = newTargets;
}
}
var newMappings = new Dictionary<Variable, Set<Variable>>(this.Count);
foreach (var oldLeft_Pair in this.Elements)
{
if (!oldToNewMap.ContainsKey(oldLeft_Pair.Key))
{
continue;
}
var targets = oldToNewMap[oldLeft_Pair.Key];
var newLeft = targets.Head; // our canonical element
var oldBounds = oldLeft_Pair.Value;
if (!oldBounds.IsNormal())
{
continue;
}
foreach (var oldRight in oldBounds.Values)
{
if (!oldToNewMap.ContainsKey(oldRight))
{
continue;
}
var newRight = oldToNewMap[oldRight].Head; // our canonical element
AddUpperBound(newLeft, newRight, newMappings);
}
}
// Precision improvements:
//
// Consider:
// if (x < y) x = y;
// Debug.Assert(x >= y);
//
// This is an example where at the end of the then branch, we have a single old variable being assigned to new new variables:
// x := y' and y := y'
// Since in this branch, we obviously have y' => y', the new renamed state should have y => x and x => y. That way, at the join,
// the constraint x >= y is retained.
//
foreach (var pair in sourcesToTargets)
{
var targets = pair.Value;
var newCanonical = targets.Head;
targets = targets.Tail;
while (targets != null)
{
// make all other targets equal to canonical (rather than n^2 combinations)
AddUpperBound(newCanonical, targets.Head, newMappings);
AddUpperBound(targets.Head, newCanonical, newMappings);
targets = targets.Tail;
}
}
// now clear the current state
this.ClearElements();
// now add the new mappings
foreach (var key in newMappings.Keys)
{
var bounds = newMappings[key];
if (bounds.Count == 0)
continue;
var newBoundsFromClosure = new Set<Variable>();
foreach (var upp in bounds)
{
if (!upp.Equals(key) && newMappings.ContainsKey(upp))
{
newBoundsFromClosure.AddRange(newMappings[upp]);
}
}
bounds.AddRange(newBoundsFromClosure);
this.AddElement(key, new SetOfConstraints<Variable>(bounds, false));
}
}
public INumericalAbstractDomain<Variable, Expression> RemoveRedundanciesWith(INumericalAbstractDomain<Variable, Expression> oracle)
{
var result = this.DuplicateMe();
// if (this.ExpressionManager.Encoder != null)
{
foreach (var pair in this.Elements)
{
if (pair.Value.IsNormal())
{
result.AddElement(pair.Key, pair.Value);
}
else
{
var newExp = new Set<Variable>();
foreach (var val in pair.Value.Values)
{
// x <= x
if (pair.Value.Equals(val))
{
continue;
}
// x <= exp
var leq = oracle.CheckIfLessEqualThan(pair.Key, val);
if (!leq.IsNormal() || !leq.BoxedElement)
{ // Then it is not implied by oracle
newExp.Add(val);
}
}
if (newExp.Count > 0)
{
result.AddElement(pair.Key, new SetOfConstraints<Variable>(newExp, false));
}
}
}
}
return result;
}
#endregion
#region INumericalAbstractDomainQuery<Variable,Expression> Members
public Variable ToVariable(Expression exp)
{
return this.ExpressionManager.Decoder.UnderlyingVariable(exp);
}
#endregion
#region Particular cases for IAbstractDomain
public override WeakUpperBoundsEqual<Variable, Expression> Join(WeakUpperBoundsEqual<Variable, Expression> right)
{
// Here we do not have trivial joins as we want to join maps of different cardinality
if (this.IsBottom)
return right;
if (right.IsBottom)
return this;
var result = Factory();
foreach (var pair in this.Elements) // For all the elements in the intersection do the point-wise join
{
SetOfConstraints<Variable> intersection;
SetOfConstraints<Variable> right_x;
if (right.TryGetValue(pair.Key, out right_x))
{
// Implementation of transitive closure using the steps option
closureSteps = DefaultClosureSteps;
Contract.Assume(pair.Value != null);
var closedleft = new Set<Variable>(pair.Value.Values);
var closedright = new Set<Variable>(right_x.Values);
while (closureSteps > 0)
{
// here we do a transitive closure step
var templeft = new Set<Variable>(closedleft);
var tempright = new Set<Variable>(closedright);
foreach (var e in closedleft)
{
SetOfConstraints<Variable> this_e;
if (this.TryGetValue(e, out this_e) && !this_e.IsTop)
{
var tempSet = new Set<Variable>(this_e.Values);
tempSet.Remove(pair.Key);
templeft.AddRange(tempSet);
}
}
foreach (var e in closedright)
{
SetOfConstraints<Variable> right_e;
if (right.TryGetValue(e, out right_e) && !right_e.IsTop)
{
var tempSet = new Set<Variable>(right_e.Values);
tempSet.Remove(pair.Key);
tempright.AddRange(tempSet);
}
}
closedleft = templeft;
closedright = tempright;
closureSteps--;
}
intersection = new SetOfConstraints<Variable>(closedleft.Intersection(closedright), false);
if (intersection.IsNormal())
{
// We keep in the map only the elements that are != top and != bottom
result[pair.Key] = intersection;
}
}
}
return result;
}
public WeakUpperBoundsEqual<Variable, Expression> Join(WeakUpperBoundsEqual<Variable, Expression> right,
IIntervalAbstraction<Variable, Expression> intervalsForThis, IIntervalAbstraction<Variable, Expression> intervalsForRight)
{
Contract.Requires(right != null);
Contract.Requires(intervalsForThis != null);
Contract.Requires(intervalsForRight != null);
// Here we do not have trivial joins as we want to join maps of different cardinality
if (this.IsBottom)
return right;
if (right.IsBottom)
return this;
var result = this.Factory();
foreach (var pair in this.Elements) // For all the elements in the intersection do the point-wise join
{
var intersection = new SetOfConstraints<Variable>(new Set<Variable>(), false);
var newValues = new Set<Variable>();
SetOfConstraints<Variable> right_x;
if (right.TryGetValue(pair.Key, out right_x))
{
Contract.Assume(pair.Value != null);
intersection = pair.Value.Join(right_x);
if (!intersection.IsTop)
{
newValues.AddRange(intersection.Values);
}
// Foreach x <= y
if (right_x.IsNormal())
{
foreach (var y in right_x.Values)
{
if (newValues.Contains(y))
{
continue;
}
var res = intervalsForThis.CheckIfLessEqualThan(pair.Key, y);
if (!res.IsNormal())
{
continue;
}
if (res.BoxedElement) // If the intervals imply this relation, just keep it
{
newValues.Add(y); // Add x <= y
}
}
}
}
// Foreach x <= y
if (pair.Value.IsNormal())
{
foreach (var y in pair.Value.Values)
{
if (newValues.Contains(y))
{
continue;
}
var res = intervalsForRight.CheckIfLessEqualThan(pair.Key, y);
if (!res.IsNormal())
{
continue;
}
if (res.BoxedElement) // If the intervals imply this relation, just keep it
{
newValues.Add(y); // Add x <= y everywhere
right.TestTrueLessEqualThan(pair.Key, y);
}
}
}
if (!newValues.IsEmpty)
{
result[pair.Key] = new SetOfConstraints<Variable>(newValues, false);
}
}
foreach (var x_pair in right.Elements)
{
if (this.ContainsKey(x_pair.Key))
{
// Case already handled
continue;
}
var newValues = new Set<Variable>();
// Foreach x <= y
if (x_pair.Value.IsNormal())
{
foreach (var y in x_pair.Value.Values)
{
var res = intervalsForThis.CheckIfLessEqualThan(x_pair.Key, y);
if (!res.IsNormal())
{
continue;
}
if (res.BoxedElement) // If the intervals imply this relation, just keep it
{
newValues.Add(y); // Add x <= y
this.TestTrueLessEqualThan(x_pair.Key, y);
}
}
if (!newValues.IsEmpty)
{
result[x_pair.Key] = new SetOfConstraints<Variable>(newValues, false);
}
}
}
return result;
}
#endregion
#region IPureExpressionAssignments<Expression> Members
public List<Variable> Variables
{
get
{
var result = new List<Variable>();
var inside = new Set<Variable>();
foreach (var x_pair in this.Elements)
{
result.Add(x_pair.Key);
Contract.Assume(x_pair.Value != null);
if (!x_pair.Value.IsTop)
{
inside.AddRange(x_pair.Value.Values);
}
}
result.AddRange(inside);
return result;
}
}
public IEnumerable<Variable> SlackVariables
{
get
{
var seen = new Set<Variable>();
var decoder = this.ExpressionManager.Decoder;
foreach (var x_pair in this.Elements)
{
if (decoder.IsSlackVariable(x_pair.Key))
{
seen.Add(x_pair.Key);
yield return x_pair.Key;
}
if (!x_pair.Value.IsTop)
{
foreach (var y in x_pair.Value.Values)
{
if (decoder.IsSlackVariable(y) && !seen.Contains(y))
{
seen.Add(y);
yield return y;
}
}
}
}
}
}
public void AddVariable(Variable var)
{
// Does nothing, as we assume variables initialized to top
}
public void ProjectVariable(Variable var)
{
this.RemoveElement(var);
var toUpdate = new List<Pair<Variable, SetOfConstraints<Variable>>>();
foreach (var pair in this.Elements)
{
if (pair.Value.IsNormal() && pair.Value.Contains(var))
{
var s = new Set<Variable>(pair.Value.Values);
s.Remove(var);
toUpdate.Add(pair.Key, new SetOfConstraints<Variable>(s, false));
}
}
foreach (var pair in toUpdate)
{
this[pair.One] = pair.Two;
}
}
[ContractVerification(false)]
public void RemoveVariable(Variable var)
{
var toUpdate = new Dictionary<Variable, SetOfConstraints<Variable>>(this.Count);
var forVar = new Set<Variable>();
SetOfConstraints<Variable> value;
if (this.TryGetValue(var, out value) && value.IsNormal())
{
forVar = new Set<Variable>(value.Values);
}
foreach (var x_Pair in this.Elements)
{
var constraints = x_Pair.Value;
if (!constraints.IsNormal() || !constraints.Contains(var))
{
continue;
}
var newConstraints = new Set<Variable>(constraints.Values);
newConstraints.AddRange(forVar);
newConstraints.Remove(var);
toUpdate[x_Pair.Key] = new SetOfConstraints<Variable>(newConstraints);
}
foreach (var x_pair in toUpdate)
{
this[x_pair.Key] = x_pair.Value;
}
this.RemoveElement(var);
}
public void RenameVariable(Variable OldName, Variable NewName)
{
foreach (var x_pair in this.Elements)
{
if (x_pair.Value.IsNormal())
{
var oldVal = x_pair.Value;
if (oldVal.Contains(OldName))
{
var newVal = new Set<Variable>(oldVal.Values);
newVal.Remove(OldName);
newVal.Add(NewName);
this[x_pair.Key] = new SetOfConstraints<Variable>(newVal, false);
}
}
}
}
#endregion
#region IPureExpressionTest<Expression> Members
IAbstractDomainForEnvironments<Variable, Expression> IPureExpressionTest<Variable, Expression>.TestTrue(Expression guard)
{
return this.TestTrue(guard);
}
public WeakUpperBoundsEqual<Variable, Expression> TestTrue(Expression guard)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
return ProcessTestTrue(guard);
}
IAbstractDomainForEnvironments<Variable, Expression> IPureExpressionTest<Variable, Expression>.TestFalse(Expression guard)
{
return this.TestFalse(guard);
}
void IPureExpressionTest<Variable, Expression>.AssumeDomainSpecificFact(DomainSpecificFact fact)
{
this.AssumeDomainSpecificFact(fact);
}
public WeakUpperBoundsEqual<Variable, Expression> TestFalse(Expression guard)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
// if (this.ExpressionManager.Encoder != null)
{
var notGuard = this.ExpressionManager.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Not, guard);
return TestTrue(notGuard);
}
/*
else
{
return ProcessTestFalse(guard);
}
*/
}
/// <summary>
/// Does nothing
/// </summary>
public INumericalAbstractDomain<Variable, Expression> TestTrueGeqZero(Expression exp)
{
return this;
}
INumericalAbstractDomain<Variable, Expression> INumericalAbstractDomain<Variable, Expression>.TestTrueEqual(Expression exp1, Expression exp2)
{
return this.TestTrueEqual(exp1, exp2);
}
#endregion
#region WeakUpperBounds-Specific Methods
INumericalAbstractDomain<Variable, Expression> INumericalAbstractDomain<Variable, Expression>.TestTrueLessThan(Expression e1, Expression e2)
{
return this.HelperForLessThan(e1, e2);
}
public WeakUpperBoundsEqual<Variable, Expression> TestTrueLessThan(Expression e1, Expression e2)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
return this.HelperForLessThan(e1, e2);
}
INumericalAbstractDomain<Variable, Expression> INumericalAbstractDomain<Variable, Expression>.TestTrueLessEqualThan(Expression e1, Expression e2)
{
return this.TestTrueLessEqualThan(e1, e2);
}
public WeakUpperBoundsEqual<Variable, Expression> TestTrueLessEqualThan(Expression e1, Expression e2)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
return this.HelperForLessEqualThan(e1, e2);
}
public WeakUpperBoundsEqual<Variable, Expression> TestTrueLessEqualThan(Variable e1, Variable e2)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
return this.TestTrueLessEqualThan(this.ExpressionManager.Encoder.VariableFor(e1), this.ExpressionManager.Encoder.VariableFor(e2));
}
public WeakUpperBoundsEqual<Variable, Expression> TestTrueEqual(Expression e1, Expression e2)
{
return this.HelperForEqual(e1, e2);
}
#endregion
#region Protected methods
protected WeakUpperBoundsEqual<Variable, Expression> ProcessTestTrue(Expression guard)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
var decoder = this.ExpressionManager.Decoder;
switch (decoder.OperatorFor(guard))
{
#region all the cases
case ExpressionOperator.Equal:
case ExpressionOperator.Equal_Obj:
{
var left = decoder.LeftExpressionFor(guard);
var right = decoder.RightExpressionFor(guard);
var leftVar = decoder.UnderlyingVariable(left);
var rightVar = decoder.UnderlyingVariable(right);
SetOfConstraints<Variable> v1, v2;
if (this.TryGetValue(leftVar, out v1) && this.TryGetValue(rightVar, out v2))
{
var intersection = v1.Meet(v2);
if (v1.IsBottom)
{
return this.Bottom;
}
else
{
this[leftVar] = intersection;
this[rightVar] = intersection;
return this;
}
}
else
{
// Try to figure out if it is in the form of (e11 rel e12) == 0
Expression e11, e12;
ExpressionOperator op;
if (decoder.Match_E1relopE2eq0(left, right, out op, out e11, out e12))
{
return ProcessTestFalse(left);
}
else
{
// F: We do not want this domain to track arbitrary equalities (because of performances),
// so if we do not understand the equality, we abstract it
return this;
}
}
}
case ExpressionOperator.GreaterEqualThan:
{
// left >= right, so we want to add right <= left
var left = this.ExpressionManager.Decoder.LeftExpressionFor(guard);
var right = this.ExpressionManager.Decoder.RightExpressionFor(guard);
return this.TestTrueLessEqualThan(right, left);
}
case ExpressionOperator.GreaterThan:
{
// "left > right", so we add the constraint
var left = decoder.LeftExpressionFor(guard);
var right = decoder.RightExpressionFor(guard);
return HelperForLessThan(right, left);
}
case ExpressionOperator.LessEqualThan:
{
// "left <= right"
var left = decoder.LeftExpressionFor(guard);
var right = decoder.RightExpressionFor(guard);
return HelperForLessEqualThan(left, right);
}
case ExpressionOperator.LessThan:
{
// "left < right"
var left = decoder.LeftExpressionFor(guard);
var right = decoder.RightExpressionFor(guard);
return HelperForLessThan(left, right);
}
// We abstract away the symbolic reasoning for unsigned as it may be incorrect
// Example "sv1 CLT_Un sv2" and sv2 is -1, so it should be understood as sv1 CLT_Un UInt.MaxValue - this reasoning is done by intervals
case ExpressionOperator.LessThan_Un:
case ExpressionOperator.LessEqualThan_Un:
case ExpressionOperator.GreaterThan_Un:
case ExpressionOperator.GreaterEqualThan_Un:
{
return this;
}
case ExpressionOperator.LogicalAnd:
{
var leftDomain = this.DuplicateMe();
var rightDomain = this.DuplicateMe();
leftDomain = leftDomain.ProcessTestTrue(decoder.LeftExpressionFor(guard));
rightDomain = rightDomain.ProcessTestTrue(decoder.RightExpressionFor(guard));
return leftDomain.Meet(rightDomain);
}
case ExpressionOperator.LogicalOr:
{
var leftDomain = this.DuplicateMe();
var rightDomain = this.DuplicateMe();
leftDomain = leftDomain.ProcessTestTrue(decoder.LeftExpressionFor(guard));
rightDomain = rightDomain.ProcessTestTrue(decoder.RightExpressionFor(guard));
return leftDomain.Join(rightDomain);
}
case ExpressionOperator.Not:
{
return this.ProcessTestFalse(decoder.LeftExpressionFor(guard));
}
default:
{
return this;
}
#endregion
}
}
protected WeakUpperBoundsEqual<Variable, Expression> ProcessTestFalse(Expression guard)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
var decoder = this.ExpressionManager.Decoder;
switch (this.ExpressionManager.Decoder.OperatorFor(guard))
{
#region all the cases
case ExpressionOperator.Equal:
case ExpressionOperator.Equal_Obj:
return HelperForNotEqual(decoder.LeftExpressionFor(guard), decoder.RightExpressionFor(guard));
case ExpressionOperator.GreaterEqualThan:
{
// !(left >= right) is equivalent to (left < right)
var left = decoder.LeftExpressionFor(guard);
var right = decoder.RightExpressionFor(guard);
return HelperForLessThan(left, right);
}
case ExpressionOperator.GreaterThan:
{
// !(left > right) is equivalent to left <= right
var left = decoder.LeftExpressionFor(guard);
var right = decoder.RightExpressionFor(guard);
return HelperForLessEqualThan(left, right);
}
case ExpressionOperator.LessEqualThan:
{
// !(left <= right) is equivalent to (left > right)
var left = decoder.LeftExpressionFor(guard);
var right = decoder.RightExpressionFor(guard);
return HelperForLessThan(right, left);
}
case ExpressionOperator.LessThan:
{
// !(left < right) is equivalent to (left >= right) that is (right <= left)
var left = decoder.LeftExpressionFor(guard);
var right = decoder.RightExpressionFor(guard);
return this.HelperForLessEqualThan(right, left);
}
case ExpressionOperator.GreaterThan_Un:
case ExpressionOperator.LessThan_Un:
case ExpressionOperator.LessEqualThan_Un:
case ExpressionOperator.GreaterEqualThan_Un:
{
return this;
}
case ExpressionOperator.LogicalAnd:
{
var leftDomain = this.DuplicateMe();
var rightDomain = this.DuplicateMe();
leftDomain = leftDomain.ProcessTestFalse(decoder.LeftExpressionFor(guard));
rightDomain = rightDomain.ProcessTestFalse(decoder.RightExpressionFor(guard));
return leftDomain.Join(rightDomain);
}
case ExpressionOperator.LogicalOr:
{
var leftDomain = this.DuplicateMe();
var rightDomain = this.DuplicateMe();
leftDomain = leftDomain.ProcessTestFalse(decoder.LeftExpressionFor(guard)) as WeakUpperBoundsEqual<Variable, Expression>;
rightDomain = rightDomain.ProcessTestFalse(decoder.RightExpressionFor(guard)) as WeakUpperBoundsEqual<Variable, Expression>;
return leftDomain.Meet(rightDomain);
}
case ExpressionOperator.Not:
{
var left = this.ExpressionManager.Decoder.LeftExpressionFor(guard);
return this.ProcessTestTrue(left);
}
default:
return this;
#endregion
}
}
/// <summary>
/// Handle the case <code>e1 < e2</code> as it was <code>e1 <= e2</code>
/// </summary>
private WeakUpperBoundsEqual<Variable, Expression> HelperForLessThan(Expression e1, Expression e2)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
var decoder = this.ExpressionManager.Decoder;
if (decoder.IsBinaryExpression(e2) && decoder.OperatorFor(e2) == ExpressionOperator.Addition)
{
var exp = decoder.RightExpressionFor(e2);
int value;
if (decoder.IsConstantInt(exp, out value) && value == 1)
{
return HelperForLessEqualThan(e1, decoder.LeftExpressionFor(e2));
}
}
if (decoder.IsBinaryExpression(e1) && decoder.OperatorFor(e1) == ExpressionOperator.Subtraction)
{
var exp = decoder.RightExpressionFor(e1);
int value;
if (decoder.IsConstantInt(exp, out value) && value == 1)
{
return HelperForLessEqualThan(decoder.LeftExpressionFor(e1), e2);
}
}
return HelperForLessEqualThan(e1, e2);
}
private WeakUpperBoundsEqual<Variable, Expression> HelperForLessEqualThan(Expression e1, Expression e2)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
var decoder = this.ExpressionManager.Decoder;
var e1Var = decoder.UnderlyingVariable(e1);
var e2Var = decoder.UnderlyingVariable(e2);
if (!decoder.IsSlackOrFrameworkVariable(e1Var) || !decoder.IsSlackOrFrameworkVariable(e2Var))
{
return this;
}
SetOfConstraints<Variable> this_e1;
if (this.TryGetValue(e1Var, out this_e1) && !this_e1.IsTop)
{
var newConstraints = new Set<Variable>(this_e1.Values);
newConstraints.Add(e2Var);
this[e1Var] = new SetOfConstraints<Variable>(newConstraints, false);
}
var newValues = new Set<Variable>();
var stripped = decoder.Stripped(e1);
var strippedVar = decoder.UnderlyingVariable(stripped);
if (decoder.IsVariable(stripped) || decoder.IsConstant(stripped))
{
newValues.Add(e2Var); // e1 <= e2
newValues.Add(decoder.UnderlyingVariable(decoder.Stripped(e2))); // Add "e1 <= e2'", if e2 was in the form "(int32) e2'" or similar
SetOfConstraints<Variable> this_stripped;
if (this.TryGetValue(strippedVar, out this_stripped) && !this_stripped.IsTop)
{ // e1 <= "all the values before"
newValues.AddRange(this_stripped.Values);
}
SetOfConstraints<Variable> this_e2;
if (this.TryGetValue(e2Var, out this_e2) && !this_e2.IsTop)
{ // e1 <= "all the values e2 is smaller than"
newValues.AddRange(this_e2.Values);
}
this[strippedVar] = new SetOfConstraints<Variable>(newValues, false);
}
else if (!this.ContainsKey(strippedVar))
{
var tmp = new Set<Variable>() { e2Var, decoder.UnderlyingVariable(decoder.Stripped(e2)) };
this[strippedVar] = new SetOfConstraints<Variable>(tmp, false);
}
Polynomial<Variable, Expression> e1LEQe2;
if (Polynomial<Variable, Expression>.TryToPolynomialForm(ExpressionOperator.LessEqualThan, e1, e2, decoder, out e1LEQe2))
{
Rational k1, k2, k;
Variable x1, x2;
if (e1LEQe2.TryMatch_k1XPlusk2YLessThanK(out k1, out x1, out k2, out x2, out k))
{
if (k <= 0)
{
if (k1 == 1 && k2 == -1) // x1 - x2 <= k <= 0 => x1 < x2
{
this.UpdateConstraintsFor(x1, x2);
}
else if (k1 == -1 && k2 == 1) // -x1 + x2 <= k <= 0 => x2 < x1
{
this.UpdateConstraintsFor(x2, x1);
}
}
if (k == 1)
{
if (k1 == 1 && k2 == -1) // x1 - x2 < 1 => x1 < x2 +1 => x1 <= x2
{
this.UpdateConstraintsFor(x1, x2);
}
else if (k1 == -1 && k2 == 1)
{
this.UpdateConstraintsFor(x2, x1);
}
}
}
}
var valuesOfStripped = this[strippedVar];
if (valuesOfStripped.IsNormal())
{
var toBeUpdated = new List<Pair<Variable, SetOfConstraints<Variable>>>();
// "e1 <= e2", so we search all the variables to see if "e0 <= e1"
foreach (var e0_pair in this.Elements)
{
if (e0_pair.Value.IsNormal())
{
if (e0_pair.Value.Contains(strippedVar))
{
var values = new Set<Variable>(e0_pair.Value.Values);
values.AddRange(valuesOfStripped.Values);
toBeUpdated.Add(e0_pair.Key, new SetOfConstraints<Variable>(values, false));
}
}
}
if (toBeUpdated.Count > 0)
{
foreach (var pair in toBeUpdated)
{
this[pair.One] = pair.Two;
}
}
}
return this;
}
private WeakUpperBoundsEqual<Variable, Expression> HelperForNotEqual(Expression e1, Expression e2)
{
Contract.Ensures(Contract.Result<WeakUpperBoundsEqual<Variable, Expression>>() != null);
int value;
// If it is in the for "op(e11, e12) relSym k" where relSym is a relational symbol, and k a constant
if (this.ExpressionManager.Decoder.OperatorFor(e1).IsRelationalOperator() && this.ExpressionManager.Decoder.IsConstantInt(e2, out value))
{
if (value == 0)
{ // that is !!(e1)
return this.TestTrue(e1);
}
if (value == 1)
{ // that is !e1
return this.TestFalse(e1);
}
}
return this;
}
private WeakUpperBoundsEqual<Variable, Expression> HelperForEqual(Expression e1, Expression e2)
{
var result = this.HelperForLessEqualThan(e1, e2).HelperForLessEqualThan(e2, e1);
// The code below is to share the constraints between e1 and e2
var e1Var = this.ExpressionManager.Decoder.UnderlyingVariable(e1);
var e2Var = this.ExpressionManager.Decoder.UnderlyingVariable(e2);
SetOfConstraints<Variable> e1Leq, e2Leq;
if (result.TryGetValue(e1Var, out e1Leq) && result.TryGetValue(e2Var, out e2Leq))
{
var meet = e1Leq.Meet(e2Leq);
result[e1Var] = meet;
result[e2Var] = meet;
}
return result;
}
#endregion
#region Private and Protected methods
/// <summary>
/// Add the constraint <code>x < y ></code>to this environment.
/// If <code>x</code> already has some constraints related to him, we make the union of constraints (but we do not propagate)
/// </summary>
private void UpdateConstraintsFor(Variable x, Variable y)
{
var newValues = new Set<Variable>();
SetOfConstraints<Variable> bounds;
if (this.TryGetValue(x, out bounds) && !bounds.IsTop)
{
newValues.AddRange(bounds.Values);
}
newValues.Add(y);
this[x] = new SetOfConstraints<Variable>(newValues, false); // Do the update
}
#endregion
#region ToLogicalFormula
protected override string ToLogicalFormula(Variable d, SetOfConstraints<Variable> c)
{
if (!c.IsNormal())
{
return null;
}
var result = new List<string>();
var niceD = ExpressionPrinter.ToString(d, this.ExpressionManager.Decoder);
foreach (var y in c.Values)
{
var niceY = ExpressionPrinter.ToString(y, this.ExpressionManager.Decoder);
result.Add(ExpressionPrinter.ToStringBinary(ExpressionOperator.LessEqualThan, niceD, niceY));
}
return ExpressionPrinter.ToLogicalFormula(ExpressionOperator.LogicalAnd, result);
}
protected override T To<T>(Variable d, SetOfConstraints<Variable> c, IFactory<T> factory)
{
// F: this are preconditions, but I am lazy...
Contract.Assume(c != null);
if (c.IsTop)
return factory.Constant(true);
if (c.IsBottom)
return factory.Constant(false);
var result = factory.IdentityForAnd;
var x = factory.Variable(d);
// We know the constraints are x <= y
foreach (var y in c.Values)
{
T atom = factory.LessEqualThan(x, factory.Variable(y));
result = factory.And(result, atom);
}
return result;
}
#endregion
#region ToString
public override string ToString()
{
if (this.IsTop)
return "Top";
if (this.IsBottom)
return "Bottom";
var result = new StringBuilder();
result.AppendLine("WUB=:");
foreach (var pair in this.Elements)
{
Contract.Assume(pair.Value != null);
if (!pair.Value.IsTop)
{
var niceX = ExpressionPrinter.ToString(pair.Key, this.ExpressionManager.Decoder);
var niceVal = pair.Value.ToString();
result.AppendLine(niceX + " <= " + niceVal + " ");
}
}
return result.ToString();
}
public string ToString(Expression exp)
{
// if (this.ExpressionManager.Decoder != null)
{
return ExpressionPrinter.ToString(exp, this.ExpressionManager.Decoder);
}
/*else
{
return "< missing expression decoder >";
}*/
}
#endregion
#region Floating point types
public void SetFloatType(Variable v, ConcreteFloat f)
{
// does nothing
}
public FlatAbstractDomain<ConcreteFloat> GetFloatType(Variable v)
{
return FloatTypes<Variable, Expression>.Unknown;
}
#endregion
}
}
| |
using Microsoft.Xna.Framework;
using System.Collections.Generic;
namespace MonoVarmint.Widgets
{
public enum Orientation
{
Vertical,
Horizontal
}
//--------------------------------------------------------------------------------------
/// <summary>
/// StackPanel
/// </summary>
//--------------------------------------------------------------------------------------
[VarmintWidgetShortName("StackPanel")]
public class VarmintWidgetStackPanel : VarmintWidget
{
public Orientation Orientation { get; set; }
private WidgetMargin _myMargin;
public override WidgetMargin Margin
{
get { return _myMargin; }
set
{
// Stack panels always stretch to fill their parent area
_myMargin = value;
if (_myMargin.Left == null) _myMargin.Left = 0;
if (_myMargin.Top == null) _myMargin.Top = 0;
if (_myMargin.Right == null) _myMargin.Right = 0;
if (_myMargin.Bottom == null) _myMargin.Bottom = 0;
}
}
//--------------------------------------------------------------------------------------
/// <summary>
/// ctor
/// </summary>
//--------------------------------------------------------------------------------------
public VarmintWidgetStackPanel()
{
ChildrenAffectFormatting = true;
this.OnRender += Render;
}
//--------------------------------------------------------------------------------------
/// <summary>
/// Render
/// </summary>
//--------------------------------------------------------------------------------------
void Render(GameTime gameTime, VarmintWidget widget)
{
Renderer.DrawBox(AbsoluteOffset, Size, RenderBackgroundColor);
}
bool isUpdating = false;
//--------------------------------------------------------------------------------------
/// <summary>
/// UpdateChildFormatting
/// </summary>
//--------------------------------------------------------------------------------------
protected override void UpdateFormatting_Internal(Vector2 maxExtent, bool updateChildren)
{
if (Orientation == Orientation.Horizontal) UpdateHorizontal(maxExtent);
else UpdateVertical(maxExtent);
// base.UpdateFormatting_Internal(maxExtent);
}
//--------------------------------------------------------------------------------------
/// <summary>
/// UpdateVertical
/// </summary>
//--------------------------------------------------------------------------------------
private void UpdateVertical(Vector2 maxExtent)
{
// Go through all the children and figure out known sizes. Stretched sizes will be double.MaxVlue
float childHeight = 0;
float childWidth = 0;
int stretchedChildren = 0;
foreach(var child in Children)
{
child.UpdateFormatting(maxExtent);
if (child.Size.X > childWidth)
{
childWidth = child.Size.X;
}
if(child.Size.Y == maxExtent.Y)
{
stretchedChildren++;
}
else
{
childHeight += child.Size.Y + (child.Margin?.Top ?? 0) + (child.Margin?.Bottom ?? 0);
}
}
var remainingHeight = maxExtent.Y - childHeight;
if (remainingHeight < 0) remainingHeight = 0;
// reformat all the children now that we know the available sizes
float finalHeight = 0;
foreach (var child in Children)
{
if(child.Size.Y == maxExtent.Y)
{
var childSizeConstraint = new Vector2(
childWidth,
remainingHeight / stretchedChildren);
child.UpdateFormatting(childSizeConstraint);
}
else
{
var childSizeConstraint = new Vector2(
childWidth,
child.Size.Y + (child.Margin?.Top ?? 0) + (child.Margin?.Bottom ?? 0));
child.UpdateFormatting(childSizeConstraint);
}
finalHeight += child.Size.Y + (child.Margin?.Top ?? 0) + (child.Margin?.Bottom ?? 0);
}
this.Size = new Vector2(childWidth, finalHeight);
base.UpdateFormatting_Internal(maxExtent, updateChildren: false);
float verticalOffset = 0;
foreach (var child in Children)
{
child.Offset = new Vector2(child.Offset.X, verticalOffset + (child.Margin?.Top ?? 0));
verticalOffset += child.Size.Y + (child.Margin?.Top ?? 0) + (child.Margin?.Bottom ?? 0);
}
}
//--------------------------------------------------------------------------------------
/// <summary>
/// UpdateHorizontal
/// </summary>
//--------------------------------------------------------------------------------------
private void UpdateHorizontal(Vector2 maxExtent)
{
// Go through all the children and figure out known sizes. Stretched sizes will be double.MaxVlue
float childHeight = 0;
float childWidth = 0;
int stretchedChildren = 0;
foreach (var child in Children)
{
child.UpdateFormatting(maxExtent);
if (child.Size.Y > childHeight)
{
childHeight = child.Size.Y;
}
if (child.Size.X == maxExtent.X)
{
stretchedChildren++;
}
else
{
childWidth += child.Size.X + (child.Margin?.Left ?? 0) + (child.Margin?.Right ?? 0);
}
}
var remainingWidth = maxExtent.X - childWidth;
if (remainingWidth < 0) remainingWidth = 0;
// reformat all the children now that we know the available sizes
float finalWidth = 0;
foreach (var child in Children)
{
if (child.Size.X == maxExtent.X)
{
var childSizeConstraint = new Vector2(
remainingWidth / stretchedChildren,
childHeight);
child.UpdateFormatting(childSizeConstraint);
}
else
{
var childSizeConstraint = new Vector2(
child.Size.X + (child.Margin?.Left ?? 0) + (child.Margin?.Right ?? 0),
childHeight);
child.UpdateFormatting(childSizeConstraint);
}
finalWidth += child.Size.X + (child.Margin?.Left ?? 0) + (child.Margin?.Right ?? 0);
}
this.Size = new Vector2(finalWidth, childHeight);
base.UpdateFormatting_Internal(maxExtent, updateChildren: false);
float horizontalOffset = 0;
foreach (var child in Children)
{
child.Offset = new Vector2(horizontalOffset + (child.Margin?.Left ?? 0), child.Offset.Y);
horizontalOffset += child.Size.X + (child.Margin?.Left ?? 0) + (child.Margin?.Right ?? 0);
}
}
}
}
| |
using Microsoft.TeamFoundation.TestManagement.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.WebApi;
namespace Microsoft.VisualStudio.Services.Agent.Worker.CodeCoverage
{
public sealed class CodeCoverageCommandExtension : AgentService, IWorkerCommandExtension
{
private int _buildId;
// publish code coverage inputs
private string _summaryFileLocation;
private List<string> _additionalCodeCoverageFiles;
private string _codeCoverageTool;
private string _reportDirectory;
public HostTypes SupportedHostTypes => HostTypes.Build;
public void ProcessCommand(IExecutionContext context, Command command)
{
if (string.Equals(command.Event, WellKnownResultsCommand.PublishCodeCoverage, StringComparison.OrdinalIgnoreCase))
{
ProcessPublishCodeCoverageCommand(context, command.Properties);
}
else
{
throw new Exception(StringUtil.Loc("CodeCoverageCommandNotFound", command.Event));
}
}
public Type ExtensionType
{
get
{
return typeof(IWorkerCommandExtension);
}
}
public string CommandArea
{
get
{
return "codecoverage";
}
}
#region publish code coverage helper methods
private void ProcessPublishCodeCoverageCommand(IExecutionContext context, Dictionary<string, string> eventProperties)
{
ArgUtil.NotNull(context, nameof(context));
_buildId = context.Variables.Build_BuildId ?? -1;
if (!IsHostTypeBuild(context) || _buildId < 0)
{
//In case the publishing codecoverage is not applicable for current Host type we continue without publishing
context.Warning(StringUtil.Loc("CodeCoveragePublishIsValidOnlyForBuild"));
return;
}
LoadPublishCodeCoverageInputs(context, eventProperties);
string project = context.Variables.System_TeamProject;
long? containerId = context.Variables.Build_ContainerId;
ArgUtil.NotNull(containerId, nameof(containerId));
Guid projectId = context.Variables.System_TeamProjectId ?? Guid.Empty;
ArgUtil.NotEmpty(projectId, nameof(projectId));
//step 1: read code coverage summary
var reader = GetCodeCoverageSummaryReader(_codeCoverageTool);
context.Output(StringUtil.Loc("ReadingCodeCoverageSummary", _summaryFileLocation));
var coverageData = reader.GetCodeCoverageSummary(context, _summaryFileLocation);
if (coverageData == null || coverageData.Count() == 0)
{
context.Warning(StringUtil.Loc("CodeCoverageDataIsNull"));
}
VssConnection connection = WorkerUtilities.GetVssConnection(context);
var codeCoveragePublisher = HostContext.GetService<ICodeCoveragePublisher>();
codeCoveragePublisher.InitializePublisher(_buildId, connection);
var commandContext = HostContext.CreateService<IAsyncCommandContext>();
commandContext.InitializeCommandContext(context, StringUtil.Loc("PublishCodeCoverage"));
commandContext.Task = PublishCodeCoverageAsync(context, commandContext, codeCoveragePublisher, coverageData, project, projectId, containerId.Value, context.CancellationToken);
context.AsyncCommands.Add(commandContext);
}
private async Task PublishCodeCoverageAsync(
IExecutionContext executionContext,
IAsyncCommandContext commandContext,
ICodeCoveragePublisher codeCoveragePublisher,
IEnumerable<CodeCoverageStatistics> coverageData,
string project,
Guid projectId,
long containerId,
CancellationToken cancellationToken)
{
//step 2: publish code coverage summary to TFS
if (coverageData != null && coverageData.Count() > 0)
{
commandContext.Output(StringUtil.Loc("PublishingCodeCoverage"));
foreach (var coverage in coverageData)
{
commandContext.Output(StringUtil.Format(" {0}- {1} of {2} covered.", coverage.Label, coverage.Covered, coverage.Total));
}
await codeCoveragePublisher.PublishCodeCoverageSummaryAsync(coverageData, project, cancellationToken);
}
// step 3: publish code coverage files as build artifacts
string additionalCodeCoverageFilePath = null;
string destinationSummaryFile = null;
var newReportDirectory = _reportDirectory;
try
{
var filesToPublish = new List<Tuple<string, string>>();
if (!Directory.Exists(newReportDirectory))
{
if (!string.IsNullOrWhiteSpace(newReportDirectory))
{
// user gave a invalid report directory. Write warning and continue.
executionContext.Warning(StringUtil.Loc("DirectoryNotFound", newReportDirectory));
}
newReportDirectory = GetCoverageDirectory(_buildId.ToString(), CodeCoverageConstants.ReportDirectory);
Directory.CreateDirectory(newReportDirectory);
}
var summaryFileName = Path.GetFileName(_summaryFileLocation);
destinationSummaryFile = Path.Combine(newReportDirectory, CodeCoverageConstants.SummaryFileDirectory + _buildId, summaryFileName);
Directory.CreateDirectory(Path.GetDirectoryName(destinationSummaryFile));
File.Copy(_summaryFileLocation, destinationSummaryFile, true);
commandContext.Output(StringUtil.Loc("ModifyingCoberturaIndexFile"));
ModifyCoberturaIndexDotHTML(newReportDirectory, executionContext);
filesToPublish.Add(new Tuple<string, string>(newReportDirectory, GetCoverageDirectoryName(_buildId.ToString(), CodeCoverageConstants.ReportDirectory)));
if (_additionalCodeCoverageFiles != null && _additionalCodeCoverageFiles.Count != 0)
{
additionalCodeCoverageFilePath = GetCoverageDirectory(_buildId.ToString(), CodeCoverageConstants.RawFilesDirectory);
CodeCoverageUtilities.CopyFilesFromFileListWithDirStructure(_additionalCodeCoverageFiles, ref additionalCodeCoverageFilePath);
filesToPublish.Add(new Tuple<string, string>(additionalCodeCoverageFilePath, GetCoverageDirectoryName(_buildId.ToString(), CodeCoverageConstants.RawFilesDirectory)));
}
commandContext.Output(StringUtil.Loc("PublishingCodeCoverageFiles"));
ChangeHtmExtensionToHtmlIfRequired(newReportDirectory, executionContext);
await codeCoveragePublisher.PublishCodeCoverageFilesAsync(commandContext, projectId, containerId, filesToPublish, File.Exists(Path.Combine(newReportDirectory, CodeCoverageConstants.DefaultIndexFile)), cancellationToken);
}
catch (Exception ex)
{
executionContext.Warning(StringUtil.Loc("ErrorOccurredWhilePublishingCCFiles", ex.Message));
}
finally
{
// clean temporary files.
if (!string.IsNullOrEmpty(additionalCodeCoverageFilePath))
{
if (Directory.Exists(additionalCodeCoverageFilePath))
{
Directory.Delete(path: additionalCodeCoverageFilePath, recursive: true);
}
}
if (!string.IsNullOrEmpty(destinationSummaryFile))
{
var summaryFileDirectory = Path.GetDirectoryName(destinationSummaryFile);
if (Directory.Exists(summaryFileDirectory))
{
Directory.Delete(path: summaryFileDirectory, recursive: true);
}
}
if (!Directory.Exists(_reportDirectory))
{
if (Directory.Exists(newReportDirectory))
{
//delete the generated report directory
Directory.Delete(path: newReportDirectory, recursive: true);
}
}
}
}
private ICodeCoverageSummaryReader GetCodeCoverageSummaryReader(string codeCoverageTool)
{
var extensionManager = HostContext.GetService<IExtensionManager>();
ICodeCoverageSummaryReader summaryReader = (extensionManager.GetExtensions<ICodeCoverageSummaryReader>()).FirstOrDefault(x => codeCoverageTool.Equals(x.Name, StringComparison.OrdinalIgnoreCase));
if (summaryReader == null)
{
throw new ArgumentException(StringUtil.Loc("UnknownCodeCoverageTool", codeCoverageTool));
}
return summaryReader;
}
private bool IsHostTypeBuild(IExecutionContext context)
{
var hostType = context.Variables.System_HostType;
if (hostType.HasFlag(HostTypes.Build))
{
return true;
}
return false;
}
private void LoadPublishCodeCoverageInputs(IExecutionContext context, Dictionary<string, string> eventProperties)
{
//validate codecoverage tool input
eventProperties.TryGetValue(PublishCodeCoverageEventProperties.CodeCoverageTool, out _codeCoverageTool);
if (string.IsNullOrEmpty(_codeCoverageTool))
{
throw new ArgumentException(StringUtil.Loc("ArgumentNeeded", "CodeCoverageTool"));
}
//validate summary file input
eventProperties.TryGetValue(PublishCodeCoverageEventProperties.SummaryFile, out _summaryFileLocation);
if (string.IsNullOrEmpty(_summaryFileLocation))
{
throw new ArgumentException(StringUtil.Loc("ArgumentNeeded", "SummaryFile"));
}
if (context.Container != null)
{
// Translate file path back from container path
_summaryFileLocation = context.Container.TranslateToHostPath(_summaryFileLocation);
}
eventProperties.TryGetValue(PublishCodeCoverageEventProperties.ReportDirectory, out _reportDirectory);
if (context.Container != null)
{
// Translate file path back from container path
_reportDirectory = context.Container.TranslateToHostPath(_reportDirectory);
}
string additionalFilesInput;
eventProperties.TryGetValue(PublishCodeCoverageEventProperties.AdditionalCodeCoverageFiles, out additionalFilesInput);
if (!string.IsNullOrEmpty(additionalFilesInput) && additionalFilesInput.Split(',').Count() > 0)
{
if (context.Container != null)
{
_additionalCodeCoverageFiles = additionalFilesInput.Split(',').Select(x => context.Container.TranslateToHostPath(x)).ToList<string>();
}
else
{
_additionalCodeCoverageFiles = additionalFilesInput.Split(',').ToList<string>();
}
}
}
// Changes the index.htm file to index.html if index.htm exists
private void ChangeHtmExtensionToHtmlIfRequired(string reportDirectory, IExecutionContext executionContext)
{
var defaultIndexFile = Path.Combine(reportDirectory, CodeCoverageConstants.DefaultIndexFile);
var htmIndexFile = Path.Combine(reportDirectory, CodeCoverageConstants.HtmIndexFile);
// If index.html does not exist and index.htm exists, copy the .html file from .htm file.
// Don't delete the .htm file as it might be referenced by other .htm/.html files.
if (!File.Exists(defaultIndexFile) && File.Exists(htmIndexFile))
{
try
{
File.Copy(sourceFileName: htmIndexFile, destFileName: defaultIndexFile);
}
catch (Exception ex)
{
// In the warning text, prefer using ex.InnerException when available, for more-specific details
executionContext.Warning(StringUtil.Loc("RenameIndexFileCoberturaFailed", htmIndexFile, defaultIndexFile, _codeCoverageTool, (ex.InnerException ?? ex).ToString()));
}
}
}
/// <summary>
/// This method replaces the default index.html generated by cobertura with
/// the non-framed version
/// </summary>
/// <param name="reportDirectory"></param>
private void ModifyCoberturaIndexDotHTML(string reportDirectory, IExecutionContext executionContext)
{
try
{
string newIndexHtml = Path.Combine(reportDirectory, CodeCoverageConstants.NewIndexFile);
string indexHtml = Path.Combine(reportDirectory, CodeCoverageConstants.DefaultIndexFile);
string nonFrameHtml = Path.Combine(reportDirectory, CodeCoverageConstants.DefaultNonFrameFileCobertura);
if (_codeCoverageTool.Equals("cobertura", StringComparison.OrdinalIgnoreCase) &&
File.Exists(indexHtml) &&
File.Exists(nonFrameHtml))
{
// duplicating frame-summary.html to index.html and renaming index.html to newindex.html
File.Delete(newIndexHtml);
File.Move(indexHtml, newIndexHtml);
File.Copy(nonFrameHtml, indexHtml, overwrite: true);
}
}
catch (Exception ex)
{
// In the warning text, prefer using ex.InnerException when available, for more-specific details
executionContext.Warning(StringUtil.Loc("RenameIndexFileCoberturaFailed", CodeCoverageConstants.DefaultNonFrameFileCobertura, CodeCoverageConstants.DefaultIndexFile, _codeCoverageTool, (ex.InnerException ?? ex).ToString()));
}
}
private string GetCoverageDirectory(string buildId, string directoryName)
{
return Path.Combine(Path.GetTempPath(), GetCoverageDirectoryName(buildId, directoryName));
}
private string GetCoverageDirectoryName(string buildId, string directoryName)
{
return directoryName + "_" + buildId;
}
#endregion
internal static class WellKnownResultsCommand
{
internal static readonly string PublishCodeCoverage = "publish";
internal static readonly string EnableCodeCoverage = "enable";
}
internal static class EnableCodeCoverageEventProperties
{
internal static readonly string BuildTool = "buildtool";
internal static readonly string BuildFile = "buildfile";
internal static readonly string CodeCoverageTool = "codecoveragetool";
internal static readonly string ClassFilesDirectories = "classfilesdirectories";
internal static readonly string ClassFilter = "classfilter";
internal static readonly string SourceDirectories = "sourcedirectories";
internal static readonly string SummaryFile = "summaryfile";
internal static readonly string ReportDirectory = "reportdirectory";
internal static readonly string CCReportTask = "ccreporttask";
internal static readonly string ReportBuildFile = "reportbuildfile";
internal static readonly string IsMultiModule = "ismultimodule";
}
internal static class PublishCodeCoverageEventProperties
{
internal static readonly string CodeCoverageTool = "codecoveragetool";
internal static readonly string SummaryFile = "summaryfile";
internal static readonly string ReportDirectory = "reportdirectory";
internal static readonly string AdditionalCodeCoverageFiles = "additionalcodecoveragefiles";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryCoalesceTests
{
public static IEnumerable<object[]> TestData()
{
foreach (bool useInterpreter in new bool[] { true, false })
{
yield return new object[] { new bool?[] { null, true, false }, new bool[] { true, false }, useInterpreter };
yield return new object[] { new byte?[] { null, 0, 1, byte.MaxValue }, new byte[] { 0, 1, byte.MaxValue }, useInterpreter };
yield return new object[] { new C[] { null, new C(), new D(), new D(0), new D(5) }, new C[] { null, new C(), new D(), new D(0), new D(5) }, useInterpreter };
yield return new object[] { new char?[] { null, '\0', '\b', 'A', '\uffff' }, new char[] { '\0', '\b', 'A', '\uffff' }, useInterpreter };
yield return new object[] { new D[] { null, new D(), new D(0), new D(5) }, new D[] { null, new D(), new D(0), new D(5) }, useInterpreter };
yield return new object[] { new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, useInterpreter };
yield return new object[] { new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } }, new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } }, useInterpreter };
yield return new object[] { new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, useInterpreter};
yield return new object[] { new E?[] { null, 0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, new E[] { 0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, useInterpreter };
yield return new object[] { new El?[] { null, 0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, new El[] { 0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, useInterpreter };
yield return new object[] { new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, useInterpreter };
yield return new object[] { new Func<object>[] { null, delegate () { return null; } }, new Func<object>[] { null, delegate () { return null; } }, useInterpreter };
yield return new object[] { new I[] { null, new C(), new D(), new D(0), new D(5) }, new I[] { null, new C(), new D(), new D(0), new D(5) }, useInterpreter };
yield return new object[] { new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) }, new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) }, useInterpreter };
yield return new object[] { new IEquatable<D>[] { null, new D(), new D(0), new D(5) }, new IEquatable<D>[] { null, new D(), new D(0), new D(5) }, useInterpreter };
yield return new object[] { new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }, new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, useInterpreter };
yield return new object[] { new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }, new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, useInterpreter };
yield return new object[] { new object[] { null, new object(), new C(), new D(3) }, new object[] { null, new object(), new C(), new D(3) }, useInterpreter };
yield return new object[] { new S?[] { null, default(S), new S() }, new S[] { default(S), new S() }, useInterpreter };
yield return new object[] { new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, useInterpreter };
yield return new object[] { new Sc?[] { null, default(Sc), new Sc(), new Sc(null) }, new Sc[] { default(Sc), new Sc(), new Sc(null) }, useInterpreter };
yield return new object[] { new Scs?[] { null, default(Scs), new Scs(), new Scs(null, new S()) }, new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) }, useInterpreter };
yield return new object[] { new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }, new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, useInterpreter };
yield return new object[] { new Sp?[] { null, default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) }, useInterpreter };
yield return new object[] { new Ss?[] { null, default(Ss), new Ss(), new Ss(new S()) }, new Ss[] { default(Ss), new Ss(), new Ss(new S()) }, useInterpreter };
yield return new object[] { new string[] { null, "", "a", "foo" }, new string[] { null, "", "a", "foo" }, useInterpreter };
yield return new object[] { new uint?[] { null, 0, 1, uint.MaxValue }, new uint[] { 0, 1, uint.MaxValue }, useInterpreter };
yield return new object[] { new ulong?[] { null, 0, 1, ulong.MaxValue }, new ulong[] { 0, 1, ulong.MaxValue }, useInterpreter };
yield return new object[] { new ushort?[] { null, 0, 1, ushort.MaxValue }, new ushort[] { 0, 1, ushort.MaxValue }, useInterpreter };
yield return new object[] { new string[] { null, "", "a", "foo" }, new string[] { null, "", "a", "foo" }, useInterpreter };
yield return new object[] { new bool?[] { null, true, false }, new bool?[] { null, true, false }, useInterpreter };
yield return new object[] { new byte?[] { null, 0, 1, byte.MaxValue }, new byte?[] { null, 0, 1, byte.MaxValue }, useInterpreter };
yield return new object[] { new char?[] { null, '\0', '\b', 'A', '\uffff' }, new char?[] { null, '\0', '\b', 'A', '\uffff' }, useInterpreter };
yield return new object[] { new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, useInterpreter };
yield return new object[] { new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, useInterpreter };
yield return new object[] { new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, useInterpreter };
yield return new object[] { new El?[] { null, (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, new El?[] { null, (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, useInterpreter };
yield return new object[] { new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, useInterpreter };
yield return new object[] { new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }, new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }, useInterpreter };
yield return new object[] { new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }, new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }, useInterpreter };
yield return new object[] { new S?[] { null, default(S), new S() }, new S?[] { null, default(S), new S() }, useInterpreter };
yield return new object[] { new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, useInterpreter };
yield return new object[] { new Sc?[] { null, default(Sc), new Sc(), new Sc(null) }, new Sc?[] { null, default(Sc), new Sc(), new Sc(null) }, useInterpreter };
yield return new object[] { new Scs?[] { null, default(Scs), new Scs(), new Scs(null, new S()) }, new Scs?[] { null, default(Scs), new Scs(), new Scs(null, new S()) }, useInterpreter };
yield return new object[] { new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }, new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }, useInterpreter };
yield return new object[] { new Sp?[] { null, default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp?[] { null, default(Sp), new Sp(), new Sp(5, 5.0) }, useInterpreter };
yield return new object[] { new Ss?[] { null, default(Ss), new Ss(), new Ss(new S()) }, new Ss?[] { null, default(Ss), new Ss(), new Ss(new S()) }, useInterpreter };
yield return new object[] { new uint?[] { null, 0, 1, uint.MaxValue }, new uint?[] { null, 0, 1, uint.MaxValue }, useInterpreter };
yield return new object[] { new ulong?[] { null, 0, 1, ulong.MaxValue }, new ulong?[] { null, 0, 1, ulong.MaxValue }, useInterpreter };
yield return new object[] { new ushort?[] { null, 0, 1, ushort.MaxValue }, new ushort?[] { null, 0, 1, ushort.MaxValue }, useInterpreter };
}
}
public static IEnumerable<object> ImplicitNumericConversionData()
{
foreach (bool useInterpreter in new bool[] { true, false })
{
yield return new object[] { new byte?[] { null, 1 }, new object[] { (byte)2, (short)3, (ushort)3, (int)4, (uint)4, (long)5, (ulong)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new sbyte?[] { null, 1 }, new object[] { (sbyte)2, (short)3, (int)4, (long)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new ushort?[] { null, 1 }, new object[] { (ushort)3, (int)4, (uint)4, (long)5, (ulong)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new short?[] { null, 1 }, new object[] { (short)3, (int)4, (long)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new uint?[] { null, 1 }, new object[] { (uint)4, (long)5, (ulong)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new int?[] { null, 1 }, new object[] { (int)4, (long)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new ulong?[] { null, 1 }, new object[] { (ulong)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new long?[] { null, 1 }, new object[] { (long)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new char?[] { null, 'a' }, new object[] { (ushort)3, (int)4, (uint)4, (long)5, (ulong)5, (float)3.14, (double)3.14, (decimal)49.95 }, useInterpreter };
yield return new object[] { new float?[] { null, 1F }, new object[] { (float)3.14, (double)3.14 }, useInterpreter };
yield return new object[] { new double?[] { null, 1D }, new object[] { (double)3.14 }, useInterpreter };
yield return new object[] { new decimal?[] { null, 1M }, new object[] { (decimal)49.95 }, useInterpreter };
}
}
[Theory]
[MemberData(nameof(TestData))]
public static void Coalesce(Array array1, Array array2, bool useInterpreter)
{
Type type1 = array1.GetType().GetElementType();
Type type2 = array2.GetType().GetElementType();
for (int i = 0; i < array1.Length; i++)
{
var value1 = array1.GetValue(i);
for (int j = 0; j < array2.Length; j++)
{
VerifyCoalesce(value1, type1, array2.GetValue(j), type2, useInterpreter);
}
}
}
[Theory]
[MemberData(nameof(ImplicitNumericConversionData))]
public static void ImplicitNumericConversions(Array array1, Array array2, bool useInterpreter)
{
Type type1 = array1.GetType().GetElementType();
for (int i = 0; i < array1.Length; i++)
{
var value1 = array1.GetValue(i);
for (int j = 0; j < array2.Length; j++)
{
var value2 = array2.GetValue(j);
var type2 = value2.GetType();
var result = value1 != null ? value1 : value2;
if (result.GetType() == typeof(char))
{
// ChangeType does not support conversion of char to float, double, or decimal,
// although these are classified as implicit numeric conversions, so we widen
// the value to Int32 first as a workaround
result = Convert.ChangeType(result, typeof(int));
}
var expected = Convert.ChangeType(result, type2);
VerifyCoalesce(value1, type1, value2, type2, useInterpreter, expected);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithClassRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionCoalesceHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectWithClassRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionCoalesceHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithSubClassRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithSubClassRestrictionCoalesceHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithClassAndNewRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionCoalesceHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectWithClassAndNewRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionCoalesceHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithSubClassAndNewRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithSubClassAndNewRestrictionCoalesceHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericEnumWithStructRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionCoalesceHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStructRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionCoalesceHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStringAndFieldWithStructRestrictionCoalesceTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionCoalesceHelper<Scs>(useInterpreter);
}
private static void CheckGenericWithClassRestrictionCoalesceHelper<Tc>(bool useInterpreter) where Tc : class
{
Tc[] array1 = new Tc[] { null, default(Tc) };
Tc[] array2 = new Tc[] { null, default(Tc) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
VerifyCoalesce(array1[i], typeof(Tc), array2[j], typeof(Tc), useInterpreter);
}
}
}
private static void CheckGenericWithSubClassRestrictionCoalesceHelper<TC>(bool useInterpreter) where TC : C
{
TC[] array1 = new TC[] { null, default(TC), (TC)new C() };
TC[] array2 = new TC[] { null, default(TC), (TC)new C() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
VerifyCoalesce(array1[i], typeof(TC), array2[j], typeof(TC), useInterpreter);
}
}
}
private static void CheckGenericWithClassAndNewRestrictionCoalesceHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
Tcn[] array1 = new Tcn[] { null, default(Tcn), new Tcn() };
Tcn[] array2 = new Tcn[] { null, default(Tcn), new Tcn() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
VerifyCoalesce(array1[i], typeof(Tcn), array2[j], typeof(Tcn), useInterpreter);
}
}
}
private static void CheckGenericWithSubClassAndNewRestrictionCoalesceHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
TCn[] array1 = new TCn[] { null, default(TCn), new TCn(), (TCn)new C() };
TCn[] array2 = new TCn[] { null, default(TCn), new TCn(), (TCn)new C() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
VerifyCoalesce(array1[i], typeof(TCn), array2[j], typeof(TCn), useInterpreter);
}
}
}
private static void CheckGenericWithStructRestrictionCoalesceHelper<Ts>(bool useInterpreter) where Ts : struct
{
Ts?[] array1 = new Ts?[] { null, default(Ts), new Ts() };
Ts[] array2 = new Ts[] { default(Ts), new Ts() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
VerifyCoalesce(array1[i], typeof(Ts?), array2[j], typeof(Ts), useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericEnumWithStructRestrictionCoalesce_NullableTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionCoalesce_NullableHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStructRestrictionCoalesce_NullableTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionCoalesce_NullableHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStringAndFieldWithStructRestrictionCoalesce_NullableTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionCoalesce_NullableHelper<Scs>(useInterpreter);
}
private static void CheckGenericWithStructRestrictionCoalesce_NullableHelper<Ts>(bool useInterpreter) where Ts : struct
{
Ts?[] array = new Ts?[] { null, default(Ts), new Ts() };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCoalesce(array[i], typeof(Ts?), array[j], typeof(Ts?), useInterpreter);
}
}
}
public static void VerifyCoalesce(object obj1, Type type1, object obj2, Type type2, bool useInterpreter, object expected = null)
{
BinaryExpression expression = Expression.Coalesce(Expression.Constant(obj1, type1), Expression.Constant(obj2, type2));
Delegate lambda = Expression.Lambda(expression).Compile(useInterpreter);
expected = expected ?? (obj1 == null ? obj2 : obj1);
Assert.Equal(expected, lambda.DynamicInvoke());
}
[Fact]
public static void BasicCoalesceExpressionTest()
{
int? i = 0;
double? d = 0;
var left = Expression.Constant(d, typeof(double?));
var right = Expression.Constant(i, typeof(int?));
Expression<Func<double?, int?>> conversion = x => 1 + (int?)x;
BinaryExpression actual = Expression.Coalesce(left, right, conversion);
Assert.Equal(conversion, actual.Conversion);
Assert.Equal(actual.Right.Type, actual.Type);
Assert.Equal(ExpressionType.Coalesce, actual.NodeType);
// Compile and evaluate with interpretation flag and without
// in case there are bugs in the compiler/interpreter.
Assert.Equal(2, conversion.Compile(false).Invoke(1.1));
Assert.Equal(2, conversion.Compile(true).Invoke(1.1));
}
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Coalesce(Expression.Constant(0, typeof(int?)), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.Coalesce(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.Coalesce(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.Coalesce(value, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.Coalesce(Expression.Constant(""), value));
}
[Theory]
[InlineData(null, "YY")]
[InlineData("abc", "abcdef")]
public static void Conversion_String(string parameter, string expected)
{
Expression<Func<string, string>> conversion = x => x + "def";
ParameterExpression parameterExpression = Expression.Parameter(typeof(string));
BinaryExpression coalescion = Expression.Coalesce(parameterExpression, Expression.Constant("YY"), conversion);
Func<string, string> result = Expression.Lambda<Func<string, string>>(coalescion, parameterExpression).Compile();
Assert.Equal(expected, result(parameter));
}
[Theory]
[InlineData(null, 5)]
[InlineData(5, 10)]
public static void Conversion_NullableInt(int? parameter, int? expected)
{
Expression<Func<int?, int?>> conversion = x => x * 2;
ParameterExpression parameterExpression = Expression.Parameter(typeof(int?));
BinaryExpression coalescion = Expression.Coalesce(parameterExpression, Expression.Constant(5, typeof(int?)), conversion);
Func<int?, int?> result = Expression.Lambda<Func<int?, int?>>(coalescion, parameterExpression).Compile();
Assert.Equal(expected, result(parameter));
}
[Fact]
public static void Left_NonNullValueType_ThrowsInvalidOperationException()
{
Expression<Func<int, int>> conversion = x => x * 2;
Assert.Throws<InvalidOperationException>(() => Expression.Coalesce(Expression.Constant(5), Expression.Constant(5)));
Assert.Throws<InvalidOperationException>(() => Expression.Coalesce(Expression.Constant(5), Expression.Constant(5), conversion));
}
[Fact]
public static void RightLeft_NonEquivilentTypes_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(null, () => Expression.Coalesce(Expression.Constant("abc"), Expression.Constant(5)));
}
public delegate void VoidDelegate();
[Fact]
public static void Conversion_VoidReturnType_ThrowsArgumentException()
{
LambdaExpression conversion = Expression.Lambda(typeof(VoidDelegate), Expression.Constant(""));
Assert.Throws<ArgumentException>("conversion", () => Expression.Coalesce(Expression.Constant(""), Expression.Constant(""), conversion));
}
[Fact]
public static void Conversion_NumberOfParameters_NotOne_ThrowsArgumentException()
{
Expression<Func<int, int, int>> moreThanOne = (x, y) => x * 2;
Expression<Func<int>> lessThanOne = () => 2;
Assert.Throws<ArgumentException>("conversion", () => Expression.Coalesce(Expression.Constant(""), Expression.Constant(""), moreThanOne));
Assert.Throws<ArgumentException>("conversion", () => Expression.Coalesce(Expression.Constant(""), Expression.Constant(""), lessThanOne));
}
[Fact]
public static void Conversion_ReturnTypeNotEquivilientToRightType_ThrowsInvalidOperationException()
{
Expression<Func<int?, int>> nullableNotEquivilent = x => x ?? 5;
Assert.Throws<InvalidOperationException>(() => Expression.Coalesce(Expression.Constant(5, typeof(int?)), Expression.Constant(5, typeof(int?)), nullableNotEquivilent));
Expression<Func<string, bool>> stringNotEquivilent = x => x == "";
Assert.Throws<InvalidOperationException>(() => Expression.Coalesce(Expression.Constant(""), Expression.Constant(""), stringNotEquivilent));
}
[Fact]
public static void Conversion_ParameterTypeNotEquivilentToLeftType_ThrowsInvalidOperationException()
{
Expression<Func<bool, string>> boolNotEquivilent = x => x.ToString();
Assert.Throws<InvalidOperationException>(() => Expression.Coalesce(Expression.Constant(""), Expression.Constant(""), boolNotEquivilent));
Assert.Throws<InvalidOperationException>(() => Expression.Coalesce(Expression.Constant(0, typeof(int?)), Expression.Constant(""), boolNotEquivilent));
}
[Fact]
public static void ToStringTest()
{
var e = Expression.Coalesce(Expression.Parameter(typeof(string), "a"), Expression.Parameter(typeof(string), "b"));
Assert.Equal("(a ?? b)", e.ToString());
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysRelAntecedentePaciente class.
/// </summary>
[Serializable]
public partial class SysRelAntecedentePacienteCollection : ActiveList<SysRelAntecedentePaciente, SysRelAntecedentePacienteCollection>
{
public SysRelAntecedentePacienteCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysRelAntecedentePacienteCollection</returns>
public SysRelAntecedentePacienteCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysRelAntecedentePaciente o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_RelAntecedentePaciente table.
/// </summary>
[Serializable]
public partial class SysRelAntecedentePaciente : ActiveRecord<SysRelAntecedentePaciente>, IActiveRecord
{
#region .ctors and Default Settings
public SysRelAntecedentePaciente()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysRelAntecedentePaciente(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysRelAntecedentePaciente(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysRelAntecedentePaciente(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_RelAntecedentePaciente", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdRelAntecedentePaciente = new TableSchema.TableColumn(schema);
colvarIdRelAntecedentePaciente.ColumnName = "idRelAntecedentePaciente";
colvarIdRelAntecedentePaciente.DataType = DbType.Int32;
colvarIdRelAntecedentePaciente.MaxLength = 0;
colvarIdRelAntecedentePaciente.AutoIncrement = true;
colvarIdRelAntecedentePaciente.IsNullable = false;
colvarIdRelAntecedentePaciente.IsPrimaryKey = true;
colvarIdRelAntecedentePaciente.IsForeignKey = false;
colvarIdRelAntecedentePaciente.IsReadOnly = false;
colvarIdRelAntecedentePaciente.DefaultSetting = @"";
colvarIdRelAntecedentePaciente.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdRelAntecedentePaciente);
TableSchema.TableColumn colvarIdAntecedente = new TableSchema.TableColumn(schema);
colvarIdAntecedente.ColumnName = "idAntecedente";
colvarIdAntecedente.DataType = DbType.Int32;
colvarIdAntecedente.MaxLength = 0;
colvarIdAntecedente.AutoIncrement = false;
colvarIdAntecedente.IsNullable = true;
colvarIdAntecedente.IsPrimaryKey = false;
colvarIdAntecedente.IsForeignKey = true;
colvarIdAntecedente.IsReadOnly = false;
colvarIdAntecedente.DefaultSetting = @"";
colvarIdAntecedente.ForeignKeyTableName = "Sys_Antecedente";
schema.Columns.Add(colvarIdAntecedente);
TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema);
colvarIdPaciente.ColumnName = "idPaciente";
colvarIdPaciente.DataType = DbType.Int32;
colvarIdPaciente.MaxLength = 0;
colvarIdPaciente.AutoIncrement = false;
colvarIdPaciente.IsNullable = true;
colvarIdPaciente.IsPrimaryKey = false;
colvarIdPaciente.IsForeignKey = true;
colvarIdPaciente.IsReadOnly = false;
colvarIdPaciente.DefaultSetting = @"";
colvarIdPaciente.ForeignKeyTableName = "Sys_Paciente";
schema.Columns.Add(colvarIdPaciente);
TableSchema.TableColumn colvarIdClasificacion = new TableSchema.TableColumn(schema);
colvarIdClasificacion.ColumnName = "idClasificacion";
colvarIdClasificacion.DataType = DbType.Int32;
colvarIdClasificacion.MaxLength = 0;
colvarIdClasificacion.AutoIncrement = false;
colvarIdClasificacion.IsNullable = true;
colvarIdClasificacion.IsPrimaryKey = false;
colvarIdClasificacion.IsForeignKey = true;
colvarIdClasificacion.IsReadOnly = false;
colvarIdClasificacion.DefaultSetting = @"";
colvarIdClasificacion.ForeignKeyTableName = "Rem_Clasificacion";
schema.Columns.Add(colvarIdClasificacion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_RelAntecedentePaciente",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdRelAntecedentePaciente")]
[Bindable(true)]
public int IdRelAntecedentePaciente
{
get { return GetColumnValue<int>(Columns.IdRelAntecedentePaciente); }
set { SetColumnValue(Columns.IdRelAntecedentePaciente, value); }
}
[XmlAttribute("IdAntecedente")]
[Bindable(true)]
public int? IdAntecedente
{
get { return GetColumnValue<int?>(Columns.IdAntecedente); }
set { SetColumnValue(Columns.IdAntecedente, value); }
}
[XmlAttribute("IdPaciente")]
[Bindable(true)]
public int? IdPaciente
{
get { return GetColumnValue<int?>(Columns.IdPaciente); }
set { SetColumnValue(Columns.IdPaciente, value); }
}
[XmlAttribute("IdClasificacion")]
[Bindable(true)]
public int? IdClasificacion
{
get { return GetColumnValue<int?>(Columns.IdClasificacion); }
set { SetColumnValue(Columns.IdClasificacion, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a SysAntecedente ActiveRecord object related to this SysRelAntecedentePaciente
///
/// </summary>
public DalSic.SysAntecedente SysAntecedente
{
get { return DalSic.SysAntecedente.FetchByID(this.IdAntecedente); }
set { SetColumnValue("idAntecedente", value.IdAntecedente); }
}
/// <summary>
/// Returns a RemClasificacion ActiveRecord object related to this SysRelAntecedentePaciente
///
/// </summary>
public DalSic.RemClasificacion RemClasificacion
{
get { return DalSic.RemClasificacion.FetchByID(this.IdClasificacion); }
set { SetColumnValue("idClasificacion", value.IdClasificacion); }
}
/// <summary>
/// Returns a SysPaciente ActiveRecord object related to this SysRelAntecedentePaciente
///
/// </summary>
public DalSic.SysPaciente SysPaciente
{
get { return DalSic.SysPaciente.FetchByID(this.IdPaciente); }
set { SetColumnValue("idPaciente", value.IdPaciente); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int? varIdAntecedente,int? varIdPaciente,int? varIdClasificacion)
{
SysRelAntecedentePaciente item = new SysRelAntecedentePaciente();
item.IdAntecedente = varIdAntecedente;
item.IdPaciente = varIdPaciente;
item.IdClasificacion = varIdClasificacion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdRelAntecedentePaciente,int? varIdAntecedente,int? varIdPaciente,int? varIdClasificacion)
{
SysRelAntecedentePaciente item = new SysRelAntecedentePaciente();
item.IdRelAntecedentePaciente = varIdRelAntecedentePaciente;
item.IdAntecedente = varIdAntecedente;
item.IdPaciente = varIdPaciente;
item.IdClasificacion = varIdClasificacion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdRelAntecedentePacienteColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdAntecedenteColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdPacienteColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdClasificacionColumn
{
get { return Schema.Columns[3]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdRelAntecedentePaciente = @"idRelAntecedentePaciente";
public static string IdAntecedente = @"idAntecedente";
public static string IdPaciente = @"idPaciente";
public static string IdClasificacion = @"idClasificacion";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.